text:
package com.quan404.recordvideotomp4;

import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.EGLExt;
import android.opengl.EGLSurface;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * Record the camera (no audio) to a MP4 file in sdcard.
 * Basically, we can use MediaRecorder to this task.
 * This example is for editing of the video as MediaCodec is encoding the video.
 *

 * Required: Android 4.3 ( API 18 )
 *

 * Output: /sdcard/recordvideo.mp4
 */
public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    private static final boolean DEBUG = true;
    // Encoder Parameters
    private static final String MIME_TYPE = "video/avc";    // H.264 Advanced Video Coding
    private static final int FRAME_WIDTH = 640;             // 640px
    private static final int FRAME_HEIGHT = 480;            // 480px
    private static final int FRAME_RATE = 30;               // 30fps
    private static final int IFRAME_INTERVAL = 5;           // 5 seconds between I-frames
    private static final long DURATION_SEC = 8;             // 8 seconds of video
    private static final int BITRATE = 6000000;            // 6000000 Mbps
    /**
     * Shader functions for frame editing
     */
    // Fragment shader that swaps color channels around.
    private static final String SWAPPED_FRAGMENT_SHADER =
            "#extension GL_OES_EGL_image_external : require\n" +
                    "precision mediump float;\n" +
                    "varying vec2 vTextureCoord;\n" +
                    "uniform samplerExternalOES sTexture;\n" +
                    "void main() {\n" +
                    "  gl_FragColor = texture2D(sTexture, vTextureCoord).gbra;\n" +
                    "}\n";
    /**
     * Get the sdcard path.
     * Permission: WRITE_EXTERNAL_STORAGE
     */
    private File OUTPUT_DIR = Environment.getExternalStorageDirectory();
    /**
     * Encoder & Muxer
     */
    private MediaCodec mEncoder;
    private MediaMuxer mMuxer;
    private int mTrackIndex;
    private boolean mMuxerStarted;
    private CodecInputSurface mInputSurface;
    private MediaCodec.BufferInfo mBufferInfo;
    /**
     * Camera Stuff
     */
    private Camera mCamera;
    private SurfaceTextureManager mStManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.recordVideoToMP4);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (DEBUG) {
                    Log.d(TAG, "Button recordVideoToMP4 onClick");
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        prepareCamera(FRAME_WIDTH, FRAME_HEIGHT);
                        prepareEncoder(FRAME_WIDTH, FRAME_HEIGHT, BITRATE);
                        mInputSurface.makeCurrent();
                        prepareSurfaceTexture();

                        mCamera.startPreview();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "Start recording", Toast.LENGTH_LONG).show();
                            }
                        });

                        long startWhen = System.nanoTime();
                        long desiredEnd = startWhen + DURATION_SEC * 1000000000L;
                        SurfaceTexture st = mStManager.getSurfaceTexture();
                        int frameCount = 0;

                        while (System.nanoTime() < desiredEnd) {
                            // Feed any pending encoder output into the muxer.
                            drainEncoder(false);

                            // Switch up the colors every 15 frames.  Besides demonstrating the use of
                            // fragment shaders for video editing, this provides a visual indication of
                            // the frame rate: if the camera is capturing at 15fps, the colors will change
                            // once per second.
                            if ((frameCount % 15) == 0) {
                                Log.d(TAG, "((frameCount % 15) == 0): change color");

                                String fragmentShader = null;
                                if ((frameCount & 0x01) != 0) {
                                    fragmentShader = SWAPPED_FRAGMENT_SHADER;
                                }
                                mStManager.changeFragmentShader(fragmentShader);
                            }
                            frameCount++;

                            // Acquire a new frame of input, and render it to the Surface.  If we had a
                            // GLSurfaceView we could switch EGL contexts and call drawImage() a second
                            // time to render it on screen.  The texture can be shared between contexts by
                            // passing the GLSurfaceView's EGLContext as eglCreateContext()'s share_context
                            // argument.
                            mStManager.awaitNewImage();
                            mStManager.drawImage();

                            // Set the presentation time stamp from the SurfaceTexture's time stamp.  This
                            // will be used by MediaMuxer to set the PTS in the video.
                            if (DEBUG) {
                                Log.d(TAG, "present: " +
                                        ((st.getTimestamp() - startWhen) / 1000000.0) + "ms");
                            }
                            mInputSurface.setPresentationTime(st.getTimestamp());

                            // Submit it to the encoder.  The eglSwapBuffers call will block if the input
                            // is full, which would be bad if it stayed full until we dequeued an output
                            // buffer (which we can't do, since we're stuck here).  So long as we fully drain
                            // the encoder before supplying additional input, the system guarantees that we
                            // can supply another frame without blocking.
                            if (DEBUG) Log.d(TAG, "sending frame to encoder");
                            mInputSurface.swapBuffers();
                        }

                        // send end-of-stream to encoder, and drain remaining output
                        drainEncoder(true);
                    }
                }).start();

            }
        });
    }

    @Override
    protected void onStop() {
        releaseCamera();
        releaseEncoder();
        releaseSurfaceTexture();
        super.onStop();
    }

    /**
     * Camera functions
     */
    private void prepareCamera(int expectedWidth, int expectedHeight) {
        if (DEBUG) {
            Log.d(TAG, "prepareCamera");
        }

        try {
            // Open front camera
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    mCamera = Camera.open(i);
                }
            }

            // Else open rear camera
            if (mCamera == null) {
                mCamera = Camera.open();
            }

            // Else throw an Error
            if (mCamera == null) {
                throw new RuntimeException("Can not open any camera");
            }

            // Select a preview size that match the expectedWidth & expectedHeight
            Camera.Parameters params = mCamera.getParameters();
            choosePreviewSize(params, expectedWidth, expectedHeight);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void choosePreviewSize(Camera.Parameters params, int width, int height) {
        Camera.Size ppsfv = params.getPreferredPreviewSizeForVideo();

        if (DEBUG) {
            Log.d(TAG, "choosePreviewSize: PreferredPreviewSize width = " + ppsfv.width + " height = " + ppsfv.height);
        }

        for (Camera.Size size : params.getSupportedPreviewSizes()) {
            if (size.width == width && size.height == height) {
                if (DEBUG)
                    Log.d(TAG, "choosePreviewSize: setPreviewSize to " + width + " " + height);
                params.setPreviewSize(width, height);
                return;
            }
        }

        Log.d(TAG, "choosePreviewSize: Unable to set preview size to " + width + " " + height + " revert to " + ppsfv.width + " " + ppsfv.height);
        if (ppsfv != null) {
            params.setPreviewSize(ppsfv.width, ppsfv.height);
        }
    }

    private void releaseCamera() {
        if (DEBUG) {
            Log.d(TAG, "releaseCamera");
        }
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    /**
     * Encoder functions
     */
    private void prepareEncoder(int width, int height, int bitRate) {
        if (DEBUG) {
            Log.d(TAG, "prepareEncoder");
        }

        mBufferInfo = new MediaCodec.BufferInfo();
        MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, width, height);

        // Set some properties.  Failing to specify some of these can cause the MediaCodec
        // configure() call to throw an unhelpful exception.
        format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
                MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
        format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
        format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
        format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);

        if (DEBUG)
            Log.d(TAG, "format: " + format);

        // Create a MediaCodec encoder, and configure it with our format.  Get a Surface
        // we can use for input and wrap it with a class that handles the EGL work.
        //
        // If you want to have two EGL contexts -- one for display, one for recording --
        // you will likely want to defer instantiation of CodecInputSurface until after the
        // "display" EGL context is created, then modify the eglCreateContext call to
        // take eglGetCurrentContext() as the share_context argument.
        try {
            mEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
            mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
            mInputSurface = new CodecInputSurface(mEncoder.createInputSurface());
            mEncoder.start();
        } catch (IOException ioe) {
            throw new RuntimeException("MediaCodec creation failed", ioe);
        }

        // Output filename.  Ideally this would use Context.getFilesDir() rather than a
        // hard-coded output directory.
        String outputPath = new File(OUTPUT_DIR,
                "test." + width + "x" + height + ".mp4").toString();
        Log.i(TAG, "Output file is " + outputPath);

        // Create a MediaMuxer.  We can't add the video track and start() the muxer here,
        // because our MediaFormat doesn't have the Magic Goodies.  These can only be
        // obtained from the encoder after it has started processing data.
        //
        // We're not actually interested in multiplexing audio.  We just want to convert
        // the raw H.264 elementary stream we get from MediaCodec into a .mp4 file.
        try {
            mMuxer = new MediaMuxer(outputPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
        } catch (IOException ioe) {
            throw new RuntimeException("MediaMuxer creation failed", ioe);
        }

        mTrackIndex = -1;
        mMuxerStarted = false;
    }

    /**
     * Releases encoder resources.
     */
    private void releaseEncoder() {
        if (DEBUG) Log.d(TAG, "releasing encoder objects");
        if (mEncoder != null) {
            mEncoder.stop();
            mEncoder.release();
            mEncoder = null;
        }
        if (mInputSurface != null) {
            mInputSurface.release();
            mInputSurface = null;
        }
        if (mMuxer != null) {
            try {
                mMuxer.stop();
                mMuxer.release();
                mMuxer = null;
            } catch (Exception e) {
                Log.e(TAG, "You started a Muxer but haven't fed any data into it");
                e.printStackTrace();
            }
        }
    }

    /**
     * Extracts all pending data from the encoder and forwards it to the muxer.
     *

     * If endOfStream is not set, this returns when there is no more data to drain.  If it
     * is set, we send EOS to the encoder, and then iterate until we see EOS on the output.
     * Calling this with endOfStream set should be done once, right before stopping the muxer.
     *

     * We're just using the muxer to get a .mp4 file (instead of a raw H.264 stream).  We're
     * not recording audio.
     */
    private void drainEncoder(boolean endOfStream) {
        final int TIMEOUT_USEC = 10000;
        if (DEBUG) Log.d(TAG, "drainEncoder(" + endOfStream + ")");

        if (endOfStream) {
            if (DEBUG) Log.d(TAG, "sending EOS to encoder");
            mEncoder.signalEndOfInputStream();
        }

        ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers();
        while (true) {
            int encoderStatus = mEncoder.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
            if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
                // no output available yet
                if (!endOfStream) {
                    break;      // out of while
                } else {
                    if (DEBUG) Log.d(TAG, "no output available, spinning to await EOS");
                }
            } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                // not expected for an encoder
                encoderOutputBuffers = mEncoder.getOutputBuffers();
            } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                // should happen before receiving buffers, and should only happen once
                if (mMuxerStarted) {
                    throw new RuntimeException("format changed twice");
                }
                MediaFormat newFormat = mEncoder.getOutputFormat();
                Log.d(TAG, "encoder output format changed: " + newFormat);

                // now that we have the Magic Goodies, start the muxer
                mTrackIndex = mMuxer.addTrack(newFormat);
                mMuxer.start();
                mMuxerStarted = true;
            } else if (encoderStatus < 0) {
                Log.w(TAG, "unexpected result from encoder.dequeueOutputBuffer: " +
                        encoderStatus);
                // let's ignore it
            } else {
                ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
                if (encodedData == null) {
                    throw new RuntimeException("encoderOutputBuffer " + encoderStatus +
                            " was null");
                }

                if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                    // The codec config data was pulled out and fed to the muxer when we got
                    // the INFO_OUTPUT_FORMAT_CHANGED status.  Ignore it.
                    if (DEBUG) Log.d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG");
                    mBufferInfo.size = 0;
                }

                if (mBufferInfo.size != 0) {
                    if (!mMuxerStarted) {
                        throw new RuntimeException("muxer hasn't started");
                    }

                    // adjust the ByteBuffer values to match BufferInfo (not needed?)
                    encodedData.position(mBufferInfo.offset);
                    encodedData.limit(mBufferInfo.offset + mBufferInfo.size);

                    mMuxer.writeSampleData(mTrackIndex, encodedData, mBufferInfo);
                    if (DEBUG) Log.d(TAG, "sent " + mBufferInfo.size + " bytes to muxer");
                }

                mEncoder.releaseOutputBuffer(encoderStatus, false);

                if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                    if (!endOfStream) {
                        Log.w(TAG, "reached end of stream unexpectedly");
                    } else {
                        if (DEBUG) Log.d(TAG, "end of stream reached");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "End Of Stream Reached. Save the video to sdcard", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    break;      // out of while
                }
            }
        }
    }

    /**
     * Configures SurfaceTexture for camera preview.  Initializes mStManager, and sets the
     * associated SurfaceTexture as the Camera's "preview texture".
     *

     * Configure the EGL surface that will be used for output before calling here.
     */
    private void prepareSurfaceTexture() {
        mStManager = new SurfaceTextureManager();
        SurfaceTexture st = mStManager.getSurfaceTexture();
        try {
            mCamera.setPreviewTexture(st);
        } catch (IOException ioe) {
            throw new RuntimeException("setPreviewTexture failed", ioe);
        }
    }

    /**
     * SurfaceTexture functions
     */

    /**
     * Releases the SurfaceTexture.
     */
    private void releaseSurfaceTexture() {
        if (mStManager != null) {
            mStManager.release();
            mStManager = null;
        }
    }

    /**
     * Holds state associated with a Surface used for MediaCodec encoder input.
     *

     * The constructor takes a Surface obtained from MediaCodec.createInputSurface(), and uses
     * that to create an EGL window surface. Calls to eglSwapBuffers() cause a frame of data to
     * be sent to the video encoder.
     *

     * This object owns the Surface -- releasing this will release the Surface too.
     */
    private static class CodecInputSurface {

        private static final int EGL_RECORDABLE_ANDROID = 0x3142;

        private EGLDisplay mEGLDisplay = EGL14.EGL_NO_DISPLAY;
        private EGLContext mEGLContext = EGL14.EGL_NO_CONTEXT;
        private EGLSurface mEGLSurface = EGL14.EGL_NO_SURFACE;

        private Surface mSurface;

        /**
         * Creates a CodecInputSurface from a Surface.
         */
        public CodecInputSurface(Surface surface) {
            if (surface == null) {
                throw new NullPointerException();
            }
            mSurface = surface;

            eglSetup();
        }

        /**
         * Prepares EGL.  We want a GLES 2.0 context and a surface that supports recording.
         */
        private void eglSetup() {
            mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
            if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) {
                throw new RuntimeException("unable to get EGL14 display");
            }
            int[] version = new int[2];
            if (!EGL14.eglInitialize(mEGLDisplay, version, 0, version, 1)) {
                throw new RuntimeException("unable to initialize EGL14");
            }

            // Configure EGL for recording and OpenGL ES 2.0.
            int[] attribList = {
                    EGL14.EGL_RED_SIZE, 8,
                    EGL14.EGL_GREEN_SIZE, 8,
                    EGL14.EGL_BLUE_SIZE, 8,
                    EGL14.EGL_ALPHA_SIZE, 8,
                    EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
                    EGL_RECORDABLE_ANDROID, 1,
                    EGL14.EGL_NONE
            };
            EGLConfig[] configs = new EGLConfig[1];
            int[] numConfigs = new int[1];
            EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, configs, 0, configs.length,
                    numConfigs, 0);
            checkEglError("eglCreateContext RGB888+recordable ES2");

            // Configure context for OpenGL ES 2.0.
            int[] attrib_list = {
                    EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
                    EGL14.EGL_NONE
            };
            mEGLContext = EGL14.eglCreateContext(mEGLDisplay, configs[0], EGL14.EGL_NO_CONTEXT,
                    attrib_list, 0);
            checkEglError("eglCreateContext");

            // Create a window surface, and attach it to the Surface we received.
            int[] surfaceAttribs = {
                    EGL14.EGL_NONE
            };
            mEGLSurface = EGL14.eglCreateWindowSurface(mEGLDisplay, configs[0], mSurface,
                    surfaceAttribs, 0);
            checkEglError("eglCreateWindowSurface");
        }

        /**
         * Discards all resources held by this class, notably the EGL context.  Also releases the
         * Surface that was passed to our constructor.
         */
        public void release() {
            if (mEGLDisplay != EGL14.EGL_NO_DISPLAY) {
                EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE,
                        EGL14.EGL_NO_CONTEXT);
                EGL14.eglDestroySurface(mEGLDisplay, mEGLSurface);
                EGL14.eglDestroyContext(mEGLDisplay, mEGLContext);
                EGL14.eglReleaseThread();
                EGL14.eglTerminate(mEGLDisplay);
            }
            mSurface.release();

            mEGLDisplay = EGL14.EGL_NO_DISPLAY;
            mEGLContext = EGL14.EGL_NO_CONTEXT;
            mEGLSurface = EGL14.EGL_NO_SURFACE;

            mSurface = null;
        }

        /**
         * Makes our EGL context and surface current.
         */
        public void makeCurrent() {
            EGL14.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
            checkEglError("eglMakeCurrent");
        }

        /**
         * Calls eglSwapBuffers.  Use this to "publish" the current frame.
         */
        public boolean swapBuffers() {
            boolean result = EGL14.eglSwapBuffers(mEGLDisplay, mEGLSurface);
            checkEglError("eglSwapBuffers");
            return result;
        }

        /**
         * Sends the presentation time stamp to EGL.  Time is expressed in nanoseconds.
         */
        public void setPresentationTime(long nsecs) {
            EGLExt.eglPresentationTimeANDROID(mEGLDisplay, mEGLSurface, nsecs);
            checkEglError("eglPresentationTimeANDROID");
        }

        /**
         * Checks for EGL errors.  Throws an exception if one is found.
         */
        private void checkEglError(String msg) {
            int error;
            if ((error = EGL14.eglGetError()) != EGL14.EGL_SUCCESS) {
                throw new RuntimeException(msg + ": EGL error: 0x" + Integer.toHexString(error));
            }
        }
    }

    /**
     * Manages a SurfaceTexture.  Creates SurfaceTexture and TextureRender objects, and provides
     * functions that wait for frames and render them to the current EGL surface.
     *

     * The SurfaceTexture can be passed to Camera.setPreviewTexture() to receive camera output.
     */
    private static class SurfaceTextureManager implements SurfaceTexture.OnFrameAvailableListener {
        private SurfaceTexture mSurfaceTexture;
        private STextureRender mTextureRender;

        private Object mFrameSyncObject = new Object();     // guards mFrameAvailable
        private boolean mFrameAvailable;

        /**
         * Creates instances of TextureRender and SurfaceTexture.
         */
        public SurfaceTextureManager() {
            mTextureRender = new STextureRender();
            mTextureRender.surfaceCreated();

            if (DEBUG) Log.d(TAG, "textureID=" + mTextureRender.getTextureId());
            mSurfaceTexture = new SurfaceTexture(mTextureRender.getTextureId());

            // This doesn't work if this object is created on the thread that CTS started for
            // these test cases.
            //
            // The CTS-created thread has a Looper, and the SurfaceTexture constructor will
            // create a Handler that uses it.  The "frame available" message is delivered
            // there, but since we're not a Looper-based thread we'll never see it.  For
            // this to do anything useful, OutputSurface must be created on a thread without
            // a Looper, so that SurfaceTexture uses the main application Looper instead.
            //
            // Java language note: passing "this" out of a constructor is generally unwise,
            // but we should be able to get away with it here.
            mSurfaceTexture.setOnFrameAvailableListener(this);
        }

        public void release() {
            // this causes a bunch of warnings that appear harmless but might confuse someone:
            //  W BufferQueue: [unnamed-3997-2] cancelBuffer: BufferQueue has been abandoned!
            //mSurfaceTexture.release();

            mTextureRender = null;
            mSurfaceTexture = null;
        }

        /**
         * Returns the SurfaceTexture.
         */
        public SurfaceTexture getSurfaceTexture() {
            return mSurfaceTexture;
        }

        /**
         * Replaces the fragment shader.
         */
        public void changeFragmentShader(String fragmentShader) {
            mTextureRender.changeFragmentShader(fragmentShader);
        }

        /**
         * Latches the next buffer into the texture.  Must be called from the thread that created
         * the OutputSurface object.
         */
        public void awaitNewImage() {
            final int TIMEOUT_MS = 2500;

            synchronized (mFrameSyncObject) {
                while (!mFrameAvailable) {
                    try {
                        // Wait for onFrameAvailable() to signal us.  Use a timeout to avoid
                        // stalling the test if it doesn't arrive.
                        mFrameSyncObject.wait(TIMEOUT_MS);
                        if (!mFrameAvailable) {
                            // TODO: if "spurious wakeup", continue while loop
                            throw new RuntimeException("Camera frame wait timed out");
                        }
                    } catch (InterruptedException ie) {
                        // shouldn't happen
                        throw new RuntimeException(ie);
                    }
                }
                mFrameAvailable = false;
            }

            // Latch the data.
            mTextureRender.checkGlError("before updateTexImage");
            mSurfaceTexture.updateTexImage();
        }

        /**
         * Draws the data from SurfaceTexture onto the current EGL surface.
         */
        public void drawImage() {
            mTextureRender.drawFrame(mSurfaceTexture);
        }

        @Override
        public void onFrameAvailable(SurfaceTexture surfaceTexture) {
            if (DEBUG) Log.d(TAG, "new frame available");
            synchronized (mFrameSyncObject) {
                if (mFrameAvailable) {
                    throw new RuntimeException("mFrameAvailable already set, frame could be dropped");
                }
                mFrameAvailable = true;
                mFrameSyncObject.notifyAll();
            }
        }
    }

    /**
     * Code for rendering a texture onto a surface using OpenGL ES 2.0.
     */
    private static class STextureRender {
        private static final int FLOAT_SIZE_BYTES = 4;
        private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
        private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
        private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
        private static final String VERTEX_SHADER =
                "uniform mat4 uMVPMatrix;\n" +
                        "uniform mat4 uSTMatrix;\n" +
                        "attribute vec4 aPosition;\n" +
                        "attribute vec4 aTextureCoord;\n" +
                        "varying vec2 vTextureCoord;\n" +
                        "void main() {\n" +
                        "    gl_Position = uMVPMatrix * aPosition;\n" +
                        "    vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
                        "}\n";
        private static final String FRAGMENT_SHADER =
                "#extension GL_OES_EGL_image_external : require\n" +
                        "precision mediump float;\n" +      // highp here doesn't seem to matter
                        "varying vec2 vTextureCoord;\n" +
                        "uniform samplerExternalOES sTexture;\n" +
                        "void main() {\n" +
                        "    gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
                        "}\n";
        private final float[] mTriangleVerticesData = {
                // X, Y, Z, U, Vo
                -1.0f, -1.0f, 0, 0.f, 0.f,
                1.0f, -1.0f, 0, 1.f, 0.f,
                -1.0f, 1.0f, 0, 0.f, 1.f,
                1.0f, 1.0f, 0, 1.f, 1.f,
        };
        private FloatBuffer mTriangleVertices;
        private float[] mMVPMatrix = new float[16];
        private float[] mSTMatrix = new float[16];

        private int mProgram;
        private int mTextureID = -12345;
        private int muMVPMatrixHandle;
        private int muSTMatrixHandle;
        private int maPositionHandle;
        private int maTextureHandle;

        public STextureRender() {
            mTriangleVertices = ByteBuffer.allocateDirect(
                    mTriangleVerticesData.length * FLOAT_SIZE_BYTES)
                    .order(ByteOrder.nativeOrder()).asFloatBuffer();
            mTriangleVertices.put(mTriangleVerticesData).position(0);

            Matrix.setIdentityM(mSTMatrix, 0);
        }

        public static void checkLocation(int location, String label) {
            if (location < 0) {
                throw new RuntimeException("Unable to locate '" + label + "' in program");
            }
        }

        public int getTextureId() {
            return mTextureID;
        }

        public void drawFrame(SurfaceTexture st) {
            checkGlError("onDrawFrame start");
            st.getTransformMatrix(mSTMatrix);

            // (optional) clear to green so we can see if we're failing to set pixels
            GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
            GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

            GLES20.glUseProgram(mProgram);
            checkGlError("glUseProgram");

            GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
            GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID);

            mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
            GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
            checkGlError("glVertexAttribPointer maPosition");
            GLES20.glEnableVertexAttribArray(maPositionHandle);
            checkGlError("glEnableVertexAttribArray maPositionHandle");

            mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
            GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false,
                    TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
            checkGlError("glVertexAttribPointer maTextureHandle");
            GLES20.glEnableVertexAttribArray(maTextureHandle);
            checkGlError("glEnableVertexAttribArray maTextureHandle");

            Matrix.setIdentityM(mMVPMatrix, 0);
            GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
            GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);

            GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
            checkGlError("glDrawArrays");

            // IMPORTANT: on some devices, if you are sharing the external texture between two
            // contexts, one context may not see updates to the texture unless you un-bind and
            // re-bind it.  If you're not using shared EGL contexts, you don't need to bind
            // texture 0 here.
            GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
        }

        /**
         * Initializes GL state.  Call this after the EGL surface has been created and made current.
         */
        public void surfaceCreated() {
            mProgram = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
            if (mProgram == 0) {
                throw new RuntimeException("failed creating program");
            }
            maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
            checkLocation(maPositionHandle, "aPosition");
            maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
            checkLocation(maTextureHandle, "aTextureCoord");

            muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
            checkLocation(muMVPMatrixHandle, "uMVPMatrix");
            muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
            checkLocation(muSTMatrixHandle, "uSTMatrix");

            int[] textures = new int[1];
            GLES20.glGenTextures(1, textures, 0);

            mTextureID = textures[0];
            GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID);
            checkGlError("glBindTexture mTextureID");

            GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
                    GLES20.GL_NEAREST);
            GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
                    GLES20.GL_LINEAR);
            GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
                    GLES20.GL_CLAMP_TO_EDGE);
            GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
                    GLES20.GL_CLAMP_TO_EDGE);
            checkGlError("glTexParameter");
        }

        /**
         * Replaces the fragment shader.  Pass in null to reset to default.
         */
        public void changeFragmentShader(String fragmentShader) {
            if (fragmentShader == null) {
                fragmentShader = FRAGMENT_SHADER;
            }
            GLES20.glDeleteProgram(mProgram);
            mProgram = createProgram(VERTEX_SHADER, fragmentShader);
            if (mProgram == 0) {
                throw new RuntimeException("failed creating program");
            }
        }

        private int loadShader(int shaderType, String source) {
            int shader = GLES20.glCreateShader(shaderType);
            checkGlError("glCreateShader type=" + shaderType);
            GLES20.glShaderSource(shader, source);
            GLES20.glCompileShader(shader);
            int[] compiled = new int[1];
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
            if (compiled[0] == 0) {
                Log.e(TAG, "Could not compile shader " + shaderType + ":");
                Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader));
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
            return shader;
        }

        private int createProgram(String vertexSource, String fragmentSource) {
            int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
            if (vertexShader == 0) {
                return 0;
            }
            int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
            if (pixelShader == 0) {
                return 0;
            }

            int program = GLES20.glCreateProgram();
            if (program == 0) {
                Log.e(TAG, "Could not create program");
            }
            GLES20.glAttachShader(program, vertexShader);
            checkGlError("glAttachShader");
            GLES20.glAttachShader(program, pixelShader);
            checkGlError("glAttachShader");
            GLES20.glLinkProgram(program);
            int[] linkStatus = new int[1];
            GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
            if (linkStatus[0] != GLES20.GL_TRUE) {
                Log.e(TAG, "Could not link program: ");
                Log.e(TAG, GLES20.glGetProgramInfoLog(program));
                GLES20.glDeleteProgram(program);
                program = 0;
            }
            return program;
        }

        public void checkGlError(String op) {
            int error;
            while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
                Log.e(TAG, op + ": glError " + error);
                throw new RuntimeException(op + ": glError " + error);
            }
        }
    }
}


