text:
package to.augmented.reality.android.em.recorder;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;
import android.util.Log;
import android.util.Range;
import android.util.Size;
import android.view.Surface;
import to.augmented.reality.em.recorder.ScriptC_yuv2grey;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class PreviewCamera implements Previewable, Bufferable, Freezeable
//=======================================================================
{
   static final private String LOGTAG = "PreviewCamera";
   static private final boolean DEBUG = false;

   private final GLSurfaceView surfaceView;
   private final GLRecorderRenderer renderer;
   private final RenderScript renderscript;
   private final NativeFrameBuffer frameBuffer;
   private final ConditionVariable frameAvailCondVar;
   private Semaphore mCameraOpenCloseLock = new Semaphore(1);
   private String cameraID = null;
   private int legacyCameraId = -1;
   private CameraDevice cameraDevice;
   private int cameraWidth, cameraHeight;
   private boolean hasYUV = false, hasNV21 = false;
   private int imageFormat =-1;
   private Range<Integer> fps[] = null;
   private CameraCaptureSession captureSession;
   private ImageReader previewImageReader;
   boolean isPreviewing = false;
   private Surface previewSurface, displaySurface;
   private volatile boolean mustBuffer = false;
   private boolean hasFlash = false;
   private HandlerThread cameraThread;
   private Handler cameraHandler;
   private HandlerThread previewThread;
   private Handler previewHandler;
   private HandlerThread captureThread;
   private Handler captureHandler;

   @Override public boolean hasFlash() { return hasFlash; }

   @Override public void bufferOn() { frameBuffer.bufferOn(); mustBuffer = true; }
   @Override  public void bufferOff() { frameBuffer.bufferOff(); mustBuffer = false; }
   @Override public void bufferClear() { frameBuffer.bufferClear(); }
   @Override public boolean bufferEmpty() { return frameBuffer.bufferEmpty(); }
   @Override public void writeFile(File f) throws IOException { frameBuffer.writeFile(f); }
   @Override public File writeFile() { return frameBuffer.writeFile(); }
   @Override public boolean closeFile() throws IOException { return frameBuffer.closeFile(); }
   @Override public void flushFile() { frameBuffer.flushFile(); }
   @Override public void writeOff() { frameBuffer.writeOff(); }
   @Override public void writeOn() { frameBuffer.writeOn(); }
   @Override public void push(long timestamp, byte[] data, int retries) { frameBuffer.push(timestamp, data, retries); }

   @Override public void startTimestamp(long timestamp) { frameBuffer.startTimestamp(timestamp); }
   @Override public int writeCount() { return frameBuffer.writeCount(); }
   @Override public long writeSize() { return frameBuffer.writeSize(); }
   @Override public void stop() { frameBuffer.stop(); }
   @Override public boolean openForReading() { return frameBuffer.openForReading(); }
   @Override public boolean openForReading(File f) { return frameBuffer.openForReading(f); }
   @Override public BufferData read() throws IOException { return frameBuffer.read(); }
   @Override public long readPos(long offset) { return frameBuffer.readPos(offset); }

   float focalLen = -1;
   public float getFocalLen() { return focalLen; }

   float fovx = -1;
   public float getFovx() { return fovx; }

   float fovy = -1;
   public float getFovy() { return fovy; }

   String[] resolutions = new String[0];

   boolean isFlashOn = false;
   @Override public boolean isFlashOn() { return isFlashOn; }
   @Override public void setFlash(boolean isOnOff) { isFlashOn = isOnOff; }

   public PreviewCamera(GLRecorderRenderer renderer, GLSurfaceView surfaceView, Surface displaySurface,
                        NativeFrameBuffer frameBuffer, ConditionVariable frameAvailCondVar)
   //--------------------------------------------------------------------------------------------
   {
      this.renderer = renderer;
      this.surfaceView = surfaceView;
      this.displaySurface = displaySurface;
      this.frameBuffer = frameBuffer;
      this.frameAvailCondVar = frameAvailCondVar;
      renderscript = RenderScript.create(renderer.activity);
   }

   @Override
   public boolean open(int face, int width, int height, StringBuilder errbuf) throws CameraAccessException
   //=====================================================================================================
   {
      boolean isLock = false;
      try
      {
         CameraManager manager = (CameraManager) surfaceView.getContext().getSystemService(Context.CAMERA_SERVICE);
         String camList[] = manager.getCameraIdList();
         if (camList.length == 0)
         {
            Log.e(LOGTAG, "Error: No camera");
            if (errbuf != null) errbuf.append("Error: No camera");
            return false;
         }
         CameraCharacteristics characteristics = null;
         for (String cameraID : camList)
         {
            characteristics = manager.getCameraCharacteristics(cameraID);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing == null) continue;
            if (face == facing)
            {
               this.cameraID = cameraID;
               break;
            }
         }
         if (cameraID == null)
         {
            Log.e(LOGTAG, "Could not find matching camera");
            if (errbuf != null) errbuf.append("Error: Could not find matching camera");
            return false;
         }
         characteristics = manager.getCameraCharacteristics(cameraID);
         Boolean isFlashAvail = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
         hasFlash =  ( (isFlashAvail != null) && (isFlashAvail) );
         if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS))
            throw new RuntimeException("Time out waiting to lock camera opening.");
         isLock = true;
         setPreviewSize(width, height, errbuf);
         imageFormat = ((hasYUV) ? ImageFormat.YUV_420_888 : ((hasNV21) ? ImageFormat.NV21 : -1));
         if (imageFormat < 0)
         {
            Log.e(LOGTAG, "No supported output formats");
            throw new RuntimeException("No supported output formats");
         }
//         float[] focalLens = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS);

         int facing = Camera.CameraInfo.CAMERA_FACING_BACK;
         switch (face)
         {
            case CameraCharacteristics.LENS_FACING_BACK:
               facing = Camera.CameraInfo.CAMERA_FACING_BACK;
               break;
            case CameraCharacteristics.LENS_FACING_FRONT:
               facing = Camera.CameraInfo.CAMERA_FACING_FRONT;
               break;
         }
         Camera.CameraInfo camera1Info = new Camera.CameraInfo();
         Camera camera1 = null;
         try
         {
            for (int i = 0; i < Camera.getNumberOfCameras(); i++)
            {
               Camera.getCameraInfo(i, camera1Info);
               if (camera1Info.facing == facing)
               {
                  legacyCameraId = i;
                  try { camera1 = Camera.open(legacyCameraId); } catch (Exception _e) { camera1 = null; }
                  break;
               }
            }
            if (camera1 != null)
            {
               Camera.Parameters camera1Parameters = camera1.getParameters();
               fovx = camera1Parameters.getHorizontalViewAngle();
               fovy = camera1Parameters.getVerticalViewAngle();
               focalLen = camera1Parameters.getFocalLength();
            }
         }
         catch (Exception _e)
         {
            Log.e(LOGTAG, "", _e);
         }
         finally
         {
            if (camera1 != null)
               try { camera1.release(); } catch (Exception _e) { Log.e(LOGTAG, "", _e); }
         }

//       Android 5.0.1 bug (https://code.google.com/p/android/issues/detail?id=81984)
//       YUV_420_888 does not contain all U and V data
//       if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)
//          imageFormat = ImageFormat.NV21;
         if ((Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) && (hasNV21))
            imageFormat = ImageFormat.NV21;
         previewImageReader = ImageReader.newInstance(width, height, imageFormat, 2);
      }
      catch (SecurityException e)
      {
         Log.e(LOGTAG, "", e);
      }
      catch (Throwable e)
      {
         Log.e(LOGTAG, "", e);
         if (isLock)
            mCameraOpenCloseLock.release();
         return false;
      }
      return true;
   }

   private final CameraDevice.StateCallback cameraStateCallback = new CameraDevice.StateCallback()
   //=========================================================================================
   {

      @Override public void onOpened(CameraDevice cameraDevice)
      //-------------------------------------------------------
      {
         PreviewCamera.this.cameraDevice = cameraDevice;
         mCameraOpenCloseLock.release();
         createCameraPreviewSession();
      }

      @Override public void onDisconnected(CameraDevice cameraDevice)
      //-------------------------------------------------------------
      {
         cameraDevice.close();
         PreviewCamera.this.cameraDevice = null;
         mCameraOpenCloseLock.release();
      }

      @Override public void onError(CameraDevice cameraDevice, int error)
      //-------------------------------------------------------
      {
         cameraDevice.close();
         PreviewCamera.this.cameraDevice = null;
         mCameraOpenCloseLock.release();
      }
   };

   @Override
   @SuppressLint({"NewApi", "MissingPermission, UseCheckPermission"})
   @SuppressWarnings({"ResourceType"})
   public void startPreview(boolean isFlashOn)
   //-----------------------
   {
      if (cameraWidth < 0 || cameraHeight < 0)
         return;
      this.isFlashOn = isFlashOn;
      CameraManager manager = (CameraManager) surfaceView.getContext().getSystemService(Context.CAMERA_SERVICE);
      if (manager == null)
         return;
      try
      {
         cameraThread = new HandlerThread("CameraPreview");
         cameraThread.start();
         cameraHandler = new Handler(cameraThread.getLooper());
         manager.openCamera(cameraID, cameraStateCallback, cameraHandler);
      }
      catch (Exception e)
      {
         Log.e(LOGTAG, "", e);
         throw new RuntimeException(e);
      }
   }

   private void createCameraPreviewSession()
   //---------------------------------------
   {
      try
      {
         mCameraOpenCloseLock.acquire();
         if (null == cameraDevice)
         {
            mCameraOpenCloseLock.release();
            Log.e(LOGTAG, "startPreview: camera isn't opened");
            return;
         }
         if (null != captureSession)
         {
            mCameraOpenCloseLock.release();
            Log.e(LOGTAG, "startPreview: captureSession is already started");
            return;
         }
         previewSurface = previewImageReader.getSurface();
         renderer.previewSurfaceTexture.setDefaultBufferSize(cameraWidth, cameraHeight);
         final CaptureRequest.Builder previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
         displaySurface = renderer.newDisplaySurface();
         previewRequestBuilder.addTarget(displaySurface);
         previewRequestBuilder.addTarget(previewSurface);
         previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);
//         previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//         previewRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, 0.0f);
         if ( (fps != null) && (fps.length > 0) )
            previewRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fps[fps.length - 1]);