text:
package com.facebook.buck.message_ipc;

import com.google.common.base.Preconditions;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import javax.annotation.Nullable;

/**
 * Connection is a wrapper around MessageTransport class that transforms function calls into
 * messages.
 *
 *
You may specify your own interface, and call methods of that interface on an object that
 * Connection exposes to you via getRemoteObjectProxy(). Call method calls on proxy object will be
 * translated into InvocationMessage objects and sent via assigned MessageTransport object.
 *
 *
Example:
 *
 *
private interface RemoteInterface { String doString(int arg1, boolean arg2); }
 *
 *
MessageSerializer messageSerializer = new MessageSerializer(new ObjectMapper()); // imagine
 * you have workerProcess ready to use MessageTransport messageTransport = new
 * MessageTransport(workerProcess, messageSerializer);
 *
 *
Connection<RemoteInterface> connection = new Connection<>(messageTransport);
 * connection.setRemoteInterface(RemoteInterface.class, RemoteInterface.class.getClassLoader());
 * String result = connection.getRemoteObjectProxy().doString(42, true); // process result
 */
public class Connection<REMOTE> implements AutoCloseable {
  private final MessageTransport messageTransport;

  @Nullable private REMOTE remoteObjectProxy;

  private boolean isClosed = false;

  public Connection(MessageTransport messageTransport) {
    this.messageTransport = messageTransport;
  }

  @SuppressWarnings("unchecked")
  public void setRemoteInterface(Class<REMOTE> remoteInterface, ClassLoader classLoader) {
    checkNotClose();
    InvocationHandler invocationHandler =
        (proxy, method, args) -> {
          InvocationMessage invocation =
              new InvocationMessage(method.getName(), Arrays.asList(args));
          ReturnResultMessage response = messageTransport.sendMessageAndWaitForResponse(invocation);
          return response.getValue();
        };
    this.remoteObjectProxy =
        (REMOTE)
            Proxy.newProxyInstance(classLoader, new Class[] {remoteInterface}, invocationHandler);
  }

  public REMOTE getRemoteObjectProxy() {
    checkNotClose();
    Preconditions.checkNotNull(
        remoteObjectProxy, "You must set remote interface before obtaining remote object proxy.");
    return remoteObjectProxy;
  }

  @Override
  public void close() {
    checkNotClose();
    isClosed = true;
    messageTransport.close();
    remoteObjectProxy = null;
  }

  private void checkNotClose() {
    Preconditions.checkState(
        !isClosed,
        "%s <%d> is already closed",
        this.getClass().getSimpleName(),
        System.identityHashCode(this));
  }
}

redpajama_set_name: RedPajamaGithub


text:
//-----------------------------------------------------------------------------
// <copyright file="ActionAliasAttribute.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team.  See LICENSE.txt.  This file is
//   subject to the Microsoft Public License.  All other rights reserved.
// </copyright>
//
//   An action alias attribute.
//
//-----------------------------------------------------------------------------