//         previewRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON);
         if (isFlashOn)
         {
            CameraManager manager = (CameraManager) surfaceView.getContext().getSystemService(Context.CAMERA_SERVICE);
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID);
            Boolean isFlashAvail = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            if ( (isFlashAvail != null) && (isFlashAvail) )
               previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
         }
         CameraCaptureSession.StateCallback cameraStatusCallback = new CameraCaptureSession.StateCallback()
         {
            @Override
            public void onClosed(CameraCaptureSession session)
            {
               Log.i(LOGTAG, "Camera2 closed");
            }

            @Override
            public void onReady(CameraCaptureSession session)
            {
               Log.i(LOGTAG, "Camera2 ready");
            }

            @Override
            public void onConfigured(CameraCaptureSession session)
            //-----------------------------------------------------------------
            {
               captureSession = session;
               try
               {
                  previewThread = new HandlerThread("CameraPreview");
                  previewThread.start();
                  previewHandler = new Handler(previewThread.getLooper());
                  previewImageReader.setOnImageAvailableListener(imageAvailableListener, previewHandler);

                  captureSession.setRepeatingRequest(previewRequestBuilder.build(), null, null); //cameraHandler);
                  Log.i(LOGTAG, "CameraPreviewSession has been started");
                  isPreviewing = true;
               }
               catch (Throwable e)
               {
                  Log.e(LOGTAG, "createCaptureSession failed", e);
                  throw new RuntimeException(e);
               }
               finally
               {
                  mCameraOpenCloseLock.release();
               }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session)
            //---------------------------------------------------------
            {
               Log.e(LOGTAG, "startPreview failed");
               mCameraOpenCloseLock.release();
            }
         };
         captureThread = new HandlerThread("CameraCapture");
         captureThread.start();
         captureHandler = new Handler(captureThread.getLooper());
         cameraDevice.createCaptureSession(Arrays.asList(previewSurface, displaySurface), cameraStatusCallback, captureHandler);
      }
      catch (CameraAccessException e)
      {
         Log.e(LOGTAG, "startPreview");
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException("Interrupted while in startPreview", e);
      }
      finally
      {
         //mCameraOpenCloseLock.release();
      }
   }

   @Override
   public void close()
   //-----------------
   {
      Log.i(LOGTAG, "closeCamera");
      try
      {
         mCameraOpenCloseLock.acquire();
         if (null != captureSession)
         {
            captureSession.close();
            captureSession = null;
            isPreviewing = false;
         }
         if (null != cameraDevice)
         {
            cameraDevice.close();
            cameraDevice = null;
         }
         if (cameraThread != null)
            cameraThread.quit();
         cameraHandler = null;
         if (previewThread != null)
            previewThread.quit();
         previewHandler = null;
         if (captureThread != null)
            captureThread.quit();
         captureHandler = null;
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
      }
      finally
      {
         mCameraOpenCloseLock.release();
      }
   }

   public void suspendPreview()
   //--------------------------
   {
      if (previewImageReader != null)
         previewImageReader.setOnImageAvailableListener(null, null);
   }

   public void restartPreview()
   //--------------------------
   {
      if ( (previewImageReader != null) && (imageAvailableListener != null) )
         previewImageReader.setOnImageAvailableListener(imageAvailableListener, cameraHandler);
   }

   @Override
   public void stopPreview()
   //----------------------
   {
      try
      {
         mCameraOpenCloseLock.acquire();
         if (null != captureSession)
         {
            captureSession.close();
            captureSession = null;
            isPreviewing = false;
         }
         displaySurface = renderer.newDisplaySurface();
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
      }
      finally
      {
         mCameraOpenCloseLock.release();
      }
   }

   @Override public boolean isPreviewing() { return isPreviewing; }

   @Override public int getPreviewWidth() { return cameraWidth;}

   @Override public int getPreviewHeight() { return cameraHeight; }

   @Override public int getPreviewBufferSize() { return frameBuffer.getFrameSize(); }

   @Override public void setPreviewWidth(int width) { cameraWidth = width; }

   @Override public  void setPreviewHeight(int height) { cameraHeight = height; }

   @Override
   public String[] availableResolutions() { return resolutions; }

   public boolean setPreviewSize(final int width, final int height, StringBuilder errbuf)
   //------------------------------------------------------------------------------
   {
      Log.i(LOGTAG, "setPreviewSize: " + width + "x" + height);
      if (cameraID == null)
      {
         Log.e(LOGTAG, "Camera isn't initialized!");
         return false;
      }
      CameraManager manager = (CameraManager) surfaceView.getContext().getSystemService(Context.CAMERA_SERVICE);
      try
      {
         CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID);
         fps = characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES);
         StreamConfigurationMap streamConfig = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
         if (streamConfig != null)
         {
            int[] outputs = streamConfig.getOutputFormats();
            if (outputs != null)
            {
               for (int c : outputs)
               {
                  Log.i(LOGTAG, "Supported Camera Format: " + RecorderActivity.imageFormatString(c));
                  switch (c)
                  {
                     case ImageFormat.YUV_420_888: hasYUV = true; break;
                     case ImageFormat.NV21:        hasNV21 = true; break;
                  }
               }
            }
         }
         else
         {
            hasYUV = (streamConfig.getOutputSizes(ImageFormat.YUV_420_888) != null);
            hasNV21 = (streamConfig.getOutputSizes(ImageFormat.NV21) != null);
         }
         if ((!hasYUV) && (!hasNV21))
         {
            hasYUV = (streamConfig.getOutputSizes(ImageFormat.YUV_420_888) != null);
            hasNV21 = (streamConfig.getOutputSizes(ImageFormat.NV21) != null);
         }

         int bestWidth = 0, bestHeight = 0;
         float aspect = (float) width / height;
         Size[] sizes = null;
         if (streamConfig != null)
            sizes = streamConfig.getOutputSizes(SurfaceTexture.class);
         if (sizes != null)
         {
            int i = 0;
            resolutions = new String[sizes.length];
            for (Size psize : sizes)
            {
               int w = psize.getWidth(), h = psize.getHeight();
               resolutions[i++] = String.format("%dx%d", w, h);
               if ((width >= w) && (height >= h) && (bestWidth <= w) && (bestHeight <= h) &&
                     (Math.abs(aspect - (float) w / h) < 0.2))
               {
                  bestWidth = w;
                  bestHeight = h;
               }
            }
         }
         Log.i(LOGTAG, "best size: " + bestWidth + "x" + bestHeight);
         if ( (bestWidth == 0) || (bestHeight == 0) )
         {
            if (errbuf != null) errbuf.append("Error finding matching preview size for ").append(width).append('x').
                  append(height);
            Log.e(LOGTAG, "Error finding matching preview size");
            return false;
         }
         else
         {
            cameraWidth = bestWidth;
            cameraHeight = bestHeight;
            return true;
         }
      }
      catch (CameraAccessException e)
      {
         Log.e(LOGTAG, "cacPreviewSize - Camera Access Exception");
      }
      catch (IllegalArgumentException e)
      {
         Log.e(LOGTAG, "cacPreviewSize - Illegal Argument Exception");
      }
      catch (SecurityException e)
      {
         Log.e(LOGTAG, "cacPreviewSize - Security Exception");
      }
      return false;
   }

   @Override
   public void freeze(Bundle B)
   //------------------------
   {
      B.putString("cameraID", cameraID);
      B.putInt("cameraWidth", cameraWidth);
      B.putInt("cameraHeight", cameraHeight);
      B.putBoolean("hasYUV", hasYUV);
      B.putBoolean("hasNV21", hasNV21);
      B.putBoolean("isPreviewing", isPreviewing);
      B.putInt("ImageFormat", imageFormat);
   }

   @Override
   public void thaw(Bundle B)
   //--------------------------
   {
      cameraID = B.getString("cameraID");
      cameraWidth = B.getInt("cameraWidth");
      cameraHeight = B.getInt("cameraHeight");
      hasYUV = B.getBoolean("hasYUV");
      hasNV21 = B.getBoolean("hasNV21");
      isPreviewing = B.getBoolean("isPreviewing");
      imageFormat = B.getInt("ImageFormat");
   }

   @Override public PreviewData pop() { throw new RuntimeException("N/A (NativeFrameBuffer writes data)"); }

   @Override public String getPreviewFormat()
   //----------------------------------------
   {
      imageFormat = ((hasYUV) ? ImageFormat.YUV_420_888 : ((hasNV21) ? ImageFormat.NV21 : -1));
      switch (imageFormat)
      {
         case ImageFormat.YUV_420_888: return "YUV_420_888";
         case ImageFormat.NV21:        return "NV21";
         default:                      return "UNKNOWN";
      }
   }

   ByteBuffer imagebuf = null;

   @Override public void releaseFrame() { }

   private final ImageReader.OnImageAvailableListener imageAvailableListener
         = new ImageReader.OnImageAvailableListener()
   //========================================================================
   {
      @Override
      public void onImageAvailable(ImageReader reader)
      //----------------------------------------------
      {
         Image image;
         try { image = reader.acquireNextImage(); } catch (Exception e) { Log.e(LOGTAG, "", e); image = null; }
         if (image == null)
            return;
         if (mustBuffer)
         {
            Image.Plane[] planes = image.getPlanes();
            long timestamp = SystemClock.elapsedRealtimeNanos();
            Image.Plane Yplane = planes[0];
            Image.Plane Uplane = planes[1];
            Image.Plane Vplane = planes[2];
            ByteBuffer Y = Yplane.getBuffer();
            ByteBuffer U = Uplane.getBuffer();
            ByteBuffer V = Vplane.getBuffer();
            Y.rewind();
            U.rewind();
            V.rewind();
            final int ylen = Y.remaining();
            final int ulen = U.remaining();
            final int vlen = V.remaining();
            final int ustride = Uplane.getPixelStride();
            final int vstride = Vplane.getPixelStride();
            frameBuffer.pushYUV(timestamp, Y, ylen, U, ulen, ustride, V, vlen, vstride, 5);
         }
         image.close();
         frameAvailCondVar.open();
      }
   };

   public byte[] toRGBA(Context context, byte[] frame, int previewWidth, int previewHeight, int rgbaSize, byte[] grey)
   //----------------------------------------------------------------------------------------------------------------
   {
      try
      {
         final int inputFormat = ImageFormat.YUV_420_888;
         Type.Builder yuvTypeBuilder = new Type.Builder(renderscript, Element.YUV(renderscript));
         yuvTypeBuilder.setX(previewWidth).setY(previewHeight).setYuvFormat(inputFormat);
         Allocation allocYUVIn = Allocation.createTyped(renderscript, yuvTypeBuilder.create(), Allocation.USAGE_SCRIPT);

         Type.Builder rgbTypeBuilder = new Type.Builder(renderscript, Element.RGBA_8888(renderscript));
         rgbTypeBuilder.setX(previewWidth).setY(previewHeight);
         Allocation allocRGBAOut = Allocation.createTyped(renderscript, rgbTypeBuilder.create(), Allocation.USAGE_SCRIPT);

         ScriptIntrinsicYuvToRGB YUVToRGB = ScriptIntrinsicYuvToRGB.create(renderscript, Element.RGBA_8888(renderscript));
         allocYUVIn.copyFrom(frame);
         YUVToRGB.setInput(allocYUVIn);
         YUVToRGB.forEach(allocRGBAOut);
         byte[] rgbaBuffer = new byte[rgbaSize];
         allocRGBAOut.copyTo(rgbaBuffer);
         if (grey != null)
         {
            Type.Builder greyTypeBuilder = new Type.Builder(renderscript, Element.U8(renderscript));
            greyTypeBuilder.setX(cameraWidth).setY(cameraHeight);
            Allocation allocGrayOut = Allocation.createTyped(renderscript, greyTypeBuilder.create(), Allocation.USAGE_SCRIPT);
            ScriptC_yuv2grey rsYUVtoGrey = new ScriptC_yuv2grey(renderscript);
            allocYUVIn.copyFrom(frame);
            rsYUVtoGrey.set_in(allocYUVIn);
            rsYUVtoGrey.forEach_yuv2grey(allocGrayOut);
            allocGrayOut.copyTo(grey);
         }
         return rgbaBuffer;
      }
      catch (Exception e)
      {
         Log.e(LOGTAG, "", e);
         return null;
      }
   }
}


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace boundary_views
{

template
<
    typename Polygon,
    typename Value = typename ring_type<Polygon>::type,
    typename Reference = typename ring_return_type<Polygon>::type,
    typename Difference = typename boost::range_difference
        <
            typename boost::remove_reference
                <
                    typename interior_return_type<Polygon>::type
                >::type
        >::type
>
class polygon_rings_iterator
    : public boost::iterator_facade
        <
            polygon_rings_iterator<Polygon, Value, Reference, Difference>,
            Value,
            boost::random_access_traversal_tag,
            Reference,
            Difference
        >
{
    typedef typename boost::range_size
        <
            typename boost::remove_reference
                <
                    typename interior_return_type<Polygon>::type
                >::type
        >::type size_type;

public:
    // default constructor
    polygon_rings_iterator()
        : m_polygon(NULL)
        , m_index(0)
    {}

    // for begin
    polygon_rings_iterator(Polygon& polygon)
        : m_polygon(boost::addressof(polygon))
        , m_index(0)
    {}

    // for end
    polygon_rings_iterator(Polygon& polygon, bool)
        : m_polygon(boost::addressof(polygon))
        , m_index(static_cast<size_type>(num_rings(polygon)))
    {}

    template
    <
        typename OtherPolygon,
        typename OtherValue,
        typename OtherReference,
        typename OtherDifference
    >
    polygon_rings_iterator(polygon_rings_iterator
                           <
                               OtherPolygon,
                               OtherValue,
                               OtherReference,
                               OtherDifference
                           > const& other)
        : m_polygon(other.m_polygon)
        , m_index(other.m_index)
    {
        static const bool is_convertible
            = boost::is_convertible<OtherPolygon, Polygon>::value;

        BOOST_MPL_ASSERT_MSG((is_convertible),
                             NOT_CONVERTIBLE,
                             (types<OtherPolygon>));
    }

private:
    friend class boost::iterator_core_access;

    template
    <
        typename OtherPolygon,
        typename OtherValue,
        typename OtherReference,
        typename OtherDifference
    >
    friend class polygon_rings_iterator;

    static inline std::size_t num_rings(Polygon const& polygon)
    {
        return geometry::num_interior_rings(polygon) + 1;
    }

    inline Reference dereference() const
    {
        if (m_index == 0)
        {
            return exterior_ring(*m_polygon);
        }
        return range::at(interior_rings(*m_polygon), m_index - 1);
    }

    template
    <
        typename OtherPolygon,
        typename OtherValue,
        typename OtherReference,
        typename OtherDifference
    >
    inline bool equal(polygon_rings_iterator
                      <
                          OtherPolygon,
                          OtherValue,
                          OtherReference,
                          OtherDifference
                      > const& other) const
    {
        BOOST_GEOMETRY_ASSERT(m_polygon == other.m_polygon);
        return m_index == other.m_index;
    }

    inline void increment()
    {
        ++m_index;
    }

    inline void decrement()
    {
        --m_index;
    }

    template
    <
        typename OtherPolygon,
        typename OtherValue,
        typename OtherReference,
        typename OtherDifference
    >
    inline Difference distance_to(polygon_rings_iterator
                                  <
                                      OtherPolygon,
                                      OtherValue,
                                      OtherReference,
                                      OtherDifference
                                  > const& other) const
    {
        return static_cast<Difference>(other.m_index)
            - static_cast<Difference>(m_index);
    }

    inline void advance(Difference n)
    {
        m_index += n;
    }

private:
    Polygon* m_polygon;
    size_type m_index;
};

template <typename Ring>
class ring_boundary : closeable_view<Ring, closure<Ring>::value>::type
{
private:
    typedef typename closeable_view<Ring, closure<Ring>::value>::type base_type;

public:
    typedef typename base_type::iterator iterator;
    typedef typename base_type::const_iterator const_iterator;

    typedef linestring_tag tag_type;

    explicit ring_boundary(Ring& ring)
        : base_type(ring) {}

    iterator begin() { return base_type::begin(); }
    iterator end() { return base_type::end(); }
    const_iterator begin() const { return base_type::begin(); }
    const_iterator end() const { return base_type::end(); }
};

template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct num_rings
{};

template <typename Polygon>
struct num_rings<Polygon, polygon_tag>
{
    static inline std::size_t apply(Polygon const& polygon)
    {
        return geometry::num_interior_rings(polygon) + 1;
    }
};

template <typename MultiPolygon>
struct num_rings<MultiPolygon, multi_polygon_tag>
{
    static inline std::size_t apply(MultiPolygon const& multipolygon)
    {
        return geometry::num_interior_rings(multipolygon)
            + static_cast<std::size_t>(boost::size(multipolygon));
    }
};

template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct views_container_initializer
{};

template <typename Polygon>
struct views_container_initializer<Polygon, polygon_tag>
{
    template <typename BoundaryView>
    static inline void apply(Polygon const& polygon, BoundaryView* views)
    {
        typedef polygon_rings_iterator<Polygon> rings_iterator_type;

        std::uninitialized_copy(rings_iterator_type(polygon),
                                rings_iterator_type(polygon, true),
                                views);
    }
};

template <typename MultiPolygon>
class views_container_initializer<MultiPolygon, multi_polygon_tag>
{
    typedef typename boost::mpl::if_
        <
            boost::is_const<MultiPolygon>,
            typename boost::range_value<MultiPolygon>::type const,
            typename boost::range_value<MultiPolygon>::type
        >::type polygon_type;

    typedef polygon_rings_iterator<polygon_type> inner_iterator_type;

    struct polygon_rings_begin
    {
        static inline inner_iterator_type apply(polygon_type& polygon)
        {
            return inner_iterator_type(polygon);
        }
    };

    struct polygon_rings_end
    {
        static inline inner_iterator_type apply(polygon_type& polygon)
        {
            return inner_iterator_type(polygon, true);
        }
    };

    typedef flatten_iterator
        <
            typename boost::range_iterator<MultiPolygon>::type,
            inner_iterator_type,
            typename std::iterator_traits<inner_iterator_type>::value_type,
            polygon_rings_begin,
            polygon_rings_end,
            typename std::iterator_traits<inner_iterator_type>::reference
        > rings_iterator_type;

public:
    template <typename BoundaryView>
    static inline void apply(MultiPolygon const& multipolygon,
                             BoundaryView* views)
    {
        rings_iterator_type first(boost::begin(multipolygon),
                                  boost::end(multipolygon));
        rings_iterator_type last(boost::end(multipolygon));

        std::uninitialized_copy(first, last, views);
    }
};

template <typename Areal>
class areal_boundary
{
    typedef boundary_view<typename ring_type<Areal>::type> boundary_view_type;
    typedef views_container_initializer<Areal> exception_safe_initializer;

    template <typename T>
    struct automatic_deallocator
    {
        automatic_deallocator(T* ptr) : m_ptr(ptr) {}

        ~automatic_deallocator()
        {
            operator delete(m_ptr);
        }

        inline void release() { m_ptr = NULL; }

        T* m_ptr;
    };

    inline void initialize_views(Areal const& areal)
    {
        // initialize number of rings
        std::size_t n_rings = num_rings<Areal>::apply(areal);

        if (n_rings == 0)
        {
            return;
        }

        // allocate dynamic memory
        boundary_view_type* views_ptr = static_cast
            <
                boundary_view_type*
            >(operator new(sizeof(boundary_view_type) * n_rings));

        // initialize; if exceptions are thrown by constructors
        // they are handled automatically by automatic_deallocator
        automatic_deallocator<boundary_view_type> deallocator(views_ptr);
        exception_safe_initializer::apply(areal, views_ptr);
        deallocator.release();

        // now initialize member variables safely
        m_views = views_ptr;
        m_num_rings = n_rings;
    }

    // disallow copies and/or assignments
    areal_boundary(areal_boundary const&);
    areal_boundary& operator=(areal_boundary const&);

public:
    typedef boundary_view_type* iterator;
    typedef boundary_view_type const* const_iterator;

    typedef multi_linestring_tag tag_type;

    explicit areal_boundary(Areal& areal)
        : m_views(NULL)
        , m_num_rings(0)
    {
        initialize_views(areal);
    }

    ~areal_boundary()
    {
        boundary_view_type* last = m_views + m_num_rings;
        for (boundary_view_type* it = m_views; it != last; ++it)
        {
            it->~boundary_view_type();
        }
        operator delete(m_views);
    }

    inline iterator begin() { return m_views; }
    inline iterator end() { return m_views + m_num_rings; }
    inline const_iterator begin() const { return m_views; }
    inline const_iterator end() const { return m_views + m_num_rings; }

private:
    boundary_view_type* m_views;
    std::size_t m_num_rings;
};

}} // namespace detail::boundary_view
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace detail_dispatch
{

template <typename Ring>
struct boundary_view<Ring, ring_tag>
    : detail::boundary_views::ring_boundary<Ring>
{
    explicit boundary_view(Ring& ring)
        : detail::boundary_views::ring_boundary<Ring>(ring)
    {}
};

template <typename Polygon>
struct boundary_view<Polygon, polygon_tag>
    : detail::boundary_views::areal_boundary<Polygon>
{
    explicit boundary_view(Polygon& polygon)
        : detail::boundary_views::areal_boundary<Polygon>(polygon)
    {}
};

template <typename MultiPolygon>
struct boundary_view<MultiPolygon, multi_polygon_tag>
    : detail::boundary_views::areal_boundary<MultiPolygon>
{
    explicit boundary_view(MultiPolygon& multipolygon)
        : detail::boundary_views::areal_boundary
            <
                MultiPolygon
            >(multipolygon)
    {}
};

} // namespace detail_dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_VIEWS_DETAIL_BOUNDARY_VIEW_IMPLEMENTATION_HPP

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