namespace WheelMUD.Core.Attributes
{
    using System;

    /// An action alias attribute.
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class ActionAliasAttribute : Attribute
    {
        /// Initializes a new instance of the ActionAliasAttribute class.
        /// <param name="alias">An alias for the action.</param>
        /// <param name="category">Category that this action is part of.</param>
        public ActionAliasAttribute(string alias, CommandCategory category)
        {
            this.Alias = alias.ToLower();
            this.Category = category;
        }

        /// Gets the alias attribute for the action.
        public string Alias { get; private set; }

        /// Gets the Category that this action is filed under.
        public CommandCategory Category { get; private set; }
    }
}


text:
<?php

declare(strict_types=1);

namespace Sonata\BasketBundle\Serializer;

use Sonata\Form\Serializer\BaseSerializerHandler;

/**
 * @author Sylvain Deloux <sylvain.deloux@ekino.com>
 */
class BasketSerializerHandler extends BaseSerializerHandler
{
    public static function getType()
    {
        return 'sonata_basket_basket_id';
    }
}


text:
/*******************************************************************************
 * © Indra Sistemas, S.A.
 * 2013 - 2014  SPAIN
 *
 * All rights reserved
 ******************************************************************************/
package com.indra.sofia2.kpmodelo.worker.Sib;

import com.indra.sofia2.kpmodelo.message.SibMessage;
import com.mycila.event.Subscriber;

public interface ConnectionToSIBWorker extends Subscriber<SibMessage> {

	void connected(SibMessage connected);

}


text:
package fr.esiea.unique.binome.farouk_ayoub.Metier;

public class Player extends AbstractPlayer{

    /**
     * Le constructeur de l'objet joueur
     *
     * @param name le nom du joueur
     */
    public Player(String name) {
        super(name);
    }

}


text:
package com.tkmtwo.kavro.serde;

import kafka.serializer.Encoder;

import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.generic.GenericContainer;

public class SpecificDatumEncoder<T extends GenericContainer>
  extends DatumSerDe<T> implements Encoder<T> {

	private final DatumWriter<T> datumWriter;

	public SpecificDatumEncoder(final Class<T> specificRecordClass) {
		datumWriter = new SpecificDatumWriter<T>(specificRecordClass);
	}

	@Override
    public byte[] toBytes(final T source) {
		return toBytes(source, datumWriter);
	}
}


text:
package org.hisp.dhis.trackedentity;

import org.hisp.dhis.common.GenericIdentifiableObjectStore;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Chau Thu Tran
 */
@Transactional
public class DefaultTrackedEntityAttributeGroupService
    implements TrackedEntityAttributeGroupService
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private GenericIdentifiableObjectStore<TrackedEntityAttributeGroup> attributeGroupStore;

    public void setAttributeGroupStore( GenericIdentifiableObjectStore<TrackedEntityAttributeGroup> attributeGroupStore )
    {
        this.attributeGroupStore = attributeGroupStore;
    }

    // -------------------------------------------------------------------------
    // Implementation methods
    // -------------------------------------------------------------------------

    @Override
    public int addTrackedEntityAttributeGroup( TrackedEntityAttributeGroup attributeGroup )
    {
        return attributeGroupStore.save( attributeGroup );
    }

    @Override
    public void deleteTrackedEntityAttributeGroup( TrackedEntityAttributeGroup attributeGroup )
    {
        attributeGroupStore.delete( attributeGroup );
    }

    @Override
    public void updateTrackedEntityAttributeGroup( TrackedEntityAttributeGroup attributeGroup )
    {
        attributeGroupStore.update( attributeGroup );
    }

    @Override
    public TrackedEntityAttributeGroup getTrackedEntityAttributeGroup( int id )
    {
        return attributeGroupStore.get( id );
    }

    @Override
    public TrackedEntityAttributeGroup getTrackedEntityAttributeGroup( String uid )
    {
        return attributeGroupStore.getByUid( uid );
    }

    @Override
    public TrackedEntityAttributeGroup getTrackedEntityAttributeGroupByName( String name )
    {
        return attributeGroupStore.getByName( name );
    }

    @Override
    public List<TrackedEntityAttributeGroup> getAllTrackedEntityAttributeGroups()
    {
        return attributeGroupStore.getAll();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nuovo Giorn. Bot. Ital. 22(1): 51 (1915)

#### Original name
Phomopsis gasteriae Sacc.

### Remarks
null


text:
package com.fincatto.nfe200.classes;

public enum NFOrigemProcesso {
    SEFAZ("0"),
    JUSTICA_FEDERAL("1"),
    JUSTICA_ESTADUAL("2"),
    SECEX_RFB("3"),
    OUTROS("9");

    private String codigo;

    private NFOrigemProcesso(final String codigo) {
        this.codigo = codigo;
    }

    public String getCodigo() {
        return this.codigo;
    }

    public static NFOrigemProcesso valueOfCodigo(final String codigo) {
        for (final NFOrigemProcesso origemProcesso : NFOrigemProcesso.values()) {
            if (origemProcesso.getCodigo().equals(codigo)) {
                return origemProcesso;
            }
        }
        return null;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<params>

	<section name="tenders"> <!-- obrigatório -->

		<!-- input text -->
		<param
			type="text"
			name="product_profit_factor"
			default="valor padrão do campo 1"
			label="input text"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		>

			<validation rules="trim" />

		</param>

		<!-- Radios -->
		<param
			type="radio"
			name="radio"
			value="valor radio 1"
			default="true"
			label="radio 1"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		>

			<validation rules="trim" />

		</param>
		<param
			type="radio"
			name="radio"
			value="valor radio 2"
			default=""
			label="radio 2"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		>

			<validation rules="trim" />

		</param>

		<!-- select -->
		<param
			type="select"
			name="select"
			default="0"
			label="select"
			tip="teste"
			ext_tip="teste"
			class="classe do campo"
		>

			<option value="global">Global</option>
			<option value="1">yes</option>
			<option value="0">no</option>

			<validation rules="trim" />

		</param>

		<!-- spacer -->
		<param
			type="spacer"
			class="classe do campo"
		/>

		<!-- spacer with label-->
		<param
			type="spacer"
			label="spacer label"
			class="classe do campo"
		/>

		<!-- textarea -->
		<param
			type="textarea"
			name="tender_notes_content"
			default="valor padrão do campo 1"
			label="tender_notes_content"
			tip="teste"
			ext_tip="teste"
			class="classe do campo"
		>

			<validation rules="trim" />

		</param>

		<!-- checkbox -->
		<param
			name="teste2"
			type="checkbox"
			value="valor checkbox 5"
			default=""
			label="checkbox"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		/>

		<!-- checkbox array -->
		<param
			name="teste"
			type="checkbox"
			value="valor checkbox 1"
			default=""
			label="checkbox array"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		/>

		<param
			name="teste"
			type="checkbox"
			value="valor checkbox 2"
			default="true"
			label="checkbox array"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		/>

		<param
			name="teste"
			type="checkbox"
			value="valor checkbox 3"
			default=""
			label="checkbox array"
			tip="Tip do label"
			ext_tip="Tip extendida do label"
			class="classe do campo"
		/>

	</section>

</params>


text:
package org.apache.hadoop.hive.ql.exec.tez;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.CommonMergeJoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedBatchUtil;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatchCtx;
import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpressionWriter;
import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpressionWriterFactory;
import org.apache.hadoop.hive.ql.log.PerfLogger;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.hive.serde2.SerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.tez.runtime.library.api.KeyValuesReader;

/**
 * Process input from tez LogicalInput and write output - for a map plan
 * Just pump the records through the query plan.
 */
@SuppressWarnings("deprecation")
public class ReduceRecordSource implements RecordSource {

  public static final Log l4j = LogFactory.getLog(ReduceRecordSource.class);

  private static final String CLASS_NAME = ReduceRecordSource.class.getName();

  private byte tag;

  private boolean abort = false;

  private static Deserializer inputKeyDeserializer;

  // Input value serde needs to be an array to support different SerDe
  // for different tags
  private SerDe inputValueDeserializer;

  private TableDesc keyTableDesc;
  private TableDesc valueTableDesc;

  private ObjectInspector rowObjectInspector;
  private Operator<?> reducer;

  private Object keyObject = null;
  private BytesWritable groupKey;

  private boolean vectorized = false;

  private DataOutputBuffer keyBuffer;
  private DataOutputBuffer valueBuffer;
  private VectorizedRowBatchCtx batchContext;
  private VectorizedRowBatch batch;

  // number of columns pertaining to keys in a vectorized row batch
  private int keysColumnOffset;
  private final int BATCH_SIZE = VectorizedRowBatch.DEFAULT_SIZE;

  private StructObjectInspector keyStructInspector;
  private StructObjectInspector valueStructInspectors;

  /* this is only used in the error code path */
  private List<VectorExpressionWriter> valueStringWriters;

  private KeyValuesReader reader;

  private boolean handleGroupKey;

  private ObjectInspector valueObjectInspector;

  private final PerfLogger perfLogger = SessionState.getPerfLogger();

  private Iterable<Object> valueWritables;

  private final GroupIterator groupIterator = new GroupIterator();

  void init(JobConf jconf, Operator<?> reducer, boolean vectorized, TableDesc keyTableDesc,
      TableDesc valueTableDesc, KeyValuesReader reader, boolean handleGroupKey, byte tag,
      Map<String, Map<Integer, String>> scratchColumnVectorTypes)
      throws Exception {

    ObjectInspector keyObjectInspector;

    this.reducer = reducer;
    this.vectorized = vectorized;
    this.keyTableDesc = keyTableDesc;
    this.reader = reader;
    this.handleGroupKey = handleGroupKey;
    this.tag = tag;

    try {
      inputKeyDeserializer = ReflectionUtils.newInstance(keyTableDesc
          .getDeserializerClass(), null);
      SerDeUtils.initializeSerDe(inputKeyDeserializer, null, keyTableDesc.getProperties(), null);
      keyObjectInspector = inputKeyDeserializer.getObjectInspector();

      if(vectorized) {
        keyStructInspector = (StructObjectInspector) keyObjectInspector;
        keysColumnOffset = keyStructInspector.getAllStructFieldRefs().size();
        keyBuffer = new DataOutputBuffer();
        valueBuffer = new DataOutputBuffer();
      }

      // We should initialize the SerDe with the TypeInfo when available.
      this.valueTableDesc = valueTableDesc;
      inputValueDeserializer = (SerDe) ReflectionUtils.newInstance(
          valueTableDesc.getDeserializerClass(), null);
      SerDeUtils.initializeSerDe(inputValueDeserializer, null,
          valueTableDesc.getProperties(), null);
      valueObjectInspector = inputValueDeserializer.getObjectInspector();

      ArrayList<ObjectInspector> ois = new ArrayList<ObjectInspector>();

      if(vectorized) {
        /* vectorization only works with struct object inspectors */
        valueStructInspectors = (StructObjectInspector) valueObjectInspector;

        final int totalColumns = keysColumnOffset +
            valueStructInspectors.getAllStructFieldRefs().size();
        valueStringWriters = new ArrayList<VectorExpressionWriter>(totalColumns);
        valueStringWriters.addAll(Arrays
            .asList(VectorExpressionWriterFactory
                .genVectorStructExpressionWritables(keyStructInspector)));
        valueStringWriters.addAll(Arrays
            .asList(VectorExpressionWriterFactory
                .genVectorStructExpressionWritables(valueStructInspectors)));

        /*
         * The row object inspector used by ReduceWork needs to be a **standard**
         * struct object inspector, not just any struct object inspector.
         */
        ArrayList<String> colNames = new ArrayList<String>();
        List<? extends StructField> fields = keyStructInspector.getAllStructFieldRefs();
        for (StructField field: fields) {
          colNames.add(Utilities.ReduceField.KEY.toString() + "." + field.getFieldName());
          ois.add(field.getFieldObjectInspector());
        }
        fields = valueStructInspectors.getAllStructFieldRefs();
        for (StructField field: fields) {
          colNames.add(Utilities.ReduceField.VALUE.toString() + "." + field.getFieldName());
          ois.add(field.getFieldObjectInspector());
        }
        rowObjectInspector = ObjectInspectorFactory.getStandardStructObjectInspector(colNames, ois);

        Map<Integer, String> reduceShuffleScratchColumnTypeMap =
                scratchColumnVectorTypes.get("_REDUCE_SHUFFLE_");
        batchContext = new VectorizedRowBatchCtx();
        batchContext.init(reduceShuffleScratchColumnTypeMap, (StructObjectInspector) rowObjectInspector);
        batch = batchContext.createVectorizedRowBatch();
      } else {
        ois.add(keyObjectInspector);
        ois.add(valueObjectInspector);
        rowObjectInspector =
            ObjectInspectorFactory.getStandardStructObjectInspector(Utilities.reduceFieldNameList,
                ois);
      }
    } catch (Throwable e) {
      abort = true;
      if (e instanceof OutOfMemoryError) {
        // Don't create a new object if we are already out of memory
        throw (OutOfMemoryError) e;
      } else {
        throw new RuntimeException("Reduce operator initialization failed", e);
      }
    }
    perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.TEZ_INIT_OPERATORS);
  }

  @Override
  public final boolean isGrouped() {
    return vectorized;
  }

  @Override
  public boolean pushRecord() throws HiveException {
    BytesWritable keyWritable;

    if (!vectorized && groupIterator.hasNext()) {
      // if we have records left in the group we push one of those
      groupIterator.next();
      return true;
    }

    try {
      if (!reader.next()) {
        return false;
      } else {
        keyWritable = (BytesWritable) reader.getCurrentKey();
        valueWritables = reader.getCurrentValues();
      }

      //Set the key, check if this is a new group or same group
      try {
        keyObject = inputKeyDeserializer.deserialize(keyWritable);
      } catch (Exception e) {
        throw new HiveException("Hive Runtime Error: Unable to deserialize reduce input key from "
            + Utilities.formatBinaryString(keyWritable.getBytes(), 0, keyWritable.getLength())
            + " with properties " + keyTableDesc.getProperties(), e);
      }

      if (handleGroupKey && !keyWritable.equals(this.groupKey)) {
        // If a operator wants to do some work at the beginning of a group
        if (groupKey == null) { // the first group
          this.groupKey = new BytesWritable();
        } else {
          // If a operator wants to do some work at the end of a group
          reducer.endGroup();
        }

        groupKey.set(keyWritable.getBytes(), 0, keyWritable.getLength());
        reducer.startGroup();
        reducer.setGroupKeyObject(keyObject);
      }

      if(vectorized) {
        processVectors(valueWritables, tag);
      } else {
        groupIterator.initialize(valueWritables, keyObject, tag);
        if (groupIterator.hasNext()) {
          groupIterator.next(); // push first record of group
        }
      }
      return true;
    } catch (Throwable e) {
      abort = true;
      if (e instanceof OutOfMemoryError) {
        // Don't create a new object if we are already out of memory
        throw (OutOfMemoryError) e;
      } else {
        l4j.fatal(StringUtils.stringifyException(e));
        throw new RuntimeException(e);
      }
    }
  }

  private Object deserializeValue(BytesWritable valueWritable, byte tag)
      throws HiveException {

    try {
      return inputValueDeserializer.deserialize(valueWritable);
    } catch (SerDeException e) {
      throw new HiveException(
          "Hive Runtime Error: Unable to deserialize reduce input value (tag="
              + tag
              + ") from "
          + Utilities.formatBinaryString(valueWritable.getBytes(), 0, valueWritable.getLength())
          + " with properties " + valueTableDesc.getProperties(), e);
    }
  }

  private class GroupIterator {
    private final List<Object> row = new ArrayList<Object>(Utilities.reduceFieldNameList.size());
    private List<Object> passDownKey = null;
    private Iterator<Object> values;
    private byte tag;
    private Object keyObject;

    public void initialize(Iterable<Object> values, Object keyObject, byte tag) {
      this.passDownKey = null;
      this.values = values.iterator();
      this.tag = tag;
      this.keyObject = keyObject;
    }

    public boolean hasNext() {
      return values != null && values.hasNext();
    }

    public void next() throws HiveException {
      row.clear();
      Object value = values.next();
      BytesWritable valueWritable = (BytesWritable) value;

      if (passDownKey == null) {
        row.add(this.keyObject);
      } else {
        row.add(passDownKey.get(0));
      }
      if ((passDownKey == null) && (reducer instanceof CommonMergeJoinOperator)) {
        passDownKey =
            (List<Object>) ObjectInspectorUtils.copyToStandardObject(row,
                reducer.getInputObjInspectors()[tag], ObjectInspectorCopyOption.WRITABLE);
        row.remove(0);
        row.add(0, passDownKey.get(0));
      }

      row.add(deserializeValue(valueWritable, tag));

      try {
        reducer.processOp(row, tag);
      } catch (Exception e) {
        String rowString = null;
        try {
          rowString = SerDeUtils.getJSONString(row, rowObjectInspector);
        } catch (Exception e2) {
          rowString = "[Error getting row data with exception "
              + StringUtils.stringifyException(e2) + " ]";
        }
        throw new HiveException("Hive Runtime Error while processing row (tag="
            + tag + ") " + rowString, e);
      }
    }
  }

  /**
   * @param values
   * @return true if it is not done and can take more inputs
   */
  private void processVectors(Iterable<Object> values, byte tag) throws HiveException {
    /* deserialize key into columns */
    VectorizedBatchUtil.addRowToBatchFrom(keyObject, keyStructInspector,
        0, 0, batch, keyBuffer);
    for(int i = 0; i < keysColumnOffset; i++) {
      VectorizedBatchUtil.setRepeatingColumn(batch, i);
    }

    int rowIdx = 0;
    try {
      for (Object value : values) {
        /* deserialize value into columns */
        BytesWritable valueWritable = (BytesWritable) value;
        Object valueObj = deserializeValue(valueWritable, tag);

        VectorizedBatchUtil.addRowToBatchFrom(valueObj, valueStructInspectors,
            rowIdx, keysColumnOffset, batch, valueBuffer);
        rowIdx++;
        if (rowIdx >= BATCH_SIZE) {
          VectorizedBatchUtil.setBatchSize(batch, rowIdx);
          reducer.processOp(batch, tag);

          // Reset just the value columns and value buffer.
          for (int i = keysColumnOffset; i < batch.numCols; i++) {
            batch.cols[i].reset();
          }
          valueBuffer.reset();
          rowIdx = 0;
        }
      }
      if (rowIdx > 0) {
        // Flush final partial batch.
        VectorizedBatchUtil.setBatchSize(batch, rowIdx);
        reducer.processOp(batch, tag);
      }
      batch.reset();
      keyBuffer.reset();
      valueBuffer.reset();
    } catch (Exception e) {
      String rowString = null;
      try {
        /* batch.toString depends on this */
        batch.setValueWriters(valueStringWriters
            .toArray(new VectorExpressionWriter[0]));
        rowString = batch.toString();
      } catch (Exception e2) {
        rowString = "[Error getting row data with exception "
            + StringUtils.stringifyException(e2) + " ]";
      }
      throw new HiveException("Hive Runtime Error while processing vector batch (tag="
          + tag + ") " + rowString, e);
    }
  }

  boolean close() throws Exception {
    try {
      if (handleGroupKey && groupKey != null) {
        // If a operator wants to do some work at the end of a group
        reducer.endGroup();
      }
    } catch (Exception e) {
      if (!abort) {
        // signal new failure to map-reduce
        throw new RuntimeException("Hive Runtime Error while closing operators: "
            + e.getMessage(), e);
      }
    }
    return abort;
  }

  public ObjectInspector getObjectInspector() {
    return rowObjectInspector;
  }
}


text:
build:
	docker-compose build

zip:
	docker save trntxt_app | gzip > trntxt.tar.gz


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "industrytype".
 *
 * @property integer $industrytype_id
 * @property string $name
 * @property string $description
 * @property string $status
 */
class Industrytype extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'industrytype';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'description', 'status'], 'required'],
            [['status'], 'string'],
            [['name', 'description'], 'string', 'max' => 200],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'industrytype_id' => 'Industrytype ID',
            'name' => 'Name',
            'description' => 'Description',
            'status' => 'Status',
        ];
    }
}