<title>localhost</title>

Select spectrum files to compare:

<form method="post">
  <input type="submit" value="Compare Spectra">

    {% for file in files %}

	<input type="checkbox" name="file" value="{{file}}">

	{{file}}

    {% endfor %}

</form>


text:
const expect = require('chai').expect
const sinon = require('sinon')

const proxyquire = require('proxyquire')
const userRole = require('../../../app/constants/user-roles')
const UserRole = require('../../../app/services/domain/user-role')
const removeDomainFromUsername = require('../../../app/services/user-role-service').removeDomainFromUsername

const DOMAIN_USERNAME = 'Staff.Test@test.com'
const STAFF_USER = { id: 0, username: 'Staff.Test', name: 'Staff Test' }

const STAFF_ROLE = { roleId: 0, role: userRole.STAFF }

let userRoleService
let getRoleByUsername
let updateUserRole
let addUserRole
let getRole
let getUserById
let getUserByUsername
let addUser
let removeUserRoleByUserId
let removeUserByUsername

beforeEach(function () {
  getRoleByUsername = sinon.stub()
  removeUserRoleByUserId = sinon.stub()
  removeUserByUsername = sinon.stub()
  getUserByUsername = sinon.stub()
  updateUserRole = sinon.stub()
  addUserRole = sinon.stub()
  getRole = sinon.stub()
  getUserById = sinon.stub()
  addUser = sinon.stub()
  userRoleService =
    proxyquire('../../../app/services/user-role-service',
      {
        './data/remove-user-role-by-user-id': removeUserRoleByUserId,
        './data/remove-user-by-username': removeUserByUsername,
        './data/get-user-role-by-username': getRoleByUsername,
        './data/get-user-by-username': getUserByUsername,
        './data/update-user-role': updateUserRole,
        './data/insert-user-role': addUserRole,
        './data/get-user-by-id': getUserById,
        './data/insert-user': addUser,
        './data/get-role': getRole
      })
})

describe('services/user-role-service', function () {
  it('should return a user role object with the right information', function () {
    getRoleByUsername.resolves(STAFF_ROLE)
    return userRoleService.getRoleByUsername(STAFF_USER.username)
      .then(function (result) {
        expect(result).to.equal(STAFF_ROLE)
      })
  })

  it('should return a role object with the right information', function () {
    getRole.resolves(STAFF_ROLE)
    return userRoleService.getRole(userRole.STAFF)
      .then(function (result) {
        expect(result).to.equal(STAFF_ROLE)
      })
  })

  it('should return staff role if no role returned from database', function () {
    getRole.resolves()
    return userRoleService.getRole('Random Role')
      .then(function (result) {
        expect(result).to.deep.equal({ role: userRole.STAFF })
      })
  })

  it('should return a user object with the right information', function () {
    getUserByUsername.resolves(STAFF_USER)
    return userRoleService.getUserByUsername(STAFF_USER.username)
      .then(function (result) {
        expect(result).to.equal(STAFF_USER)
      })
  })

  it('should return a user object with the right information', function () {
    getUserById.resolves(STAFF_USER)
    return userRoleService.getUserById(STAFF_USER.id)
      .then(function (result) {
        expect(result).to.equal(STAFF_USER)
      })
  })

  it('should add a user', function () {
    addUser.resolves(STAFF_ROLE.id)
    return userRoleService.addUser(STAFF_USER.username, STAFF_ROLE.name)
      .then(function (result) {
        expect(result).to.equal(STAFF_ROLE.id)
      })
  })

  it('should add a user role', function () {
    addUserRole.resolves(1)
    return userRoleService.addUserRole(new UserRole(1, 1, new Date(), 1))
      .then(function (result) {
        expect(result).to.equal(1)
      })
  })

  it('should update a user role', function () {
    updateUserRole.resolves(1)
    return userRoleService.updateUserRole(new UserRole(1, 2, new Date(), 1))
      .then(function (result) {
        expect(result).to.equal(1)
      })
  })

  it('should remove a user role by user id', function () {
    removeUserRoleByUserId.resolves(STAFF_ROLE.id)
    return userRoleService.removeUserRoleByUserId(STAFF_ROLE.id)
      .then(function (result) {
        expect(result).to.equal(STAFF_ROLE.id)
      })
  })

  it('should remove a user by username', function () {
    removeUserByUsername.resolves(1)
    return userRoleService.removeUserByUsername(STAFF_USER.username)
      .then(function (result) {
        expect(result).to.equal(1)
      })
  })

  it('should return the username without the domain name', function () {
    const result = removeDomainFromUsername(DOMAIN_USERNAME)
    expect(result).to.equal(STAFF_USER.username)
  })
})


text:
"""Parser for 454 Flowgram files in native binary format."""

__author__ = 'Kyle Bittinger'
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__license__ = 'GPL'
__version__ = "1.5.3"
__credits__ = ['Kyle Bittinger']
__maintainer__ = 'Kyle Bittinger'
__email__ = 'kylebittinger@gmail.com'
__status__ = 'Prototype'

from cStringIO import StringIO
import string
import struct

# Sections were inspired by, but not derived from, several other implementations:
# * BioPython (biopython.org)
# * sff_extract (www.melogen.upv.es/sff_extract)
# * Mothur (mothur.org)

class NamedStruct(struct.Struct):
    """Enhanced Struct class that associates names with each item in the struct.
    """

    def __init__(self, format, keys):
        """Create a new NamedStruct with a list of keys.
        """
        self.keys = keys
        super(NamedStruct, self).__init__(format)

    def read_from(self, file):
        """Read the struct from a file object and return the values as a dict.
        """
        buff = file.read(self.size)
        return self.unpack(buff)

    def pack(self, dict_of_vals):
        vals = [dict_of_vals[k] for k in self.keys]
        return super(NamedStruct, self).pack(*vals)

    def unpack(self, buffer):
        vals = super(NamedStruct, self).unpack(buffer)
        return dict(zip(self.keys, vals))

def seek_pad(file, unit=8):
    """Set a file's position to the next multiple of a given number.
    """
    position = file.tell()
    rem = position % unit
    if rem != 0:
        padding = unit - rem
        file.seek(padding, 1)

def write_pad(file, unit=8):
    """Write zeros until the file's position is a multiple of the given number.
    """
    position = file.tell()
    rem = position % unit
    if rem != 0:
        num_bytes = unit - rem
        padding_bytes = '\x00' * num_bytes
        file.write(padding_bytes)

common_header_fields = [
    'magic_number',
    'version',
    'index_offset',
    'index_length',
    'number_of_reads',
    'header_length',
    'key_length',
    'number_of_flows_per_read',
    'flowgram_format_code',
    ]

common_header_struct = NamedStruct('>IIQIIHHHB', common_header_fields)

def parse_common_header(sff_file):
    """Parse a Common Header section from a binary SFF file.

    Keys in the resulting dict are identical to those defined in the
    Roche documentation.

    As a side effect, sets the position of the file object to the end
    of the Common Header section.
    """
    h = common_header_struct.read_from(sff_file)
    h['flow_chars'] = sff_file.read(h['number_of_flows_per_read'])
    h['key_sequence'] = sff_file.read(h['key_length'])
    seek_pad(sff_file)
    return h

def write_common_header(sff_file, header):
    """Write a common header section to a binary SFF file.
    """
    header_bytes = common_header_struct.pack(header)
    sff_file.write(header_bytes)
    sff_file.write(header['flow_chars'])
    sff_file.write(header['key_sequence'])
    write_pad(sff_file)

common_header_formats = [
    '  Magic Number:  0x%X\n',
    '  Version:       %04d\n',
    '  Index Offset:  %d\n',
    '  Index Length:  %d\n',
    '  # of Reads:    %d\n',
    '  Header Length: %d\n',
    '  Key Length:    %d\n',
    '  # of Flows:    %d\n',
    '  Flowgram Code: %d\n',
    ]

def format_common_header(header):
    """Format a dictionary representation of an SFF common header as text.
    """
    out = StringIO()
    out.write('Common Header:\n')
    for key, fmt in zip(common_header_fields, common_header_formats):
        val = header[key]
        out.write(fmt % val)
    out.write('  Flow Chars:    %s\n' % header['flow_chars'])
    out.write('  Key Sequence:  %s\n' % header['key_sequence'])
    return out.getvalue()

class UnsupportedSffError(Exception):
    pass

def validate_common_header(header):
    """Validate the Common Header section of a binary SFF file.

    Raises an UnsupportedSffError if the header is not supported.
    """
    supported_values = {
        'magic_number': 0x2E736666,
        'version': 1,
        'flowgram_format_code': 1,
        }
    for attr_name, expected_value in supported_values.items():
        observed_value = header[attr_name]
        if observed_value != expected_value:
            raise UnsupportedSffError(
                '%s not supported. (Expected %s, observed %s)' % (
                    attr_name, expected_value, observed_value))

read_header_fields = [
    'read_header_length',
    'name_length',
    'number_of_bases',
    'clip_qual_left',
    'clip_qual_right',
    'clip_adapter_left',
    'clip_adapter_right',
    ]

read_header_struct = NamedStruct('>HHIHHHH', read_header_fields)

def parse_read_header(sff_file):
    """Parse a Read Header section from a binary SFF file.

    Keys in the resulting dict are identical to those defined in the
    Roche documentation.

    As a side effect, sets the position of the file object to the end
    of the Read Header section.
    """
    data = read_header_struct.read_from(sff_file)
    data['Name'] = sff_file.read(data['name_length'])
    seek_pad(sff_file)
    return data

def write_read_header(sff_file, read_header):
    """Write a read header section to a binary SFF file.
    """
    header_bytes = read_header_struct.pack(read_header)
    sff_file.write(header_bytes)
    sff_file.write(read_header['Name'])
    write_pad(sff_file)

read_header_formats = [
    '  Read Header Len:  %d\n',
    '  Name Length:      %d\n',
    '  # of Bases:       %d\n',
    '  Clip Qual Left:   %d\n',
    '  Clip Qual Right:  %d\n',
    '  Clip Adap Left:   %d\n',
    '  Clip Adap Right:  %d\n',
    ]

def format_read_header(read_header):
    """Format a dictionary representation of an SFF read header as text.
    """
    out = StringIO()
    out.write('\n>%s\n' % read_header['Name'])
    timestamp, hashchar, region, location = decode_accession(read_header['Name'])
    out.write('  Run Prefix:   R_%d_%02d_%02d_%02d_%02d_%02d_\n' % timestamp)
    out.write('  Region #:     %d\n' % region)
    out.write('  XY Location:  %04d_%04d\n' % location)
    out.write('\n')
    for key, fmt in zip(read_header_fields, read_header_formats):
        val = read_header[key]
        out.write(fmt % val)
    return out.getvalue()

def parse_read_data(sff_file, number_of_bases, number_of_flows=400):
    """Parse a Read Data section from a binary SFF file.

    Keys in the resulting dict are identical to those defined in the
    Roche documentation.

    As a side effect, sets the position of the file object to the end
    of the Read Header section.
    """
    data = {}
    flow_fmt = '>' + ('H' * number_of_flows)
    base_fmt = '>' + ('B' * number_of_bases)
    flow_fmt_size = struct.calcsize(flow_fmt)
    base_fmt_size = struct.calcsize(base_fmt)

    buff = sff_file.read(flow_fmt_size)
    data['flowgram_values'] = struct.unpack(flow_fmt, buff)

    buff = sff_file.read(base_fmt_size)
    data['flow_index_per_base'] = struct.unpack(base_fmt, buff)

    data['Bases'] = sff_file.read(number_of_bases)

    buff = sff_file.read(base_fmt_size)
    data['quality_scores'] = struct.unpack(base_fmt, buff)

    seek_pad(sff_file)
    return data

def write_read_data(sff_file, read_data):
    """Write a read data section to a binary SFF file.
    """
    number_of_flows = len(read_data['flowgram_values'])
    number_of_bases = len(read_data['quality_scores'])
    flow_fmt = '>' + ('H' * number_of_flows)
    base_fmt = '>' + ('B' * number_of_bases)

    flow_bytes = struct.pack(flow_fmt, *read_data['flowgram_values'])
    sff_file.write(flow_bytes)

    index_bytes = struct.pack(base_fmt, *read_data['flow_index_per_base'])
    sff_file.write(index_bytes)

    sff_file.write(read_data['Bases'])

    qual_bytes = struct.pack(base_fmt, *read_data['quality_scores'])
    sff_file.write(qual_bytes)

    write_pad(sff_file)

def format_read_data(read_data, read_header):
    """Format a dictionary representation of an SFF read data as text.

    The read data is expected to be in native flowgram format.
    """
    out = StringIO()
    out.write('\n')

    out.write('Flowgram:')
    for x in read_data['flowgram_values']:
        out.write('\t%01.2f' % (x * 0.01))
    out.write('\n')

    out.write('Flow Indexes:')
    current_index = 0
    for i in read_data['flow_index_per_base']:
        current_index = current_index + i
        out.write('\t%d' % current_index)
    out.write('\n')

    out.write('Bases:\t')
    # Roche uses 1-based indexing
    left_idx = read_header['clip_qual_left'] - 1
    right_idx = read_header['clip_qual_right'] - 1
    for i, base in enumerate(read_data['Bases']):
        if (i < left_idx) or (i > right_idx):
            out.write(base.lower())
        else:
            out.write(base.upper())
    out.write('\n')

    out.write('Quality Scores:')
    for score in read_data['quality_scores']:
        out.write('\t%d' % score)
    out.write('\n')

    return out.getvalue()

def parse_read(sff_file, number_of_flows=400):
    """Parse a single read from a binary SFF file.

    Keys in the resulting dict are identical to those defined in the
    Roche documentation for the Read Header and Read Data sections.

    As a side effect, sets the position of the file object to the end
    of the Read Data section.
    """
    header_data = parse_read_header(sff_file)
    read_data = parse_read_data(
        sff_file, header_data['number_of_bases'], number_of_flows)
    read_data.update(header_data)
    return read_data

def write_read(sff_file, read):
    """Write a single read to a binary SFF file.
    """
    write_read_header(sff_file, read)
    write_read_data(sff_file, read)

def format_read(read):
    """Format a dictionary representation of an SFF read as text.
    """
    out = StringIO()
    out.write(format_read_header(read))
    out.write(format_read_data(read, read))
    return out.getvalue()