text:
package org.sana.net;

import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author Sana Development
 *
 */
public class Request {

    public URL uri;
    public Map<String, List<String>> headers;

    public Request(URL uri, Map<String, List<String>> headers) {
        this.uri = uri;
        this.headers = headers;
    }

    private class POST extends Request {
        public byte[] body;

        public POST(URL uri, Map<String, List<String>> headers, byte[] body) {
            super(uri, headers);
            this.body = body;
        }
    }

    private class GET extends Request {
        public GET(URL uri, Map<String, List<String>> headers) {
            super(uri, headers);
        }
    }

    private class PUT extends Request {
        public byte[] body;

        public PUT(URL uri, Map<String, List<String>> headers, byte[] body) {
            super(uri, headers);
            this.body = body;
        }
    }

    private class DELETE extends Request {
        public DELETE(URL uri, Map<String, List<String>> headers) {
            super(uri, headers);
        }
    }

}


text:
<?php

namespace CollectionTypeTest\Collection\CollectionSet\HashSet;

use CollectionType\Collection\CollectionSet\HashSet;

class ConstructorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers       CollectionType\Collection\CollectionSet\HashSet::__construct
     * @covers       CollectionType\Collection\CollectionSet\SetAbstract::__construct
     * @covers       CollectionType\Collection\CollectionAbstract::__construct
     * @covers       CollectionType\Common\ValueTypeTrait::setValueType
     */
    public function testConstruct()
    {
        $dummyType = $this->prophesize('CollectionType\TypeValidator\StringTypeValidator');
        $dummyType->willImplement('CollectionType\TypeValidator\TypeValidatorInterface');

        $this->set = new HashSet($dummyType->reveal());

        $this->assertEquals($dummyType->reveal(), $this->set->getValueType());
    }
}


text:
using System.Collections.Generic;

namespace Day15.ConsoleApplication
{
    public class Recipe
    {
        public Recipe()
        {
            Ingredients = new Dictionary<Ingredient, int>();
        }

        public Dictionary<Ingredient, int> Ingredients { get; set; }

        public int Score { get; set; }
    }
}


text:
package org.apache.ambari.server.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.xml.bind.JAXBException;

import com.google.gson.Gson;
import com.google.inject.Injector;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.Role;
import org.apache.ambari.server.RoleCommand;
import org.apache.ambari.server.actionmanager.Stage;
import org.apache.ambari.server.agent.ExecutionCommand;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.HostsMap;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.Host;
import org.apache.ambari.server.state.ServiceComponent;
import org.apache.ambari.server.state.svccomphost.ServiceComponentHostInstallEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

public class StageUtils {
  private static final Log LOG = LogFactory.getLog(StageUtils.class);

  private static Map<String, String> componentToClusterInfoKeyMap =
      new HashMap<String, String>();

  private volatile static Gson gson;

  public static void setGson(Gson gson) {
    if (gson==null) {
      StageUtils.gson = gson;
    }
  }

  public static Gson getGson() {
    if (gson != null) {
      return gson;
    } else {
      synchronized (LOG) {
        if (gson==null) {
          gson = new Gson();
        }
        return gson;
      }
    }
  }

  static {
    componentToClusterInfoKeyMap.put("NAMENODE", "namenode_host");
    componentToClusterInfoKeyMap.put("JOBTRACKER", "jtnode_host");
    componentToClusterInfoKeyMap.put("SNAMENODE", "snamenode_host");
    componentToClusterInfoKeyMap.put("RESOURCEMANAGER", "rm_host");
    componentToClusterInfoKeyMap.put("NODEMANAGER", "nm_hosts");
    componentToClusterInfoKeyMap.put("HISTORYSERVER", "hs_host");
    componentToClusterInfoKeyMap.put("JOURNALNODE", "journalnode_hosts");
    componentToClusterInfoKeyMap.put("ZKFC", "zkfc_hosts");
    componentToClusterInfoKeyMap.put("ZOOKEEPER_SERVER", "zookeeper_hosts");
    componentToClusterInfoKeyMap.put("FLUME_SERVER", "flume_hosts");
    componentToClusterInfoKeyMap.put("HBASE_MASTER", "hbase_master_hosts");
    componentToClusterInfoKeyMap.put("HBASE_REGIONSERVER", "hbase_rs_hosts");
    componentToClusterInfoKeyMap.put("HIVE_SERVER", "hive_server_host");
    componentToClusterInfoKeyMap.put("OOZIE_SERVER", "oozie_server");
    componentToClusterInfoKeyMap.put("WEBHCAT_SERVER",
        "webhcat_server_host");
    componentToClusterInfoKeyMap.put(Role.MYSQL_SERVER.toString(),
        "hive_mysql_host");
    componentToClusterInfoKeyMap.put("DASHBOARD", "dashboard_host");
    componentToClusterInfoKeyMap.put("NAGIOS_SERVER", "nagios_server_host");
    componentToClusterInfoKeyMap.put("GANGLIA_SERVER",
        "ganglia_server_host");
    componentToClusterInfoKeyMap.put("DATANODE", "slave_hosts");
    componentToClusterInfoKeyMap.put("TASKTRACKER", "mapred_tt_hosts");
    componentToClusterInfoKeyMap.put("HBASE_REGIONSERVER", "hbase_rs_hosts");
    componentToClusterInfoKeyMap.put("KERBEROS_SERVER", "kdc_host");
    componentToClusterInfoKeyMap.put("KERBEROS_ADMIN_CLIENT",
        "kerberos_adminclient_host");
  }

  public static String getActionId(long requestId, long stageId) {
    return requestId + "-" + stageId;
  }

  public static long[] getRequestStage(String actionId) {
    String[] fields = actionId.split("-");
    long[] requestStageIds = new long[2];
    requestStageIds[0] = Long.parseLong(fields[0]);
    requestStageIds[1] = Long.parseLong(fields[1]);
    return requestStageIds;
  }

  public static Stage getATestStage(long requestId, long stageId) {
    String hostname;
    try {
      hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      hostname = "host-dummy";
    }
    return getATestStage(requestId, stageId, hostname);
  }

  //For testing only
  public static Stage getATestStage(long requestId, long stageId, String hostname) {
    Stage s = new Stage(requestId, "/tmp", "cluster1", "context");
    s.setStageId(stageId);
    long now = System.currentTimeMillis();
    String filename = null;
    s.addHostRoleExecutionCommand(hostname, Role.NAMENODE, RoleCommand.INSTALL,
        new ServiceComponentHostInstallEvent("NAMENODE", hostname, now, "HDP-1.2.0"),
        "cluster1", "HDFS");
    ExecutionCommand execCmd = s.getExecutionCommandWrapper(hostname, "NAMENODE").getExecutionCommand();
    execCmd.setCommandId(s.getActionId());
    Map<String, List<String>> clusterHostInfo = new TreeMap<String, List<String>>();
    List<String> slaveHostList = new ArrayList<String>();
    slaveHostList.add(hostname);
    slaveHostList.add("host2");
    clusterHostInfo.put("slave_hosts", slaveHostList);
    execCmd.setClusterHostInfo(clusterHostInfo);
    Map<String, String> hdfsSite = new TreeMap<String, String>();
    hdfsSite.put("dfs.block.size", "2560000000");
    Map<String, Map<String, String>> configurations =
        new TreeMap<String, Map<String, String>>();
    configurations.put("hdfs-site", hdfsSite);
    execCmd.setConfigurations(configurations);
    Map<String, String> params = new TreeMap<String, String>();
    params.put("jdklocation", "/x/y/z");
    execCmd.setHostLevelParams(params);
    Map<String, String> roleParams = new TreeMap<String, String>();
    roleParams.put("format", "false");
    execCmd.setRoleParams(roleParams);
    return s;
  }

  public static String jaxbToString(Object jaxbObj) throws JAXBException,
  JsonGenerationException, JsonMappingException, IOException {
    return getGson().toJson(jaxbObj);
  }