def parse_binary_sff(sff_file, native_flowgram_values=False):
    """Parse a binary SFF file, returning the header and a sequence of reads.

    In the binary file, flowgram values are stored as integers, 100
    times larger than the normalized floating point value.  Because
    the conversion is relatively expensive, we allow the computation
    to be skipped if the keyword argument native_flowgram_values is
    True.
    """
    header = parse_common_header(sff_file)
    number_of_flows = header['number_of_flows_per_read']
    validate_common_header(header)
    def get_reads():
        for i in range(header['number_of_reads']):

            # Skip the index section
            if sff_file.tell() == header['index_offset']:
                sff_file.seek(header['index_length'], 1)

            read = parse_read(sff_file, number_of_flows)

            if not native_flowgram_values:
                read['flowgram_values'] = [x * 0.01 for x in read['flowgram_values']]

            yield read
    return header, get_reads()

def write_binary_sff(sff_file, header, reads):
    """Write a binary SFF file, using provided header and read dicts.
    """
    sff_file.seek(0)
    sff_file.truncate()
    write_common_header(sff_file, header)
    for read in reads:
        write_read(sff_file, read)

def format_binary_sff(sff_file, output_file=None):
    """Write a text version of a binary SFF file to an output file.

    If no output file is provided, an in-memory file-like buffer is
    used (namely, a StringIO object).
    """
    if output_file is None:
        output_file = StringIO()
    header, reads = parse_binary_sff(sff_file, True)
    output_file.write(format_common_header(header))
    for read in reads:
        output_file.write(format_read(read))
    return output_file

def base36_encode(n):
    """Convert a positive integer to a base36 string.

    Following the conventions outlined in the Roche 454 manual, the
    numbers 0-25 are represented by letters, and the numbers 36-35 are
    represented by digits.

    Based on the code example at http://en.wikipedia.org/wiki/Base_36
    """
    if n < 0:
        raise ValueError('Only poitive numbers are supported.')
    chars = []
    while n != 0:
        n, remainder = divmod(n, 36)
        chars.append(base36_encode.alphabet[remainder])
    return ''.join(chars)

base36_encode.alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

def base36_decode(base36_str):
    """Convert a base36 string to a positive integer.

    Following the conventions outlined in the Roche 454 manual, the
    numbers 0-25 are represented by letters, and the numbers 36-35 are
    represented by digits.
    """
    base36_str = base36_str.translate(base36_decode.translation)
    return int(base36_str, 36)

base36_decode.translation = string.maketrans(
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    )

def decode_location(location_str):
    """Decode a base36-encoded well location, in Roche 454 format.

    Such timestamps are embedded in the final 5 characters of Roche
    \"universal\" accession numbers.
    """
    return divmod(base36_decode(location_str), 4096)

def decode_timestamp(timestamp_str):
    """Decode a base36-encoded timestamp, in Roche 454 format.

    Such timestamps are embedded in the first 6 characters of Roche
    \"universal\" accession numbers and SFF filenames.
    """
    n = base36_decode(timestamp_str)
    year, n = divmod(n, 13 * 32 * 24 * 60 * 60)
    year = year + 2000
    month, n = divmod(n, 32 * 24 * 60 * 60)
    day, n = divmod(n, 24 * 60 * 60)
    hour, n = divmod(n, 60 * 60)
    minute, second = divmod(n, 60)
    return year, month, day, hour, minute, second

def decode_accession(accession):
    """Decode a Roche 454 \"universal\" accession number.
    """
    assert len(accession) == 14
    timestamp = decode_timestamp(accession[:6])
    hashchar = accession[6]
    region = int(accession[7:9])
    location = decode_location(accession[9:14])
    return timestamp, hashchar, region, location

def decode_sff_filename(sff_filename):
    """Decode a Roche 454 SFF filename, returning a timestamp and other info.
    """
    assert len(sff_filename) == 13
    assert sff_filename.endswith('.sff')
    timestamp = decode_timestamp(sff_filename[:6])
    hashchar = sff_filename[6]
    region = int(sff_filename[7:9])
    return timestamp, hashchar, region


text:
cask 'mps' do
  version '2018.1,181.1168'
  sha256 'be094a907f63502756b48beb70e5ccc7e30d43dfff61d0138f9a27d05504b14f'

  url "https://download.jetbrains.com/mps/#{version.before_comma.major_minor}/MPS-#{version.before_comma}-macos-jdk-bundled.dmg"
  appcast 'https://data.services.jetbrains.com/products/releases?code=MPS&latest=true&type=release',
          checkpoint: 'caaf4be8c21071fab067172bbc8c9f06730c138d710657bb6123113454380c98'
  name 'JetBrains MPS'
  homepage 'https://www.jetbrains.com/mps/'

  auto_updates true

  app "MPS #{version.major_minor}.app"

  uninstall_postflight do
    ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'mps') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? }
  end

  zap trash: [
               "~/MPSSamples.#{version.before_comma.major_minor}",
               "~/Library/Application Support/MPS#{version.before_comma.major_minor}",
               "~/Library/Caches/MPS#{version.before_comma.major_minor}",
               "~/Library/Logs/MPS#{version.before_comma.major_minor}",
               "~/Library/Preferences/MPS#{version.before_comma.major_minor}",
             ]
end


text:
import {
  ChangeDetectorRef,
  Directive,
  ElementRef,
  forwardRef,
  Host,
  OnDestroy,
  OnInit,
  Provider,
  Renderer2
} from '@angular/core';

import {
  AbstractControl,
  ControlValueAccessor,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  ValidationErrors,
  Validator
} from '@angular/forms';

import {
  formatDate,
  getLocale,
  isAfter,
  isBefore,
  isDate,
  isDateValid,
  parseDate,
  utcAsLocal
} from 'ngx-bootstrap/chronos';

import { BsDatepickerDirective } from './bs-datepicker.component';
import { BsLocaleService } from './bs-locale.service';
import { Subscription } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

const BS_DATEPICKER_VALUE_ACCESSOR: Provider = {
  provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => BsDatepickerInputDirective),
  multi: true
};

const BS_DATEPICKER_VALIDATOR: Provider = {
  provide: NG_VALIDATORS,
    useExisting: forwardRef(() => BsDatepickerInputDirective),
  multi: true
};

@Directive({
  selector: `input[bsDatepicker]`,
  // eslint-disable-next-line @angular-eslint/no-host-metadata-property
  host: {
    '(change)': 'onChange($event)',
    '(keyup.esc)': 'hide()',
    '(keydown)': 'onKeydownEvent($event)',
    '(blur)': 'onBlur()'
  },
  providers: [BS_DATEPICKER_VALUE_ACCESSOR, BS_DATEPICKER_VALIDATOR]
})
export class BsDatepickerInputDirective
  implements ControlValueAccessor, Validator, OnInit, OnDestroy {
  private _onChange = Function.prototype;
  private _onTouched = Function.prototype;
    private _validatorChange = Function.prototype;
  private _value?: Date;
  private _subs = new Subscription();

  constructor(@Host() private _picker: BsDatepickerDirective,
              private _localeService: BsLocaleService,
              private _renderer: Renderer2,
              private _elRef: ElementRef,
              private changeDetection: ChangeDetectorRef) {}

  ngOnInit() {
    const setBsValue = (value: Date) => {
      this._setInputValue(value);
      if (this._value !== value) {
        this._value = value;
        this._onChange(value);
        this._onTouched();
      }
      this.changeDetection.markForCheck();
    };

    // if value set via [bsValue] it will not get into value change
    if (this._picker._bsValue) {
      setBsValue(this._picker._bsValue);
    }

    // update input value on datepicker value update
    this._subs.add(
      this._picker.bsValueChange.subscribe(setBsValue)
    );

    // update input value on locale change
    this._subs.add(
      this._localeService.localeChange.subscribe(() => {
        this._setInputValue(this._value);
      })
    );

    this._subs.add(
    this._picker.dateInputFormat$.pipe(distinctUntilChanged()).subscribe(() => {
      this._setInputValue(this._value);
    })
  );
}

  ngOnDestroy() {
    this._subs.unsubscribe();
  }

  onKeydownEvent(event: KeyboardEvent): void {
    if (event.keyCode === 13 || event.code === 'Enter') {
      this.hide();
    }
  }

  _setInputValue(value?: Date): void {
    const initialDate = !value ? ''
      : formatDate(value, this._picker._config.dateInputFormat, this._localeService.currentLocale);

    this._renderer.setProperty(this._elRef.nativeElement, 'value', initialDate);
  }

  onChange(event: Event) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    this.writeValue((event.target as any).value);
    this._onChange(this._value);
    if (this._picker._config.returnFocusToInput) {
      this._renderer.selectRootElement(this._elRef.nativeElement).focus();
    }
    this._onTouched();
  }

  validate(c: AbstractControl): ValidationErrors | null {
    const _value: Date | string = c.value;

        if (_value === null || _value === undefined || _value === '') {
      return null;
    }

    if (isDate(_value)) {
      const _isDateValid = isDateValid(_value);
      if (!_isDateValid) {
        return { bsDate: { invalid: _value } };
      }

      if (this._picker && this._picker.minDate && isBefore(_value, this._picker.minDate, 'date')) {
        this.writeValue(this._picker.minDate);

        return { bsDate: { minDate: this._picker.minDate } };
      }

      if (this._picker && this._picker.maxDate && isAfter(_value, this._picker.maxDate, 'date')) {
        this.writeValue(this._picker.maxDate);

        return { bsDate: { maxDate: this._picker.maxDate } };
      }
    }

    return null;
  }

  registerOnValidatorChange(fn: () => void): void {
    this._validatorChange = fn;
  }

  writeValue(value: Date | string) {
    if (!value) {
      this._value = void 0;
    } else {
      const _localeKey = this._localeService.currentLocale;
      const _locale = getLocale(_localeKey);
      if (!_locale) {
        throw new Error(
          `Locale "${_localeKey}" is not defined, please add it with "defineLocale(...)"`
        );
      }

      this._value = parseDate(value, this._picker._config.dateInputFormat, this._localeService.currentLocale);

      if (this._picker._config.useUtc) {
        this._value = utcAsLocal(this._value);
      }
    }

    this._picker.bsValue = this._value;
  }

  setDisabledState(isDisabled: boolean): void {
    this._picker.isDisabled = isDisabled;
    if (isDisabled) {
      this._renderer.setAttribute(this._elRef.nativeElement, 'disabled', 'disabled');

      return;
    }
    this._renderer.removeAttribute(this._elRef.nativeElement, 'disabled');
  }

  registerOnChange(fn: () => void): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this._onTouched = fn;
  }

  onBlur() {
    this._onTouched();
  }

  hide() {
    this._picker.hide();
    this._renderer.selectRootElement(this._elRef.nativeElement).blur();
    if (this._picker._config.returnFocusToInput) {
      this._renderer.selectRootElement(this._elRef.nativeElement).focus();
    }
  }
}


text:
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).

package org.rocksdb;

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

public class OptionsUtil {
  /**
   * A static method to construct the DBOptions and ColumnFamilyDescriptors by
   * loading the latest RocksDB options file stored in the specified rocksdb
   * database.
   *
   * Note that the all the pointer options (except table_factory, which will
   * be described in more details below) will be initialized with the default
   * values.  Developers can further initialize them after this function call.
   * Below is an example list of pointer options which will be initialized.
   *
   * - env
   * - memtable_factory
   * - compaction_filter_factory
   * - prefix_extractor
   * - comparator
   * - merge_operator
   * - compaction_filter
   *
   * For table_factory, this function further supports deserializing
   * BlockBasedTableFactory and its BlockBasedTableOptions except the
   * pointer options of BlockBasedTableOptions (flush_block_policy_factory,
   * block_cache, and block_cache_compressed), which will be initialized with
   * default values.  Developers can further specify these three options by
   * casting the return value of TableFactoroy::GetOptions() to
   * BlockBasedTableOptions and making necessary changes.
   *
   * @param dbPath the path to the RocksDB.
   * @param env {@link org.rocksdb.Env} instance.
   * @param dbOptions {@link org.rocksdb.DBOptions} instance. This will be
   *     filled and returned.
   * @param cfDescs A list of {@link org.rocksdb.ColumnFamilyDescriptor}'s be
   *    returned.
   *
   * @throws RocksDBException thrown if error happens in underlying
   *     native library.
   */

  public static void loadLatestOptions(String dbPath, Env env, DBOptions dbOptions,
      List<ColumnFamilyDescriptor> cfDescs) throws RocksDBException {
    loadLatestOptions(dbPath, env, dbOptions, cfDescs, false);
  }

  /**
   * @param dbPath the path to the RocksDB.
   * @param env {@link org.rocksdb.Env} instance.
   * @param dbOptions {@link org.rocksdb.DBOptions} instance. This will be
   *     filled and returned.
   * @param cfDescs A list of {@link org.rocksdb.ColumnFamilyDescriptor}'s be
   *     returned.
   * @param ignoreUnknownOptions this flag can be set to true if you want to
   *     ignore options that are from a newer version of the db, esentially for
   *     forward compatibility.
   *
   * @throws RocksDBException thrown if error happens in underlying
   *     native library.
   */
  public static void loadLatestOptions(String dbPath, Env env, DBOptions dbOptions,
      List<ColumnFamilyDescriptor> cfDescs, boolean ignoreUnknownOptions) throws RocksDBException {
    loadLatestOptions(
        dbPath, env.nativeHandle_, dbOptions.nativeHandle_, cfDescs, ignoreUnknownOptions);
  }

  /**
   * Similar to LoadLatestOptions, this function constructs the DBOptions
   * and ColumnFamilyDescriptors based on the specified RocksDB Options file.
   * See LoadLatestOptions above.
   *
   * @param optionsFileName the RocksDB options file path.
   * @param env {@link org.rocksdb.Env} instance.
   * @param dbOptions {@link org.rocksdb.DBOptions} instance. This will be
   *     filled and returned.
   * @param cfDescs A list of {@link org.rocksdb.ColumnFamilyDescriptor}'s be
   *     returned.
   *
   * @throws RocksDBException thrown if error happens in underlying
   *     native library.
   */
  public static void loadOptionsFromFile(String optionsFileName, Env env, DBOptions dbOptions,
      List<ColumnFamilyDescriptor> cfDescs) throws RocksDBException {
    loadOptionsFromFile(optionsFileName, env, dbOptions, cfDescs, false);
  }

  /**
   * @param optionsFileName the RocksDB options file path.
   * @param env {@link org.rocksdb.Env} instance.
   * @param dbOptions {@link org.rocksdb.DBOptions} instance. This will be
   *     filled and returned.
   * @param cfDescs A list of {@link org.rocksdb.ColumnFamilyDescriptor}'s be
   *     returned.
   * @param ignoreUnknownOptions this flag can be set to true if you want to
   *     ignore options that are from a newer version of the db, esentially for
   *     forward compatibility.
   *
   * @throws RocksDBException thrown if error happens in underlying
   *     native library.
   */
  public static void loadOptionsFromFile(String optionsFileName, Env env, DBOptions dbOptions,
      List<ColumnFamilyDescriptor> cfDescs, boolean ignoreUnknownOptions) throws RocksDBException {
    loadOptionsFromFile(
        optionsFileName, env.nativeHandle_, dbOptions.nativeHandle_, cfDescs, ignoreUnknownOptions);
  }

  /**
   * Returns the latest options file name under the specified RocksDB path.
   *
   * @param dbPath the path to the RocksDB.
   * @param env {@link org.rocksdb.Env} instance.
   * @return the latest options file name under the db path.
   *
   * @throws RocksDBException thrown if error happens in underlying
   *     native library.
   */
  public static String getLatestOptionsFileName(String dbPath, Env env) throws RocksDBException {
    return getLatestOptionsFileName(dbPath, env.nativeHandle_);
  }

  /**
   * Private constructor.
   * This class has only static methods and shouldn't be instantiated.
   */
  private OptionsUtil() {}

  // native methods
  private native static void loadLatestOptions(String dbPath, long envHandle, long dbOptionsHandle,
      List<ColumnFamilyDescriptor> cfDescs, boolean ignoreUnknownOptions) throws RocksDBException;
  private native static void loadOptionsFromFile(String optionsFileName, long envHandle,
      long dbOptionsHandle, List<ColumnFamilyDescriptor> cfDescs, boolean ignoreUnknownOptions)
      throws RocksDBException;
  private native static String getLatestOptionsFileName(String dbPath, long envHandle)
      throws RocksDBException;
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 *
 * @author Chema
 */
public class HibernateUtil {

    private static final SessionFactory SESSIONFACTORY;

    static {
        try {
            // Crear la factoría de sesesiones leyendo la configuración del archivo hibernate.cfg.xml
            Configuration conf = new Configuration().configure();
            ServiceRegistry s = new ServiceRegistryBuilder().applySettings(
                    conf.getProperties()).buildServiceRegistry();
            SESSIONFACTORY = conf.buildSessionFactory(s);
            System.out.println("Factoría de sesiones creada.");
        } catch (Throwable ex) {
            System.err.println("La creación de la factoría de sesiones ha fallado." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return SESSIONFACTORY;
    }
}


text:
require 'google/apis/plus_domains_v1/service.rb'
require 'google/apis/plus_domains_v1/classes.rb'
require 'google/apis/plus_domains_v1/representations.rb'

module Google
  module Apis
    # Google+ Domains API
    #
    # Builds on top of the Google+ platform for Google Apps Domains.
    #
    # @see https://developers.google.com/+/domains/
    module PlusDomainsV1
      VERSION = 'V1'
      REVISION = '20170410'

      # View your circles and the people and pages in them
      AUTH_PLUS_CIRCLES_READ = 'https://www.googleapis.com/auth/plus.circles.read'

      # Manage your circles and add people and pages. People and pages you add to your circles will be notified. Others may see this information publicly. People you add to circles can use Hangouts with you.
      AUTH_PLUS_CIRCLES_WRITE = 'https://www.googleapis.com/auth/plus.circles.write'

      # Know the list of people in your circles, your age range, and language
      AUTH_PLUS_LOGIN = 'https://www.googleapis.com/auth/plus.login'

      # Know who you are on Google
      AUTH_PLUS_ME = 'https://www.googleapis.com/auth/plus.me'

      # Send your photos and videos to Google+
      AUTH_PLUS_MEDIA_UPLOAD = 'https://www.googleapis.com/auth/plus.media.upload'

      # View your own Google+ profile and profiles visible to you
      AUTH_PLUS_PROFILES_READ = 'https://www.googleapis.com/auth/plus.profiles.read'

      # View your Google+ posts, comments, and stream
      AUTH_PLUS_STREAM_READ = 'https://www.googleapis.com/auth/plus.stream.read'

      # Manage your Google+ posts, comments, and stream
      AUTH_PLUS_STREAM_WRITE = 'https://www.googleapis.com/auth/plus.stream.write'

      # View your email address
      AUTH_USERINFO_EMAIL = 'https://www.googleapis.com/auth/userinfo.email'

      # View your basic profile info
      AUTH_USERINFO_PROFILE = 'https://www.googleapis.com/auth/userinfo.profile'
    end
  end
end


text:
/**
 * Survival
 * Cassius - https://github.com/sirDonovan/Cassius
 *
 * This file contains code for the game mode Survival
 *
 * @license MIT license
 */

'use strict';

const Game = require('./../../games').Game; // eslint-disable-line no-unused-vars
const Room = require('./../../rooms').Room; // eslint-disable-line no-unused-vars
const User = require('./../../users').User; // eslint-disable-line no-unused-vars

const name = 'Survival';
const id = Tools.toId(name);

class SurvivalGame extends Games.Game {
	/**
	 * @param {Game} game
	 */
	constructor(game) {
		super(game.room);
		this.name = game.name + ' ' + name;
		this.id = game.id + id;
		this.freeJoin = false;
		this.playerList = [];
		this.survivalRound = 0;
		this.roundTime = 9000;
		this.hint = '';
		/**@type {Array<string>} */
		this.answers = [];
		/**@type {?NodeJS.Timer} */
		this.timeout = null;

		this.override = ['name', 'id', 'freeJoin', 'playerList', 'survivalRound', 'roundTime', 'onSignups', 'onStart', 'onNextRound', 'onEnd', 'guess'];
	}

	onSignups() {}

	onStart() {
		this.nextRound();
	}

	onNextRound() {
		if (!this.playerList.length) {
			if (this.getRemainingPlayerCount() < 2) {
				this.end();
				return;
			}
			this.survivalRound++;
			this.say("/wall Round " + this.survivalRound + (this.survivalRound > 1 ? " | Remaining players: " + this.getPlayerNames(this.getRemainingPlayers()) : ""));
			this.playerList = this.shufflePlayers();
			if (this.roundTime > 1000) this.roundTime -= 500;
		}
		let currentPlayer = this.playerList.shift();
		while (currentPlayer && currentPlayer.eliminated) {
			currentPlayer = this.playerList.shift();
		}
		if (!currentPlayer) {
			this.onNextRound();
			return;
		}
		this.setAnswers();
		this.say("**" + currentPlayer.name + "** you're up!");
		this.currentPlayer = currentPlayer;
		this.timeout = setTimeout(() => {
			this.say(this.hint);
			this.timeout = setTimeout(() => {
				if (this.currentPlayer) {
					this.say("Time's up! The answer" + (this.answers.length > 1 ? 's were' : ' was') + ": __" + this.answers.join(", ") + "__");
					this.currentPlayer.eliminated = true;
					this.currentPlayer = null;
				}
				this.nextRound();
			}, this.roundTime);
		}, 5000);
	}

	onEnd() {
		let len = this.getRemainingPlayerCount();
		if (len) {
			this.say("**Winner" + (len > 1 ? "s" : "") + "**: " + this.getPlayerNames(this.getRemainingPlayers()));
		} else {
			this.say("No winners this game!");
		}
	}

	/**
	 * @param {string} guess
	 * @param {Room} room
	 * @param {User} user
	 */
	guess(guess, room, user) {
		if (!this.currentPlayer || !(user.id in this.players) || this.players[user.id] !== this.currentPlayer) return;
		guess = Tools.toId(guess);
		if (!guess) return;
		if (this.filterGuess && this.filterGuess(guess)) return;
		if (!this.checkAnswer(guess)) {
			if (this.onGuess) this.onGuess(guess, this.players[user.id]);
			return;
		}
		if (this.timeout) clearTimeout(this.timeout);
		this.currentPlayer = null;
		if (this.getRemainingPlayerCount() === 1) return this.end();
		this.say("**" + user.name + "** advances to the next round! (Answer" + (this.answers.length > 1 ? "s" : "") + ": __" + this.answers.join(", ") + "__)");
		this.answers = [];
		this.timeout = setTimeout(() => this.nextRound(), 5000);
	}
}

/**
 * @param {Game} game
 */
let SurvivalMode = function (game) {
	let mode = new SurvivalGame(game);
	for (let i = 0, len = mode.override.length; i < len; i++) {
		// @ts-ignore
		game[mode.override[i]] = mode[mode.override[i]];
	}
};

exports.name = name;
exports.id = id;
exports.naming = 'suffix';
exports.aliases = ['surv'];
exports.requiredProperties = ['setAnswers', 'checkAnswer'];
exports.game = SurvivalGame;
exports.mode = SurvivalMode;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2012 International Business Machines Corp.

  See the NOTICE file distributed with this work for additional information
  regarding copyright ownership. Licensed under the Apache License,
  Version 2.0 (the "License"); you may not use this file except in compliance
  with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<job id="chunksizeDEFAULTcommitIntervalDEFAULT" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
	<step id="step1">
		<chunk>
		 <reader ref="nullChkPtInfoReader"/>
		 <writer ref="nullChkPtInfoWriter"/>
		</chunk>
	</step>
</job>


text:
import Validator from './Validator';
import Message from './utils/Message';
import ValueContext from '../ValueContext';
import utils from './utils/utils';

export interface NumberValidatorConfig {
  errorMessageNotNumber?: string;
  errorMessageOnlyInteger?: string;
  errorMessageGreaterThan?: string;
  errorMessageGreaterThanOrEqualTo?: string;
  errorMessageEqualTo?: string;
  errorMessageLessThan?: string;
  errorMessageLessThanOrEqualTo?: string;
  errorMessageDivisibleBy?: string;
  errorMessageNotOdd?: string;
  errorMessageNotEven?: string;
  strict?: boolean;
  onlyInteger?: boolean;
  odd?: boolean;
  even?: boolean;
  greaterThan?: number;
  greaterThanOrEqualTo?: number;
  equalTo?: number;
  lessThan?: number;
  lessThanOrEqualTo?: number;
  divisibleBy?: number;

}
export default class NumberValidator extends Validator {
  static ERROR_MESSAGE_NOT_NUMBER = '{attribute} - must be a valid number';
  static ERROR_MESSAGE_ONLY_INTEGER = '{attribute} - must be an integer';
  static ERROR_MESSAGE_GREATER_THAN = '{attribute} - must be greater than {count}';
  static ERROR_MESSAGE_GREATER_THAN_OR_EQUAL_TO = '{attribute} - must be greater than or equal to {count}';
  static ERROR_MESSAGE_EQUAL_TO = '{attribute} - must be equal to {count}';
  static ERROR_MESSAGE_LESS_THAN = '{attribute} - must be less than {count}';
  static ERROR_MESSAGE_LESS_THAN_OR_EQUAL_TO = '{attribute} - must be less than or equal to {count}';
  static ERROR_MESSAGE_DIVISIBLE_BY = '{attribute} - must be divisible by {count}';
  static ERROR_MESSAGE_NOT_ODD = '{attribute} - must be odd';
  static ERROR_MESSAGE_NOT_EVEN = '{attribute} - must be even';

  private errorMessageNotNumber?: string;
  private errorMessageOnlyInteger?: string;
  private errorMessageGreaterThan?: string;
  private errorMessageGreaterThanOrEqualTo?: string;
  private errorMessageEqualTo?: string;
  private errorMessageLessThan?: string;
  private errorMessageLessThanOrEqualTo?: string;
  private errorMessageDivisibleBy?: string;
  private errorMessageNotOdd?: string;
  private errorMessageNotEven?: string;
  private strict: boolean;
  private onlyInteger: boolean;
  private odd: boolean;
  private even: boolean;
  private greaterThan?: number;
  private greaterThanOrEqualTo?: number;
  private equalTo?: number;
  private lessThan?: number;
  private lessThanOrEqualTo?: number;
  private divisibleBy?: number;

  constructor(config: NumberValidatorConfig = {}) {
    super();

    this.errorMessageNotNumber = config.errorMessageNotNumber;
    this.errorMessageOnlyInteger = config.errorMessageOnlyInteger;
    this.errorMessageGreaterThan = config.errorMessageGreaterThan;
    this.errorMessageGreaterThanOrEqualTo = config.errorMessageGreaterThanOrEqualTo;
    this.errorMessageEqualTo = config.errorMessageEqualTo;
    this.errorMessageLessThan = config.errorMessageLessThan;
    this.errorMessageLessThanOrEqualTo = config.errorMessageLessThanOrEqualTo;
    this.errorMessageDivisibleBy = config.errorMessageDivisibleBy;
    this.errorMessageNotOdd = config.errorMessageNotOdd;
    this.errorMessageNotEven = config.errorMessageNotEven;
    this.strict = config.strict || false;
    this.onlyInteger = config.onlyInteger || false;
    this.greaterThan = config.greaterThan;
    this.greaterThanOrEqualTo = config.greaterThanOrEqualTo;
    this.equalTo = config.equalTo;
    this.lessThan = config.lessThan;
    this.lessThanOrEqualTo = config.lessThanOrEqualTo;
    this.divisibleBy = config.divisibleBy;
    this.odd = config.odd || false;
    this.even = config.even || false;
  }

  validate(valueContext: ValueContext): Promise<void | string | Message> {
    let { value } = valueContext;
    const { attribute } = valueContext;

    // Empty values are fine
    if (!utils.isDefined(value) || utils.isEmpty(value)) {
      return Promise.resolve();
    }

    // Strict will check that it is a valid looking number
    if (utils.isString(value) && this.strict) {
      let pattern = '^(0|[1-9]\\d*)';
      if (!this.onlyInteger) {
        pattern += '(\\.\\d+)?';
      }
      pattern += '$';

      if (!(new RegExp(pattern).test(value))) {
        return Promise.reject(
          utils.createMessage(this.errorMessageNotNumber || NumberValidator.ERROR_MESSAGE_NOT_NUMBER, {
            attribute,
          }),
        );
      }
    }

    // Coerce the value to a number unless we're being strict.
    // if (options.noStrings !== true && utils.isString(value) && !utils.isEmpty(value)) {
    //     value = +value;
    // }

    value = +value;

    // If it's not a number we shouldn't continue since it will compare it.
    if (!utils.isNumber(value)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageNotNumber || NumberValidator.ERROR_MESSAGE_NOT_NUMBER, {
          attribute,
        }),
      );
    }

    // Same logic as above, sort of. Don't bother with comparisons if this
    // doesn't pass.
    if (this.onlyInteger && !utils.isInteger(value)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageOnlyInteger || NumberValidator.ERROR_MESSAGE_ONLY_INTEGER, {
          attribute,
        }),
      );
    }