  public static ExecutionCommand stringToExecutionCommand(String json)
      throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
    mapper.configure(SerializationConfig.Feature.USE_ANNOTATIONS, true);
    InputStream is = new ByteArrayInputStream(json.getBytes(Charset.forName("UTF8")));
    return mapper.readValue(is, ExecutionCommand.class);
  }

  public static <T> T fromJson(String json, Class<T> clazz) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
    mapper.configure(SerializationConfig.Feature.USE_ANNOTATIONS, true);
    InputStream is = new ByteArrayInputStream(json.getBytes(Charset.forName("UTF8")));
    return mapper.readValue(is, clazz);
  }

  public static Map<String, List<String>> getClusterHostInfo(
      Map<String, Host> allHosts, Cluster cluster, HostsMap hostsMap,
      Injector injector) throws AmbariException {
    Map<String, List<String>> info = new HashMap<String, List<String>>();
    if (cluster.getServices() != null) {
      String hostName = getHostName();
      for (String serviceName : cluster.getServices().keySet()) {
        if (cluster.getServices().get(serviceName) != null) {
          for (String componentName : cluster.getServices().get(serviceName)
              .getServiceComponents().keySet()) {
            String clusterInfoKey = componentToClusterInfoKeyMap
                .get(componentName);
            if (clusterInfoKey == null) {
              continue;
            }
            ServiceComponent scomp = cluster.getServices().get(serviceName)
                .getServiceComponents().get(componentName);
            if (scomp.getServiceComponentHosts() != null
                && !scomp.getServiceComponentHosts().isEmpty()) {
              List<String> hostList = new ArrayList<String>();
              for (String host: scomp.getServiceComponentHosts().keySet()) {
                String mappedHost = hostsMap.getHostMap(host);
                hostList.add(mappedHost);
              }
              info.put(clusterInfoKey, hostList);
            }
            //Set up ambari-rca connection properties, is this a hack?
//            info.put("ambari_db_server_host", Arrays.asList(hostsMap.getHostMap(getHostName())));
            Configuration configuration = injector.getInstance(Configuration.class);
            String url = configuration.getRcaDatabaseUrl();
            if (url.contains(Configuration.HOSTNAME_MACRO)) {
              url = url.replace(Configuration.HOSTNAME_MACRO, hostsMap.getHostMap(hostName));
            }
            info.put("ambari_db_rca_url", Arrays.asList(url));
            info.put("ambari_db_rca_driver", Arrays.asList(configuration.getRcaDatabaseDriver()));
            info.put("ambari_db_rca_username", Arrays.asList(configuration.getRcaDatabaseUser()));
            info.put("ambari_db_rca_password", Arrays.asList(configuration.getRcaDatabasePassword()));

          }
        }
      }
    }

    // Add a lists of all hosts and all ping ports for agents and hosts monitoring
    List<String> allHostNames = new ArrayList<String>();
    List<String> allHostPingPorts = new ArrayList<String>();
    for (Host host : allHosts.values()) {
      allHostNames.add(host.getHostName());
      while (host.getCurrentPingPort() == null) {
        try {
          LOG.warn("Ping port is null for " + host.getHostName() + ". Doing a busy wait until the port is set");
          Thread.sleep(500);
        } catch (InterruptedException e) {
          // Do nothing if wait is interrupted
        }
      }
      allHostPingPorts.add(host.getCurrentPingPort() == null ? null : host.getCurrentPingPort().toString());
    }
    info.put("all_hosts", allHostNames);
    info.put("all_ping_ports", allHostPingPorts);
    return info;
  }

  public static String getHostName() {
    try {
      return InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
      LOG.warn("Could not find canonical hostname ", e);
      return "localhost";
    }
  }

  public static String getHostsToDecommission(List<String> hosts) {
    StringBuilder builder = new StringBuilder();
    builder.append("[");
    boolean first = true;
    for (String host : hosts) {
      if (!first) {
        builder.append(",");
      } else {
        first = false;
      }
      builder.append("'");
      builder.append(host);
      builder.append("'");
    }
    return builder.toString();
  }
}


text:
namespace BD3GE {
	Material::Material() : color_ambient(Vector3(0.1f, 0.1f, 0.1f)), color_diffuse(Vector3(1.0f, 1.0f, 1.0f)), color_specular(Vector3(0.5f, 0.5f, 0.5f)), gloss_factor(32.0f) {}

	Material::Material(Vector3 color_ambient, Vector3 color_diffuse, Vector3 color_specular, float gloss_factor) {
		this->color_ambient = color_ambient;
		this->color_diffuse = color_diffuse;
		this->color_specular = color_specular;
		this->gloss_factor = gloss_factor;
	}
}


text:
/**
 * Tree node for the block structure.
 * @author Arjun Nair
 */
public class ASTBlock extends SimpleNode
{
	public ASTBlock(int id)
	{
		super(id);
	}

	public ASTBlock(ParfA p, int id)
	{
		super(p, id);
	}

	@Override
	public void interpret()
	{
		for (int i = 0; i < jjtGetNumChildren(); i++)
			jjtGetChild(i).interpret();
	}
}


text:
package objectutil

import (
	"errors"
	"fmt"

	apimeta "k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
)

// FilterWithLabels returns a copy of the items in objs matching labelSel.
func FilterWithLabels(objs []runtime.Object, labelSel labels.Selector) ([]runtime.Object, error) {
	outItems := make([]runtime.Object, 0, len(objs))
	for _, obj := range objs {
		meta, err := apimeta.Accessor(obj)
		if err != nil {
			return nil, err
		}
		if labelSel != nil {
			lbls := labels.Set(meta.GetLabels())
			if !labelSel.Matches(lbls) {
				continue
			}
		}
		outItems = append(outItems, obj.DeepCopyObject())
	}
	return outItems, nil
}

// IsAPINamespaced returns true if the object is namespace scoped.
// For unstructured objects the gvk is found from the object itself.
func IsAPINamespaced(obj runtime.Object, scheme *runtime.Scheme, restmapper apimeta.RESTMapper) (bool, error) {
	gvk, err := apiutil.GVKForObject(obj, scheme)
	if err != nil {
		return false, err
	}

	return IsAPINamespacedWithGVK(gvk, scheme, restmapper)
}

// IsAPINamespacedWithGVK returns true if the object having the provided
// GVK is namespace scoped.
func IsAPINamespacedWithGVK(gk schema.GroupVersionKind, scheme *runtime.Scheme, restmapper apimeta.RESTMapper) (bool, error) {
	restmapping, err := restmapper.RESTMapping(schema.GroupKind{Group: gk.Group, Kind: gk.Kind})
	if err != nil {
		return false, fmt.Errorf("failed to get restmapping: %w", err)
	}

	scope := restmapping.Scope.Name()

	if scope == "" {
		return false, errors.New("scope cannot be identified, empty scope returned")
	}

	if scope != apimeta.RESTScopeNameRoot {
		return true, nil
	}
	return false, nil
}


text:
"""Tests various aspects of the JS traverser."""
import mock

from .js_helper import _do_real_test_raw as _test_js

@mock.patch('validator.testcases.javascript.traverser.JSWrapper')
def test_js_traversal_error_reporting(JSWrapper):
    """Test that an internal error in JS traversal is correctly reported as
    a system error."""

    JSWrapper.side_effect = Exception('Inigo Montoya...')
    err = _test_js('hello();', path='my_name_is.js')

    assert len(err.errors) == 1
    assert err.errors[0]['id'] == ('validator', 'unexpected_exception')
    assert err.errors[0]['file'] == 'my_name_is.js'


text:
<?php
class CmcBoolean extends Boolean {

    public function __construct($name = null, $defaultVal = 0) {
        Requirements::css(CMC_HELPER_MODULE_DIR.'/css/cmcboolean.css');
        Requirements::themedCSS("cmcboolean");
        parent::__construct($name);
    }

    public function NiceCMS() {
        if ($this->value) {
        	$obj = HTMLText::create();
        	$obj->setValue('X');
            //return ' ';
            return $obj; //needs to be g for javascript
        }
        return '';
    }

    public function YesNo() {
        return $this->Nice();
    }

    public function YesBlank() {
        if ($this->value) {
            return _t('Boolean.YESANSWER', 'Yes');
        }
        return '';
    }

    public function TrueFalse() {
        return $this->NiceAsBoolean();
    }

}


text:
package biz.r2s.scaffolding.meta.field.params;

import biz.r2s.scaffolding.meta.field.TypeFieldScaffold;
/**
 * Created by raphael on 24/07/15.
 */
public class NumberPrecisionParamsFieldScaffold extends InputParamsFieldScaffold {

    int precision = 0;

    public NumberPrecisionParamsFieldScaffold() {
        this.setCampos("precision");
    }

    @Override
    public TypeFieldScaffold getType() {
        return TypeFieldScaffold.NUMBER_PRECISION;
    }

	public int getPrecision() {
		return precision;
	}

	public void setPrecision(int precision) {
		this.precision = precision;
	}

}


text:
package com.example.android.miwok;

/**
 * Created by Harsh on 12/25/2016.
 */

public class Word1 {

   private String mDefaultTranslation;
    private String mMiwokTranslation;
    private int mImgRId=NO_IMAGE_PROVIDED;
    private static final int NO_IMAGE_PROVIDED=-1;

    public Word1(String m,String d,int i){
        mMiwokTranslation=m;
        mDefaultTranslation=d;
        mImgRId=i;
    }

    public Word1(String m,String d){
        mMiwokTranslation=m;
        mDefaultTranslation=d;
    }

    public String getDefaultTranslation() {
        return mDefaultTranslation;
    }

    public String getMiwokTranslation() {
        return mMiwokTranslation;
    }

    public int getImgRId() { return mImgRId; }
    public boolean hasImage(){return mImgRId!=NO_IMAGE_PROVIDED;}
}


text:
title: Inglorious basterds
date: "2009-10-07T13:08:53+00:00"
author: ajgarlag
layout: post
tags:
  - personal
  - es