    if (this.greaterThan !== undefined && utils.isNumber(this.greaterThan) && !(value > this.greaterThan)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageGreaterThan || NumberValidator.ERROR_MESSAGE_GREATER_THAN, {
          attribute,
          count: this.greaterThan,
        }),
      );
    }

    if (this.greaterThanOrEqualTo !== undefined && utils.isNumber(this.greaterThanOrEqualTo) && !(value >= this.greaterThanOrEqualTo)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageGreaterThanOrEqualTo || NumberValidator.ERROR_MESSAGE_GREATER_THAN_OR_EQUAL_TO, {
          attribute,
          count: this.greaterThanOrEqualTo,
        }),
      );
    }

    if (this.equalTo !== undefined && utils.isNumber(this.equalTo) && !(value === this.equalTo)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageEqualTo || NumberValidator.ERROR_MESSAGE_EQUAL_TO, {
          attribute,
          count: this.equalTo,
        }),
      );
    }

    if ((this.lessThan !== undefined) && utils.isNumber(this.lessThan) && !(value < this.lessThan)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageLessThan || NumberValidator.ERROR_MESSAGE_LESS_THAN, {
          attribute,
          count: this.lessThan,
        }),
      );
    }

    if (this.lessThanOrEqualTo !== undefined && utils.isNumber(this.lessThanOrEqualTo) && !(value <= this.lessThanOrEqualTo)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageLessThanOrEqualTo || NumberValidator.ERROR_MESSAGE_LESS_THAN_OR_EQUAL_TO, {
          attribute,
          count: this.lessThanOrEqualTo,
        }),
      );
    }

    if (this.divisibleBy !== undefined && utils.isNumber(this.divisibleBy) && !(value % this.divisibleBy === 0)) {
      return Promise.reject(
        utils.createMessage(this.errorMessageDivisibleBy || NumberValidator.ERROR_MESSAGE_DIVISIBLE_BY, {
          attribute,
          count: this.divisibleBy,
        }),
      );
    }

    if (this.odd === true && Math.abs(value) % 2 !== 1) {
      return Promise.reject(
        utils.createMessage(this.errorMessageNotOdd || NumberValidator.ERROR_MESSAGE_NOT_ODD, {
          attribute,
        }),
      );
    }

    if (this.even === true && Math.abs(value) % 2 !== 0) {
      return Promise.reject(
        utils.createMessage(this.errorMessageNotEven || NumberValidator.ERROR_MESSAGE_NOT_EVEN, {
          attribute,
        }),
      );
    }

    return Promise.resolve();
  }
}


text:
project_path: /web/tools/_project.yaml
book_path: /web/tools/_book.yaml
description: Reference documentation for the "Properly Size Images" Lighthouse audit.

{# wf_updated_on: 2017-12-11 #}
{# wf_published_on: 2017-04-25 #}
{# wf_blink_components: N/A #}

# Properly Size Images  {: .page-title }

## Overview {: #overview }

Ideally, your page should never serve images that are larger than the
version that's rendered on the user's screen. Anything larger than that
just results in wasted bytes and slows down page load time.

## Recommendations {: #recommendations }

In the results of this audit, Lighthouse lists every image that failed.
Refactor how you serve these images to pass the audit.

The main strategy for serving appropriately-sized images is called
"responsive images". With responsive images, you generate multiple versions
of each image, and then specify which version to use in your HTML or CSS using
media queries, viewport dimensions, and so on. See [Images in markup][iim]
or [Images in CSS][iic] to learn more.

[iim]: /web/fundamentals/design-and-ux/responsive/images#images_in_markup
[iic]: /web/fundamentals/design-and-ux/responsive/images#images_in_css

Another strategy is to use vector-based image formats, like SVG. With a
finite amount of code, an SVG image can scale to any size. See [Replace
complex icons with SVG][svg] to learn more.

[svg]: /web/fundamentals/design-and-ux/responsive/images#replace_complex_icons_with_svg

Yet another strategy is called "client hints". With client hints, the browser
advertises its viewport dimensions and device pixel ratio when requesting
the image, and the server takes care of serving the correctly-sized image.
Note however, that browser support is limited. See [Automating Resource
Selection With Client Hints][ch] to learn more.

[ch]: /web/updates/2015/09/automating-resource-selection-with-client-hints

Tools like [gulp-responsive][gr] or [responsive-images-generator][rig] can
help automate the process of converting an image into multiple formats.
There are also image CDNs which let you generate multiple versions, either
when you upload an image, or request it from your page.

[gr]: https://www.npmjs.com/package/gulp-responsive
[rig]: https://www.npmjs.com/package/responsive-images-generator

## More information {: #more-info }

For each image on the page, Lighthouse compares the size of the rendered image
against the size of the actual image. The rendered size also accounts
for device pixel ratio. If the rendered size is at least 25KB smaller than
the actual size, then the image fails the audit.

## Feedback {: #feedback }

{% framebox width="auto" height="auto" enable_widgets="true" %}

{% include "web/_shared/multichoice.html" %}
{% endframebox %}


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe JettyRails::Handler::DelegateOnErrorsHandler do
  it "should decorate the original HttpServletResponse" do
    original = mock("original handler", :null_object => true)
    original.should_receive(:handle).once do |target, request, response, dispatch|
      response.should be_kind_of(JettyRails::Handler::DelegateOnErrorsResponse)
    end
    delegator = JettyRails::Handler::DelegateOnErrorsHandler.new
    delegator.handler = original
    delegator.handle('/any/target', mock("request"), mock("response"), 0)
  end
end

describe JettyRails::Handler::DelegateOnErrorsResponse do
  it "should delegate all method calls to wrapped response" do
    response = mock('original response')
    response.should_receive(:getContentType).once.and_return('text/html; charset=UTF-8')
    wrapper = JettyRails::Handler::DelegateOnErrorsResponse.new response, mock('request')
    wrapper.getContentType.should == 'text/html; charset=UTF-8'
  end

  it "should set request to not handled state on error" do
    request = mock('request')
    request.should_receive(:handled=).once.with(false)
    wrapper = JettyRails::Handler::DelegateOnErrorsResponse.new mock('response'), request
    wrapper.sendError(403)
  end
end


text:
YUI.add("datepicker-test", function (Y) {

    var suite = new Y.Test.Suite({
        name: "components Generation Suite"
    }),
        testCase = new Y.Test.Case({

            name: "inputex-datepicker field generation test",
            testGeneration: function () {

                Y.log("testGeneration",'debug');

                var instanceField = Y.inputEx({
                    type: "datepicker",
                    parentEl: 'demo',
                    label: 'label'

                });

        Y.Assert.isObject(instanceField);

            }
        });

    suite.add(testCase);
    Y.Test.Runner.add(suite);

}, "", {
    requires: ["test", "inputex-datepicker"]
});


text:
<?php

namespace Components\Newsletter\Models;

use Hubzero\Database\Relational;

require_once __DIR__ . DS . 'mailinglist' . DS . 'email.php';
require_once __DIR__ . DS . 'mailinglist' . DS . 'unsubscribe.php';

/**
 * Newsletter model for a mailinglist
 */
class Mailinglist extends Relational
{
	/**
	 * The table namespace
	 *
	 * @var  string
	 */
	protected $namespace = 'newsletter';

	/**
	 * Default order by for model
	 *
	 * @var  string
	 */
	public $orderBy = 'id';

	/**
	 * Default order direction for select queries
	 *
	 * @var  string
	 */
	public $orderDir = 'asc';

	/**
	 * Fields and their validation criteria
	 *
	 * @var  array
	 */
	protected $rules = array(
		'name' => 'notempty'
	);

	/**
	 * Get a list of emails
	 *
	 * @return  object
	 */
	public function emails()
	{
		return $this->oneToMany(__NAMESPACE__ . '\\Mailinglist\\Email', 'mid');
	}
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<dexprotector>
    <verbose>false</verbose>
    <optimize>false</optimize>
    <signMode>release</signMode>
    <detect>
      <!-- for debugging purposes only -->
      <trace>9</trace>
      <integrity>
        <positiveCheckCallback>com.dexprotector.detector.integrity.MainActivity.positiveTamperCheck</positiveCheckCallback>
        <negativeCheckCallback>com.dexprotector.detector.integrity.MainActivity.negativeTamperCheck</negativeCheckCallback>
        <probeMethod>com.dexprotector.detector.integrity.MainActivity.doProbe</probeMethod>
       </integrity>
    </detect>
    <integrityControl>
        <checkCertificate>off</checkCertificate>
    </integrityControl>
</dexprotector>


text:
namespace Lumix
{

static const uint32_t RENDERABLE_HASH = crc32("renderable");
static const uint32_t ANIMABLE_HASH = crc32("animable");

namespace FS
{
class FileSystem;
};

class Animation;
class Engine;
class JsonSerializer;
class Universe;

class AnimationSceneImpl : public IScene
{
private:
	struct Animable
	{
		bool m_is_free;
		ComponentIndex m_renderable;
		float m_time;
		class Animation* m_animation;
		Entity m_entity;
	};

public:
	AnimationSceneImpl(IPlugin& anim_system,
					   Engine& engine,
					   UniverseContext& ctx,
					   IAllocator& allocator)
		: m_universe(*ctx.m_universe)
		, m_engine(engine)
		, m_anim_system(anim_system)
		, m_animables(allocator)
	{
		m_render_scene = nullptr;
		uint32_t hash = crc32("renderer");
		for (auto* scene : ctx.m_scenes)
		{
			if (crc32(scene->getPlugin().getName()) == hash)
			{
				m_render_scene = static_cast<RenderScene*>(scene);
				break;
			}
		}
		ASSERT(m_render_scene);
		m_render_scene->renderableCreated()
			.bind<AnimationSceneImpl, &AnimationSceneImpl::onRenderableCreated>(
				this);
		m_render_scene->renderableDestroyed()
			.bind<AnimationSceneImpl,
				  &AnimationSceneImpl::onRenderableDestroyed>(this);
	}

	~AnimationSceneImpl()
	{
		m_render_scene->renderableCreated()
			.unbind<AnimationSceneImpl,
					&AnimationSceneImpl::onRenderableCreated>(this);
		m_render_scene->renderableDestroyed()
			.unbind<AnimationSceneImpl,
					&AnimationSceneImpl::onRenderableDestroyed>(this);
	}

	virtual Universe& getUniverse() override { return m_universe; }

	virtual bool ownComponentType(uint32_t type) const override
	{
		return type == ANIMABLE_HASH;
	}

	virtual ComponentIndex createComponent(uint32_t type,
										   Entity entity) override
	{
		if (type == ANIMABLE_HASH)
		{
			return createAnimable(entity);
		}
		return INVALID_COMPONENT;
	}

	virtual void destroyComponent(ComponentIndex component, uint32_t type)
	{
		if (type == ANIMABLE_HASH)
		{
			m_animables[component].m_is_free = true;
			m_universe.destroyComponent(
				m_animables[component].m_entity, type, this, component);
		}
	}

	virtual void serialize(OutputBlob& serializer) override
	{
		serializer.write((int32_t)m_animables.size());
		for (int i = 0; i < m_animables.size(); ++i)
		{
			serializer.write(m_animables[i].m_entity);
			serializer.write(m_animables[i].m_time);
			serializer.write(m_animables[i].m_is_free);
			serializer.writeString(
				m_animables[i].m_animation
					? m_animables[i].m_animation->getPath().c_str()
					: "");
		}
	}

	virtual void deserialize(InputBlob& serializer) override
	{
		int32_t count;
		serializer.read(count);
		m_animables.resize(count);
		for (int i = 0; i < count; ++i)
		{
			serializer.read(m_animables[i].m_entity);
			ComponentIndex renderable =
				m_render_scene->getRenderableComponent(m_animables[i].m_entity);
			if (renderable >= 0)
			{
				m_animables[i].m_renderable = renderable;
			}
			serializer.read(m_animables[i].m_time);
			serializer.read(m_animables[i].m_is_free);
			char path[MAX_PATH_LENGTH];
			serializer.readString(path, sizeof(path));
			m_animables[i].m_animation =
				path[0] == '\0' ? nullptr : loadAnimation(path);
			m_universe.addComponent(
				m_animables[i].m_entity, ANIMABLE_HASH, this, i);
		}
	}

	const char* getPreview(ComponentIndex cmp)
	{
		return m_animables[cmp].m_animation
				   ? m_animables[cmp].m_animation->getPath().c_str()
				   : "";
	}

	void setPreview(ComponentIndex cmp, const char* path)
	{
		playAnimation(cmp, path);
	}

	void playAnimation(ComponentIndex cmp, const char* path)
	{
		m_animables[cmp].m_animation = loadAnimation(path);
		m_animables[cmp].m_time = 0;
	}

	virtual void update(float time_delta) override
	{
		PROFILE_FUNCTION();
		if (m_animables.empty())
			return;
		for (int i = 0, c = m_animables.size(); i < c; ++i)
		{
			Animable& animable = m_animables[i];
			if (!animable.m_is_free && animable.m_animation &&
				animable.m_animation->isReady())
			{
				animable.m_animation->getPose(
					animable.m_time,
					m_render_scene->getPose(animable.m_renderable),
					*m_render_scene->getRenderableModel(animable.m_renderable));
				float t = animable.m_time + time_delta;
				float l = animable.m_animation->getLength();
				while (t > l)
				{
					t -= l;
				}
				animable.m_time = t;
			}
		}
	}

private:
	Animation* loadAnimation(const char* path)
	{
		ResourceManager& rm = m_engine.getResourceManager();
		return static_cast<Animation*>(
			rm.get(ResourceManager::ANIMATION)->load(Path(path)));
	}

	void onRenderableCreated(ComponentIndex cmp)
	{
		Entity entity = m_render_scene->getRenderableEntity(cmp);
		for (int i = 0; i < m_animables.size(); ++i)
		{
			if (m_animables[i].m_entity == entity)
			{
				m_animables[i].m_renderable = cmp;
				break;
			}
		}
	}

	void onRenderableDestroyed(ComponentIndex cmp)
	{
		Entity entity = m_render_scene->getRenderableEntity(cmp);
		for (int i = 0; i < m_animables.size(); ++i)
		{
			if (m_animables[i].m_entity == entity)
			{
				m_animables[i].m_renderable = INVALID_COMPONENT;
				break;
			}
		}
	}

	ComponentIndex createAnimable(Entity entity)
	{
		Animable* src = nullptr;
		for (int i = 0, c = m_animables.size(); i < c; ++i)
		{
			if (m_animables[i].m_is_free)
			{
				src = &m_animables[i];
				break;
			}
		}
		Animable& animable = src ? *src : m_animables.pushEmpty();
		animable.m_time = 0;
		animable.m_is_free = false;
		animable.m_renderable = INVALID_COMPONENT;
		animable.m_animation = nullptr;
		animable.m_entity = entity;

		ComponentIndex renderable =
			m_render_scene->getRenderableComponent(entity);
		if (renderable >= 0)
		{
			animable.m_renderable = renderable;
		}

		m_universe.addComponent(
			entity, ANIMABLE_HASH, this, m_animables.size() - 1);
		return m_animables.size() - 1;
	}

	virtual IPlugin& getPlugin() const override { return m_anim_system; }

private:
	Universe& m_universe;
	IPlugin& m_anim_system;
	Engine& m_engine;
	Array<Animable> m_animables;
	RenderScene* m_render_scene;
};

struct AnimationSystemImpl : public IPlugin
{
public:
	AnimationSystemImpl(Engine& engine)
		: m_allocator(engine.getAllocator())
		, m_engine(engine)
		, m_animation_manager(m_allocator)
	{
		registerPropertyDescriptors();
	}

	virtual IScene* createScene(UniverseContext& ctx) override
	{
		return m_allocator.newObject<AnimationSceneImpl>(
			*this, m_engine, ctx, m_allocator);
	}

	virtual void destroyScene(IScene* scene) override
	{
		m_allocator.deleteObject(scene);
	}

	virtual const char* getName() const override { return "animation"; }

	void registerPropertyDescriptors()
	{
		IAllocator& allocator = m_engine.getAllocator();
		m_engine.registerComponentType("animable", "Animable");
		m_engine.registerProperty(
			"animable",
			allocator.newObject<FilePropertyDescriptor<AnimationSceneImpl>>(
				"preview",
				&AnimationSceneImpl::getPreview,
				&AnimationSceneImpl::setPreview,
				"Animation (*.ani)",
				allocator));
	}

	virtual bool create() override
	{
		m_animation_manager.create(ResourceManager::ANIMATION,
								   m_engine.getResourceManager());
		return true;
	}

	virtual void destroy() override {}

	BaseProxyAllocator m_allocator;
	Engine& m_engine;
	AnimationManager m_animation_manager;

private:
	void operator=(const AnimationSystemImpl&);
	AnimationSystemImpl(const AnimationSystemImpl&);
};

extern "C" IPlugin* createPlugin(Engine& engine)
{
	return engine.getAllocator().newObject<AnimationSystemImpl>(engine);
}

} // ~namespace Lumix