redirect_from: /blog/inglorious-basterds/
---
![Buy this poster at tsout.com](http://static1.squarespace.com/static/550db867e4b051bbaff5260a/553afc3ee4b0f281a4ea06f8/553afe0fe4b09e094f86db6d/1429929487543/inglourious_var.jpg?format=500w)

Ayer estuve viendo la Última de Quentin Tarantino: _Malditos bastardos_ (aunque no la vi en versión original, me encata el título en inglés: _Inglourious Basterds_).

No soy yo un especialista en cine, por lo que no esperéis una sesuda crítica sobre la película; además son fan confeso de Tarantino desde que me encontré, casi por casualidad con _Pulp Fiction_, por lo que mi opinión está más que condicionada.

Podemos decir que en general me gustó y me entretuvo, que son dos cosas que no siempre ocurren de forma simultánea. El guión, sin ser brillante, sigue teniendo alguno de esos diálogos geniales de Tarantino que son para mí el verdadero valor de su cine, destacando sobre los demás la interpretación de los mismos hecha por Christoph Waltz en su papel del Coronel Hans Landa _el Cazajudíos_.

Una vez más, la película se estructura en capítulos, pero me sorprendió que todos fuesen narrados de forma lineal. También me encantó la presentación del personaje del Sargento Hugo Stiglitz, y en general de todo el grupo de los bastardos, que tienen cara de cualquier cosa menos de despiadados asesinos.

Como siempre, Tarantino mezcla la violencia (y algo de gore), con toques de humor (negro en ocasiones) de forma que el resultado final es una película siempre entretenida, que creo que es para él el principal objetivo de su cine.

Además, vuelve a dejar patente su pasión por su trabajo, y por la historia del cine, con continuos guiños a la misma y haciendo que la trama principal gire en torno a una sala de proyección.

Bueno, hasta aquí mi primera _crítica_ de cine. Como habéis leíedo, sin _spoilers_. Intentaré hacer esto con las pelis que estén aún en cartelera cuando hable de ellas.

Por cierto, para los aficionados a Tarantino:

> [La novia volverá a luchar](http://www.20minutos.es/noticia/532024/0/tarantino/kill/bill/)


text:
<?php

namespace frdl\ApplicationComposer;
use frdl\ApplicationComposer\ApplicationMap;
use frdl;

class ApplicationComposerBootstrap
{
	protected static $_instance = null;
	protected static $baseconfig = array();

	protected function __construct($baseconfig = array(), $boot = true){
		$this->init($baseconfig, $boot);
	}

	protected function __clone(){}

	public static function me( $baseconfig = null, $boot = true){
		if(null===self::$_instance){
			 self::$_instance = new self($baseconfig, $boot);
		}else{
			if(null !== $baseconfig)$this->init($baseconfig, $boot);
		}

	   return self::$_instance;
	}

	/**
	 * set working directory
	 */
	public function wd($dir = null, $code = E_USER_WARNING){
		if(null !== $dir && is_dir($dir)){
			$this->wd = $dir;
			if(chdir($dir) === false){
			    throw new \Exception('Cannot change to directory '.$dir.' in '.__METHOD__, $code);
				return $this;
			}
		}else{
			$dir = $this->wd;
		}
		return $this;
	}

	public function __get($name){
		return (isset(self::$baseconfig['name'])) ? self::$baseconfig['name'] : null;
	}

	public function __set($name, $value){
		if(array_key_exists($name, self::$baseconfig)) self::$baseconfig[$name] = $value;
		return $this;
	}

	public function boot(){

		try{
			require self::$baseconfig['file_loader'];
			require self::$baseconfig['file_app'];

	//$init = false, $LoaderClass = self::LOADER, $name = '', $branch = 'dev-master',
	//   $version = 'v1.0.2-beta.1', $meta = array()
	\frdl\webfan\App::God(self::$baseconfig['initOnBoot'],  self::$baseconfig['psr8_initial'], self::$baseconfig['name'],
   self::$baseconfig['branch'],   self::$baseconfig['version'],   self::$baseconfig['meta'])
   	     ->{'$'}('L!', '\webfan\Loader::top')
	  //    ->{'L!'}()
		->Autoloader(true)
             -> addPsr4('frdl\\', self::$baseconfig['dir_lib'] . 'frdl'.DIRECTORY_SEPARATOR,  false)
             -> addPsr4('webfan\\', self::$baseconfig['dir_lib'] . 'webfan'.DIRECTORY_SEPARATOR,  false)
             -> addPsr4('webdof\\', self::$baseconfig['dir_lib'] . 'webdof'.DIRECTORY_SEPARATOR,  false)
             -> addPsr4('', self::$baseconfig['dir_lib'],  false)

         //  -> addClass('frdl\aSQL\Engines\Terminal\aSQLCommand', 'Terminal',  true )

       ;

			/**
			 *    ---- > load ApplicationMap...
			 *    $this->loadCoreConfig( CoreConfiguration $CoreConfiguration  )
			 */

		}catch(Exception $e){
			echo $e->getMessage();
		}

		return $this;
	}

	protected function defaultConfig($dir_lib = null){
		$c =  array(
		   'name' => 'Setup',
		   'branch' => 'dev-master',
		   'version' => 'v1.0.2-beta.1',

		   'package' => 'frdl/webfan#setup',

		   'meta' => array(),

		   'config' => array(),

		   'cmd' => 'setup',

		   'initOnBoot' => true,
		   'psr8_initial' => 'frdl\webfan\Autoloading\SourceLoader',

		   'dir_lib' => (null!==$dir_lib && is_dir($dir_lib)) ? $dir_lib : realpath(__DIR__ . DIRECTORY_SEPARATOR .'..' .DIRECTORY_SEPARATOR . '..'. DIRECTORY_SEPARATOR). DIRECTORY_SEPARATOR,
	       'wd' => getcwd(),

		   'UI' => PHP_SAPI,

		);

		$c['file_loader'] = $c['dir_lib']. 'frdl'.DIRECTORY_SEPARATOR.'webfan'.DIRECTORY_SEPARATOR.'Autoloading'.DIRECTORY_SEPARATOR.'SourceLoader.php';
		$c['file_app'] = $c['dir_lib']. 'frdl'.DIRECTORY_SEPARATOR.'webfan'.DIRECTORY_SEPARATOR.'App.php';

		return $c;
	}

	protected function init($baseconfig = array(), $boot = true){
		self::$baseconfig = (is_array($baseconfig) && count($baseconfig) > 0) ? array_merge($this->defaultConfig(null), $baseconfig) : $this->defaultConfig(null);

		if($boot === true)$this->boot();
	    return $this;
	}

}


text:
class UserDecorator < Draper::Decorator
  delegate_all

  def time_worked_today
    worklogs.joins(:timeframes).
      where("timeframes.started >= ?", DateTime.now.beginning_of_day).
      uniq.
      map(&:duration).inject(0, :+).to_f
  end

  def time_worked_this_week
    worklogs.joins(:timeframes).
      where("timeframes.started >= ?", DateTime.now.beginning_of_week).
      uniq.
      map(&:duration).inject(0, :+).to_f
  end

  def time_worked_this_month
    worklogs.joins(:timeframes).
      where("timeframes.started >= ?", DateTime.now.beginning_of_month).
      uniq.
      map(&:duration).inject(0, :+).to_f
  end

  def time_worked_last_month
    worklogs.joins(:timeframes).
      where("timeframes.started >= ? AND ended <= ?", 1.month.ago.beginning_of_month, 1.month.ago.end_of_month).
      uniq.
      map(&:duration).inject(0, :+).to_f
  end

  def hours_today
    h.number_with_precision (time_worked_today / 3600), precision: 2
  end

  def hours_this_week
    h.number_with_precision (time_worked_this_week / 3600), precision: 2
  end

  def hours_this_month
    h.number_with_precision (time_worked_this_month / 3600), precision: 2
  end

  def hours_last_month
    h.number_with_precision (time_worked_last_month / 3600), precision: 2
  end

end


text:
<BODY>
Simple Ephemeris reader demo</BODY>


text:
package io.netty.util;

import io.netty.util.internal.ObjectUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * A pool of {@link Constant}s.
 *
 * @param <T> the type of the constant
 */
public abstract class ConstantPool<T extends Constant<T>> {

    private final Map<String, T> constants = new HashMap<String, T>();

    private int nextId = 1;

    /**
     * Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
     */
    public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
        if (firstNameComponent == null) {
            throw new NullPointerException("firstNameComponent");
        }
        if (secondNameComponent == null) {
            throw new NullPointerException("secondNameComponent");
        }

        return valueOf(firstNameComponent.getName() + '#' + secondNameComponent);
    }

    /**
     * Returns the {@link Constant} which is assigned to the specified {@code name}.
     * If there's no such {@link Constant}, a new one will be created and returned.
     * Once created, the subsequent calls with the same {@code name} will always return the previously created one
     * (i.e. singleton.)
     *
     * @param name the name of the {@link Constant}
     */
    public T valueOf(String name) {
        T c;

        synchronized (constants) {
            if (exists(name)) {
                c = constants.get(name);
            } else {
                c = newInstance0(name);
            }
        }

        return c;
    }

    /**
     * Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}.
     */
    public boolean exists(String name) {
        checkNotNullAndNotEmpty(name);
        synchronized (constants) {
            return constants.containsKey(name);
        }
    }

    /**
     * Creates a new {@link Constant} for the given {@code name} or fail with an
     * {@link IllegalArgumentException} if a {@link Constant} for the given {@code name} exists.
     */
    @SuppressWarnings("unchecked")
    public T newInstance(String name) {
        if (exists(name)) {
            throw new IllegalArgumentException(String.format("'%s' is already in use", name));
        }

        T c = newInstance0(name);

        return c;
    }

    // Be careful that this dose not check whether the argument is null or empty.
    private T newInstance0(String name) {
        synchronized (constants) {
            T c = newConstant(nextId, name);
            constants.put(name, c);
            nextId++;
            return c;
        }
    }

    private String checkNotNullAndNotEmpty(String name) {
        ObjectUtil.checkNotNull(name, "name");

        if (name.isEmpty()) {
            throw new IllegalArgumentException("empty name");
        }

        return name;
    }

    protected abstract T newConstant(int id, String name);

    @Deprecated
    public final int nextId() {
        synchronized (constants) {
            int id = nextId;
            nextId++;
            return id;
        }
    }
}