text:
/*
 * Authors:
 *   Keith Whitwell <keith@tungstengraphics.com>
 */

#include <sched.h>
#include <errno.h>

#include "glheader.h"
#include "imports.h"
#include "macros.h"
#include "context.h"
#include "swrast/swrast.h"

#include "r200_context.h"
#include "r200_state.h"
#include "r200_ioctl.h"
#include "r200_tcl.h"
#include "r200_sanity.h"
#include "radeon_reg.h"

#include "drirenderbuffer.h"
#include "vblank.h"

#define R200_TIMEOUT             512
#define R200_IDLE_RETRY           16

static void r200WaitForIdle( r200ContextPtr rmesa );

/* At this point we were in FlushCmdBufLocked but we had lost our context, so
 * we need to unwire our current cmdbuf, hook the one with the saved state in
 * it, flush it, and then put the current one back.  This is so commands at the
 * start of a cmdbuf can rely on the state being kept from the previous one.
 */
static void r200BackUpAndEmitLostStateLocked( r200ContextPtr rmesa )
{
   GLuint nr_released_bufs;
   struct r200_store saved_store;

   if (rmesa->backup_store.cmd_used == 0)
      return;

   if (R200_DEBUG & DEBUG_STATE)
      fprintf(stderr, "Emitting backup state on lost context\n");

   rmesa->lost_context = GL_FALSE;

   nr_released_bufs = rmesa->dma.nr_released_bufs;
   saved_store = rmesa->store;
   rmesa->dma.nr_released_bufs = 0;
   rmesa->store = rmesa->backup_store;
   r200FlushCmdBufLocked( rmesa, __FUNCTION__ );
   rmesa->dma.nr_released_bufs = nr_released_bufs;
   rmesa->store = saved_store;
}

int r200FlushCmdBufLocked( r200ContextPtr rmesa, const char * caller )
{
   int ret, i;
   drm_radeon_cmd_buffer_t cmd;

   if (rmesa->lost_context)
      r200BackUpAndEmitLostStateLocked( rmesa );

   if (R200_DEBUG & DEBUG_IOCTL) {
      fprintf(stderr, "%s from %s\n", __FUNCTION__, caller);

      if (0 & R200_DEBUG & DEBUG_VERBOSE)
	 for (i = 0 ; i < rmesa->store.cmd_used ; i += 4 )
	    fprintf(stderr, "%d: %x\n", i/4,
		    *(int *)(&rmesa->store.cmd_buf[i]));
   }

   if (R200_DEBUG & DEBUG_DMA)
      fprintf(stderr, "%s: Releasing %d buffers\n", __FUNCTION__,
	      rmesa->dma.nr_released_bufs);

   if (R200_DEBUG & DEBUG_SANITY) {
      if (rmesa->state.scissor.enabled)
	 ret = r200SanityCmdBuffer( rmesa,
				    rmesa->state.scissor.numClipRects,
				    rmesa->state.scissor.pClipRects);
      else
	 ret = r200SanityCmdBuffer( rmesa,
				    rmesa->numClipRects,
				    rmesa->pClipRects);
      if (ret) {
	 fprintf(stderr, "drmSanityCommandWrite: %d\n", ret);
	 goto out;
      }
   }

   if (R200_DEBUG & DEBUG_MEMORY) {
      if (! driValidateTextureHeaps( rmesa->texture_heaps, rmesa->nr_heaps,
				     & rmesa->swapped ) ) {
	 fprintf( stderr, "%s: texture memory is inconsistent - expect "
		  "mangled textures\n", __FUNCTION__ );
      }
   }

   cmd.bufsz = rmesa->store.cmd_used;
   cmd.buf = rmesa->store.cmd_buf;

   if (rmesa->state.scissor.enabled) {
      cmd.nbox = rmesa->state.scissor.numClipRects;
      cmd.boxes = (drm_clip_rect_t *)rmesa->state.scissor.pClipRects;
   } else {
      cmd.nbox = rmesa->numClipRects;
      cmd.boxes = (drm_clip_rect_t *)rmesa->pClipRects;
   }

   ret = drmCommandWrite( rmesa->dri.fd,
			  DRM_RADEON_CMDBUF,
			  &cmd, sizeof(cmd) );

   if (ret)
      fprintf(stderr, "drmCommandWrite: %d\n", ret);

   if (R200_DEBUG & DEBUG_SYNC) {
      fprintf(stderr, "\nSyncing in %s\n\n", __FUNCTION__);
      r200WaitForIdleLocked( rmesa );
   }

 out:
   rmesa->store.primnr = 0;
   rmesa->store.statenr = 0;
   rmesa->store.cmd_used = 0;
   rmesa->dma.nr_released_bufs = 0;
   rmesa->save_on_next_emit = 1;

   return ret;
}

/* Note: does not emit any commands to avoid recursion on
 * r200AllocCmdBuf.
 */
void r200FlushCmdBuf( r200ContextPtr rmesa, const char *caller )
{
   int ret;

   LOCK_HARDWARE( rmesa );

   ret = r200FlushCmdBufLocked( rmesa, caller );

   UNLOCK_HARDWARE( rmesa );

   if (ret) {
      fprintf(stderr, "drmRadeonCmdBuffer: %d (exiting)\n", ret);
      exit(ret);
   }
}

/* =============================================================
 * Hardware vertex buffer handling
 */

void r200RefillCurrentDmaRegion( r200ContextPtr rmesa )
{
   struct r200_dma_buffer *dmabuf;
   int fd = rmesa->dri.fd;
   int index = 0;
   int size = 0;
   drmDMAReq dma;
   int ret;

   if (R200_DEBUG & (DEBUG_IOCTL|DEBUG_DMA))
      fprintf(stderr, "%s\n", __FUNCTION__);

   if (rmesa->dma.flush) {
      rmesa->dma.flush( rmesa );
   }

   if (rmesa->dma.current.buf)
      r200ReleaseDmaRegion( rmesa, &rmesa->dma.current, __FUNCTION__ );

   if (rmesa->dma.nr_released_bufs > 4)
      r200FlushCmdBuf( rmesa, __FUNCTION__ );

   dma.context = rmesa->dri.hwContext;
   dma.send_count = 0;
   dma.send_list = NULL;
   dma.send_sizes = NULL;
   dma.flags = 0;
   dma.request_count = 1;
   dma.request_size = RADEON_BUFFER_SIZE;
   dma.request_list = &index;
   dma.request_sizes = &size;
   dma.granted_count = 0;

   LOCK_HARDWARE(rmesa);	/* no need to validate */

   while (1) {
      ret = drmDMA( fd, &dma );
      if (ret == 0)
	 break;

      if (rmesa->dma.nr_released_bufs) {
	 r200FlushCmdBufLocked( rmesa, __FUNCTION__ );
      }

      if (rmesa->do_usleeps) {
	 UNLOCK_HARDWARE( rmesa );
	 DO_USLEEP( 1 );
	 LOCK_HARDWARE( rmesa );
      }
   }

   UNLOCK_HARDWARE(rmesa);

   if (R200_DEBUG & DEBUG_DMA)
      fprintf(stderr, "Allocated buffer %d\n", index);

   dmabuf = CALLOC_STRUCT( r200_dma_buffer );
   dmabuf->buf = &rmesa->r200Screen->buffers->list[index];
   dmabuf->refcount = 1;

   rmesa->dma.current.buf = dmabuf;
   rmesa->dma.current.address = dmabuf->buf->address;
   rmesa->dma.current.end = dmabuf->buf->total;
   rmesa->dma.current.start = 0;
   rmesa->dma.current.ptr = 0;
}

void r200ReleaseDmaRegion( r200ContextPtr rmesa,
			     struct r200_dma_region *region,
			     const char *caller )
{
   if (R200_DEBUG & DEBUG_IOCTL)
      fprintf(stderr, "%s from %s\n", __FUNCTION__, caller);

   if (!region->buf)
      return;

   if (rmesa->dma.flush)
      rmesa->dma.flush( rmesa );

   if (--region->buf->refcount == 0) {
      drm_radeon_cmd_header_t *cmd;

      if (R200_DEBUG & (DEBUG_IOCTL|DEBUG_DMA))
	 fprintf(stderr, "%s -- DISCARD BUF %d\n", __FUNCTION__,
		 region->buf->buf->idx);

      cmd = (drm_radeon_cmd_header_t *)r200AllocCmdBuf( rmesa, sizeof(*cmd),
						     __FUNCTION__ );
      cmd->dma.cmd_type = RADEON_CMD_DMA_DISCARD;
      cmd->dma.buf_idx = region->buf->buf->idx;
      FREE(region->buf);
      rmesa->dma.nr_released_bufs++;
   }

   region->buf = NULL;
   region->start = 0;
}

/* Allocates a region from rmesa->dma.current.  If there isn't enough
 * space in current, grab a new buffer (and discard what was left of current)
 */
void r200AllocDmaRegion( r200ContextPtr rmesa,
			   struct r200_dma_region *region,
			   int bytes,
			   int alignment )
{
   if (R200_DEBUG & DEBUG_IOCTL)
      fprintf(stderr, "%s %d\n", __FUNCTION__, bytes);

   if (rmesa->dma.flush)
      rmesa->dma.flush( rmesa );

   if (region->buf)
      r200ReleaseDmaRegion( rmesa, region, __FUNCTION__ );

   alignment--;
   rmesa->dma.current.start = rmesa->dma.current.ptr =
      (rmesa->dma.current.ptr + alignment) & ~alignment;

   if ( rmesa->dma.current.ptr + bytes > rmesa->dma.current.end )
      r200RefillCurrentDmaRegion( rmesa );

   region->start = rmesa->dma.current.start;
   region->ptr = rmesa->dma.current.start;
   region->end = rmesa->dma.current.start + bytes;
   region->address = rmesa->dma.current.address;
   region->buf = rmesa->dma.current.buf;
   region->buf->refcount++;

   rmesa->dma.current.ptr += bytes; /* bug - if alignment > 7 */
   rmesa->dma.current.start =
      rmesa->dma.current.ptr = (rmesa->dma.current.ptr + 0x7) & ~0x7;

   assert( rmesa->dma.current.ptr <= rmesa->dma.current.end );
}

/* ================================================================
 * SwapBuffers with client-side throttling
 */

static u_int32_t r200GetLastFrame(r200ContextPtr rmesa)
{
   drm_radeon_getparam_t gp;
   int ret;
   u_int32_t frame;

   gp.param = RADEON_PARAM_LAST_FRAME;
   gp.value = (int *)&frame;
   ret = drmCommandWriteRead( rmesa->dri.fd, DRM_RADEON_GETPARAM,
			      &gp, sizeof(gp) );
   if ( ret ) {
      fprintf( stderr, "%s: drmRadeonGetParam: %d\n", __FUNCTION__, ret );
      exit(1);
   }

   return frame;
}

static void r200EmitIrqLocked( r200ContextPtr rmesa )
{
   drm_radeon_irq_emit_t ie;
   int ret;

   ie.irq_seq = &rmesa->iw.irq_seq;
   ret = drmCommandWriteRead( rmesa->dri.fd, DRM_RADEON_IRQ_EMIT,
			      &ie, sizeof(ie) );
   if ( ret ) {
      fprintf( stderr, "%s: drmRadeonIrqEmit: %d\n", __FUNCTION__, ret );
      exit(1);
   }
}

static void r200WaitIrq( r200ContextPtr rmesa )
{
   int ret;

   do {
      ret = drmCommandWrite( rmesa->dri.fd, DRM_RADEON_IRQ_WAIT,
			     &rmesa->iw, sizeof(rmesa->iw) );
   } while (ret && (errno == EINTR || errno == EBUSY));

   if ( ret ) {
      fprintf( stderr, "%s: drmRadeonIrqWait: %d\n", __FUNCTION__, ret );
      exit(1);
   }
}

static void r200WaitForFrameCompletion( r200ContextPtr rmesa )
{
   drm_radeon_sarea_t *sarea = rmesa->sarea;

   if (rmesa->do_irqs) {
      if (r200GetLastFrame(rmesa) < sarea->last_frame) {
	 if (!rmesa->irqsEmitted) {
	    while (r200GetLastFrame (rmesa) < sarea->last_frame)
	       ;
	 }
	 else {
	    UNLOCK_HARDWARE( rmesa );
	    r200WaitIrq( rmesa );
	    LOCK_HARDWARE( rmesa );
	 }
	 rmesa->irqsEmitted = 10;
      }

      if (rmesa->irqsEmitted) {
	 r200EmitIrqLocked( rmesa );
	 rmesa->irqsEmitted--;
      }
   }
   else {
      while (r200GetLastFrame (rmesa) < sarea->last_frame) {
	 UNLOCK_HARDWARE( rmesa );
	 if (rmesa->do_usleeps)
	    DO_USLEEP( 1 );
	 LOCK_HARDWARE( rmesa );
      }
   }
}

/* Copy the back color buffer to the front color buffer.
 */
void r200CopyBuffer( __DRIdrawablePrivate *dPriv,
		      const drm_clip_rect_t	 *rect)
{
   r200ContextPtr rmesa;
   GLint nbox, i, ret;
   GLboolean   missed_target;
   int64_t ust;
   __DRIscreenPrivate *psp = dPriv->driScreenPriv;

   assert(dPriv);
   assert(dPriv->driContextPriv);
   assert(dPriv->driContextPriv->driverPrivate);

   rmesa = (r200ContextPtr) dPriv->driContextPriv->driverPrivate;

   if ( R200_DEBUG & DEBUG_IOCTL ) {
      fprintf( stderr, "\n%s( %p )\n\n", __FUNCTION__, (void *)rmesa->glCtx );
   }

   R200_FIREVERTICES( rmesa );

   LOCK_HARDWARE( rmesa );

   /* Throttle the frame rate -- only allow one pending swap buffers
    * request at a time.
    */
   r200WaitForFrameCompletion( rmesa );
   if (!rect)
   {
       UNLOCK_HARDWARE( rmesa );
       driWaitForVBlank( dPriv, & missed_target );
       LOCK_HARDWARE( rmesa );
   }

   nbox = dPriv->numClipRects; /* must be in locked region */

   for ( i = 0 ; i < nbox ; ) {
      GLint nr = MIN2( i + RADEON_NR_SAREA_CLIPRECTS , nbox );
      drm_clip_rect_t *box = dPriv->pClipRects;
      drm_clip_rect_t *b = rmesa->sarea->boxes;
      GLint n = 0;

      for ( ; i < nr ; i++ ) {

	  *b = box[i];

	  if (rect)
	  {
	     if (rect->x1 > b->x1)
		 b->x1 = rect->x1;
	     if (rect->y1 > b->y1)
		 b->y1 = rect->y1;
	     if (rect->x2 < b->x2)
		 b->x2 = rect->x2;
	     if (rect->y2 < b->y2)
		 b->y2 = rect->y2;

	     if (b->x1 >= b->x2 || b->y1 >= b->y2)
		 continue;
	  }

	  b++;
	  n++;
      }
      rmesa->sarea->nbox = n;

      if (!n)
	 continue;

      ret = drmCommandNone( rmesa->dri.fd, DRM_RADEON_SWAP );

      if ( ret ) {
	 fprintf( stderr, "DRM_R200_SWAP_BUFFERS: return = %d\n", ret );
	 UNLOCK_HARDWARE( rmesa );
	 exit( 1 );
      }
   }

   UNLOCK_HARDWARE( rmesa );
   if (!rect)
   {
       rmesa->hw.all_dirty = GL_TRUE;

       rmesa->swap_count++;
       (*psp->systemTime->getUST)( & ust );
       if ( missed_target ) {
	   rmesa->swap_missed_count++;
	   rmesa->swap_missed_ust = ust - rmesa->swap_ust;
       }

       rmesa->swap_ust = ust;

       sched_yield();
   }
}

void r200PageFlip( __DRIdrawablePrivate *dPriv )
{
   r200ContextPtr rmesa;
   GLint ret;
   GLboolean   missed_target;
   __DRIscreenPrivate *psp = dPriv->driScreenPriv;

   assert(dPriv);
   assert(dPriv->driContextPriv);
   assert(dPriv->driContextPriv->driverPrivate);

   rmesa = (r200ContextPtr) dPriv->driContextPriv->driverPrivate;

   if ( R200_DEBUG & DEBUG_IOCTL ) {
      fprintf(stderr, "%s: pfCurrentPage: %d\n", __FUNCTION__,
	      rmesa->sarea->pfCurrentPage);
   }

   R200_FIREVERTICES( rmesa );
   LOCK_HARDWARE( rmesa );

   if (!dPriv->numClipRects) {
      UNLOCK_HARDWARE( rmesa );
      usleep( 10000 );		/* throttle invisible client 10ms */
      return;
   }

   /* Need to do this for the perf box placement:
    */
   {
      drm_clip_rect_t *box = dPriv->pClipRects;
      drm_clip_rect_t *b = rmesa->sarea->boxes;
      b[0] = box[0];
      rmesa->sarea->nbox = 1;
   }

   /* Throttle the frame rate -- only allow a few pending swap buffers
    * request at a time.
    */
   r200WaitForFrameCompletion( rmesa );
   UNLOCK_HARDWARE( rmesa );
   driWaitForVBlank( dPriv, & missed_target );
   if ( missed_target ) {
      rmesa->swap_missed_count++;
      (void) (*psp->systemTime->getUST)( & rmesa->swap_missed_ust );
   }
   LOCK_HARDWARE( rmesa );

   ret = drmCommandNone( rmesa->dri.fd, DRM_RADEON_FLIP );

   UNLOCK_HARDWARE( rmesa );

   if ( ret ) {
      fprintf( stderr, "DRM_RADEON_FLIP: return = %d\n", ret );
      exit( 1 );
   }

   rmesa->swap_count++;
   (void) (*psp->systemTime->getUST)( & rmesa->swap_ust );

#if 000
   if ( rmesa->sarea->pfCurrentPage == 1 ) {
	 rmesa->state.color.drawOffset = rmesa->r200Screen->frontOffset;
	 rmesa->state.color.drawPitch  = rmesa->r200Screen->frontPitch;
   } else {
	 rmesa->state.color.drawOffset = rmesa->r200Screen->backOffset;
	 rmesa->state.color.drawPitch  = rmesa->r200Screen->backPitch;
   }

   R200_STATECHANGE( rmesa, ctx );
   rmesa->hw.ctx.cmd[CTX_RB3D_COLOROFFSET] = rmesa->state.color.drawOffset
					   + rmesa->r200Screen->fbLocation;
   rmesa->hw.ctx.cmd[CTX_RB3D_COLORPITCH]  = rmesa->state.color.drawPitch;
   if (rmesa->sarea->tiling_enabled) {
      rmesa->hw.ctx.cmd[CTX_RB3D_COLORPITCH] |= R200_COLOR_TILE_ENABLE;
   }
#else
   /* Get ready for drawing next frame.  Update the renderbuffers'
    * flippedOffset/Pitch fields so we draw into the right place.
    */
   driFlipRenderbuffers(rmesa->glCtx->WinSysDrawBuffer,
                        rmesa->sarea->pfCurrentPage);

   r200UpdateDrawBuffer(rmesa->glCtx);
#endif
}

/* ================================================================
 * Buffer clear
 */
static void r200Clear( GLcontext *ctx, GLbitfield mask )
{
   r200ContextPtr rmesa = R200_CONTEXT(ctx);
   __DRIdrawablePrivate *dPriv = rmesa->dri.drawable;
   GLuint flags = 0;
   GLuint color_mask = 0;
   GLint ret, i;
   GLint cx, cy, cw, ch;

   if ( R200_DEBUG & DEBUG_IOCTL ) {
      fprintf( stderr, "r200Clear\n");
   }

   {
      LOCK_HARDWARE( rmesa );
      UNLOCK_HARDWARE( rmesa );
      if ( dPriv->numClipRects == 0 )
	 return;
   }

   r200Flush( ctx );

   if ( mask & BUFFER_BIT_FRONT_LEFT ) {
      flags |= RADEON_FRONT;
      color_mask = rmesa->hw.msk.cmd[MSK_RB3D_PLANEMASK];
      mask &= ~BUFFER_BIT_FRONT_LEFT;
   }

   if ( mask & BUFFER_BIT_BACK_LEFT ) {
      flags |= RADEON_BACK;
      color_mask = rmesa->hw.msk.cmd[MSK_RB3D_PLANEMASK];
      mask &= ~BUFFER_BIT_BACK_LEFT;
   }

   if ( mask & BUFFER_BIT_DEPTH ) {
      flags |= RADEON_DEPTH;
      mask &= ~BUFFER_BIT_DEPTH;
   }

   if ( (mask & BUFFER_BIT_STENCIL) && rmesa->state.stencil.hwBuffer ) {
      flags |= RADEON_STENCIL;
      mask &= ~BUFFER_BIT_STENCIL;
   }

   if ( mask ) {
      if (R200_DEBUG & DEBUG_FALLBACKS)
	 fprintf(stderr, "%s: swrast clear, mask: %x\n", __FUNCTION__, mask);
      _swrast_Clear( ctx, mask );
   }

   if ( !flags )
      return;

   if (rmesa->using_hyperz) {
      flags |= RADEON_USE_COMP_ZBUF;
/*      if (rmesa->r200Screen->chip_family == CHIP_FAMILY_R200)
	 flags |= RADEON_USE_HIERZ; */
      if (!(rmesa->state.stencil.hwBuffer) ||
	 ((flags & RADEON_DEPTH) && (flags & RADEON_STENCIL) &&
	    ((rmesa->state.stencil.clear & R200_STENCIL_WRITE_MASK) == R200_STENCIL_WRITE_MASK))) {
	  flags |= RADEON_CLEAR_FASTZ;
      }
   }

   LOCK_HARDWARE( rmesa );

   /* compute region after locking: */
   cx = ctx->DrawBuffer->_Xmin;
   cy = ctx->DrawBuffer->_Ymin;
   cw = ctx->DrawBuffer->_Xmax - cx;
   ch = ctx->DrawBuffer->_Ymax - cy;

   /* Flip top to bottom */
   cx += dPriv->x;
   cy  = dPriv->y + dPriv->h - cy - ch;

   /* Throttle the number of clear ioctls we do.
    */
   while ( 1 ) {
      drm_radeon_getparam_t gp;
      int ret;
      int clear;

      gp.param = RADEON_PARAM_LAST_CLEAR;
      gp.value = (int *)&clear;
      ret = drmCommandWriteRead( rmesa->dri.fd,
		      DRM_RADEON_GETPARAM, &gp, sizeof(gp) );

      if ( ret ) {
	 fprintf( stderr, "%s: drmRadeonGetParam: %d\n", __FUNCTION__, ret );
	 exit(1);
      }

      /* Clear throttling needs more thought.
       */
      if ( rmesa->sarea->last_clear - clear <= 25 ) {
	 break;
      }

      if (rmesa->do_usleeps) {
	 UNLOCK_HARDWARE( rmesa );
	 DO_USLEEP( 1 );
	 LOCK_HARDWARE( rmesa );
      }
   }

   /* Send current state to the hardware */
   r200FlushCmdBufLocked( rmesa, __FUNCTION__ );

   for ( i = 0 ; i < dPriv->numClipRects ; ) {
      GLint nr = MIN2( i + RADEON_NR_SAREA_CLIPRECTS, dPriv->numClipRects );
      drm_clip_rect_t *box = dPriv->pClipRects;
      drm_clip_rect_t *b = rmesa->sarea->boxes;
      drm_radeon_clear_t clear;
      drm_radeon_clear_rect_t depth_boxes[RADEON_NR_SAREA_CLIPRECTS];
      GLint n = 0;

      if (cw != dPriv->w || ch != dPriv->h) {
         /* clear subregion */
	 for ( ; i < nr ; i++ ) {
	    GLint x = box[i].x1;
	    GLint y = box[i].y1;
	    GLint w = box[i].x2 - x;
	    GLint h = box[i].y2 - y;

	    if ( x < cx ) w -= cx - x, x = cx;
	    if ( y < cy ) h -= cy - y, y = cy;
	    if ( x + w > cx + cw ) w = cx + cw - x;
	    if ( y + h > cy + ch ) h = cy + ch - y;
	    if ( w <= 0 ) continue;
	    if ( h <= 0 ) continue;

	    b->x1 = x;
	    b->y1 = y;
	    b->x2 = x + w;
	    b->y2 = y + h;
	    b++;
	    n++;
	 }
      } else {
         /* clear whole window */
	 for ( ; i < nr ; i++ ) {
	    *b++ = box[i];
	    n++;
	 }
      }

      rmesa->sarea->nbox = n;

      clear.flags       = flags;
      clear.clear_color = rmesa->state.color.clear;
      clear.clear_depth = rmesa->state.depth.clear;	/* needed for hyperz */
      clear.color_mask  = rmesa->hw.msk.cmd[MSK_RB3D_PLANEMASK];
      clear.depth_mask  = rmesa->state.stencil.clear;
      clear.depth_boxes = depth_boxes;

      n--;
      b = rmesa->sarea->boxes;
      for ( ; n >= 0 ; n-- ) {
	 depth_boxes[n].f[CLEAR_X1] = (float)b[n].x1;
	 depth_boxes[n].f[CLEAR_Y1] = (float)b[n].y1;
	 depth_boxes[n].f[CLEAR_X2] = (float)b[n].x2;
	 depth_boxes[n].f[CLEAR_Y2] = (float)b[n].y2;
	 depth_boxes[n].f[CLEAR_DEPTH] = ctx->Depth.Clear;
      }

      ret = drmCommandWrite( rmesa->dri.fd, DRM_RADEON_CLEAR,
			     &clear, sizeof(clear));

      if ( ret ) {
	 UNLOCK_HARDWARE( rmesa );
	 fprintf( stderr, "DRM_RADEON_CLEAR: return = %d\n", ret );
	 exit( 1 );
      }
   }

   UNLOCK_HARDWARE( rmesa );
   rmesa->hw.all_dirty = GL_TRUE;
}

void r200WaitForIdleLocked( r200ContextPtr rmesa )
{
    int ret;
    int i = 0;

    do {
       ret = drmCommandNone( rmesa->dri.fd, DRM_RADEON_CP_IDLE);
       if (ret)
	  DO_USLEEP( 1 );
    } while (ret && ++i < 100);

    if ( ret < 0 ) {
       UNLOCK_HARDWARE( rmesa );
       fprintf( stderr, "Error: R200 timed out... exiting\n" );
       exit( -1 );
    }
}

static void r200WaitForIdle( r200ContextPtr rmesa )
{
   LOCK_HARDWARE(rmesa);
   r200WaitForIdleLocked( rmesa );
   UNLOCK_HARDWARE(rmesa);
}

void r200Flush( GLcontext *ctx )
{
   r200ContextPtr rmesa = R200_CONTEXT( ctx );

   if (R200_DEBUG & DEBUG_IOCTL)
      fprintf(stderr, "%s\n", __FUNCTION__);

   if (rmesa->dma.flush)
      rmesa->dma.flush( rmesa );

   r200EmitState( rmesa );

   if (rmesa->store.cmd_used)
      r200FlushCmdBuf( rmesa, __FUNCTION__ );
}

/* Make sure all commands have been sent to the hardware and have
 * completed processing.
 */
void r200Finish( GLcontext *ctx )
{
   r200ContextPtr rmesa = R200_CONTEXT(ctx);
   r200Flush( ctx );

   if (rmesa->do_irqs) {
      LOCK_HARDWARE( rmesa );
      r200EmitIrqLocked( rmesa );
      UNLOCK_HARDWARE( rmesa );
      r200WaitIrq( rmesa );
   }
   else
      r200WaitForIdle( rmesa );
}

/* This version of AllocateMemoryMESA allocates only GART memory, and
 * only does so after the point at which the driver has been
 * initialized.
 *
 * Theoretically a valid context isn't required.  However, in this
 * implementation, it is, as I'm using the hardware lock to protect
 * the kernel data structures, and the current context to get the
 * device fd.
 */
void *r200AllocateMemoryMESA(__DRIscreen *screen, GLsizei size,
			     GLfloat readfreq, GLfloat writefreq,
			     GLfloat priority)
{
   GET_CURRENT_CONTEXT(ctx);
   r200ContextPtr rmesa;
   int region_offset;
   drm_radeon_mem_alloc_t alloc;
   int ret;

   if (R200_DEBUG & DEBUG_IOCTL)
      fprintf(stderr, "%s sz %d %f/%f/%f\n", __FUNCTION__, size, readfreq,
	      writefreq, priority);

   if (!ctx || !(rmesa = R200_CONTEXT(ctx)) || !rmesa->r200Screen->gartTextures.map)
      return NULL;

   if (getenv("R200_NO_ALLOC"))
      return NULL;

   alloc.region = RADEON_MEM_REGION_GART;
   alloc.alignment = 0;
   alloc.size = size;
   alloc.region_offset = &region_offset;

   ret = drmCommandWriteRead( rmesa->r200Screen->driScreen->fd,
			      DRM_RADEON_ALLOC,
			      &alloc, sizeof(alloc));

   if (ret) {
      fprintf(stderr, "%s: DRM_RADEON_ALLOC ret %d\n", __FUNCTION__, ret);
      return NULL;
   }

   {
      char *region_start = (char *)rmesa->r200Screen->gartTextures.map;
      return (void *)(region_start + region_offset);
   }
}

/* Called via glXFreeMemoryMESA() */
void r200FreeMemoryMESA(__DRIscreen *screen, GLvoid *pointer)
{
   GET_CURRENT_CONTEXT(ctx);
   r200ContextPtr rmesa;
   ptrdiff_t region_offset;
   drm_radeon_mem_free_t memfree;
   int ret;

   if (R200_DEBUG & DEBUG_IOCTL)
      fprintf(stderr, "%s %p\n", __FUNCTION__, pointer);

   if (!ctx || !(rmesa = R200_CONTEXT(ctx)) || !rmesa->r200Screen->gartTextures.map) {
      fprintf(stderr, "%s: no context\n", __FUNCTION__);
      return;
   }

   region_offset = (char *)pointer - (char *)rmesa->r200Screen->gartTextures.map;

   if (region_offset < 0 ||
       region_offset > rmesa->r200Screen->gartTextures.size) {
      fprintf(stderr, "offset %d outside range 0..%d\n", region_offset,
	      rmesa->r200Screen->gartTextures.size);
      return;
   }

   memfree.region = RADEON_MEM_REGION_GART;
   memfree.region_offset = region_offset;

   ret = drmCommandWrite( rmesa->r200Screen->driScreen->fd,
			  DRM_RADEON_FREE,
			  &memfree, sizeof(memfree));

   if (ret)
      fprintf(stderr, "%s: DRM_RADEON_FREE ret %d\n", __FUNCTION__, ret);
}

/* Called via glXGetMemoryOffsetMESA() */
GLuint r200GetMemoryOffsetMESA(__DRIscreen *screen, const GLvoid *pointer)
{
   GET_CURRENT_CONTEXT(ctx);
   r200ContextPtr rmesa;
   GLuint card_offset;

   if (!ctx || !(rmesa = R200_CONTEXT(ctx)) ) {
      fprintf(stderr, "%s: no context\n", __FUNCTION__);
      return ~0;
   }

   if (!r200IsGartMemory( rmesa, pointer, 0 ))
      return ~0;

   card_offset = r200GartOffsetFromVirtual( rmesa, pointer );

   return card_offset - rmesa->r200Screen->gart_base;
}

GLboolean r200IsGartMemory( r200ContextPtr rmesa, const GLvoid *pointer,
			   GLint size )
{
   ptrdiff_t offset = (char *)pointer - (char *)rmesa->r200Screen->gartTextures.map;
   int valid = (size >= 0 &&
		offset >= 0 &&
		offset + size < rmesa->r200Screen->gartTextures.size);

   if (R200_DEBUG & DEBUG_IOCTL)
      fprintf(stderr, "r200IsGartMemory( %p ) : %d\n", pointer, valid );

   return valid;
}

GLuint r200GartOffsetFromVirtual( r200ContextPtr rmesa, const GLvoid *pointer )
{
   ptrdiff_t offset = (char *)pointer - (char *)rmesa->r200Screen->gartTextures.map;

   if (offset < 0 || offset > rmesa->r200Screen->gartTextures.size)
      return ~0;
   else
      return rmesa->r200Screen->gart_texture_offset + offset;
}

void r200InitIoctlFuncs( struct dd_function_table *functions )
{
    functions->Clear = r200Clear;
    functions->Finish = r200Finish;
    functions->Flush = r200Flush;
}

redpajama_set_name: RedPajamaGithub


text:
using OpenQA.Selenium;
using System.Collections.Generic;
using System.Linq;

namespace Fenton.Selenium.SuperDriver
{
    public class SuperCookie : Cookie
    {
        public readonly ParallelQuery<Cookie> _query;

        public SuperCookie(IEnumerable<Cookie> cookies)
            : base(
                cookies.Select(c => c.Name).AssertAllMatch().First(),
                cookies.Select(c => c.Value).AssertAllMatch().First(),
                cookies.Select(c => c.Domain).AssertLooseStringMatch().FirstOrDefault(),
                cookies.Select(c => c.Path).AssertLooseStringMatch().FirstOrDefault(),
                cookies.Select(c => c.Expiry).AssertLooseDateMatch().FirstOrDefault())
        {
            _query = cookies.ToConcurrentQuery();
        }

        public override bool Secure
        {
            get
            {
                return _query.Select(c => c.Secure).AssertAllMatch().FirstOrDefault();
            }
        }

        public IList<Cookie> GetSuperCookieContents()
        {
            return _query.ToList();
        }
    }
}


text:
#include "OgreStableHeaders.h"

#include <sys/stat.h>

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE || \
    OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || \
    OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || \
    OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
#   include "OgreSearchOps.h"
#   include <sys/param.h>
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#  define WIN32_LEAN_AND_MEAN
#  if !defined(NOMINMAX) && defined(_MSC_VER)
#   define NOMINMAX // required to stop windows.h messing up std::min
#  endif
#  include <windows.h>
#  include <direct.h>
#  include <io.h>
//#  define _OGRE_FILESYSTEM_ARCHIVE_UNICODE // base path and resources subpathes expected to be in UTF-8 and wchar_t file IO routines are used
#endif

namespace Ogre {

namespace {
    /** Specialisation of the Archive class to allow reading of files from
        filesystem folders / directories.
    */
    class FileSystemArchive : public Archive
    {
    protected:
        /** Utility method to retrieve all files in a directory matching pattern.
        @param pattern
            File pattern.
        @param recursive
            Whether to cascade down directories.
        @param dirs
            Set to @c true if you want the directories to be listed instead of files.
        @param simpleList
            Populated if retrieving a simple list.
        @param detailList
            Populated if retrieving a detailed list.
        */
        void findFiles(const String& pattern, bool recursive, bool dirs,
            StringVector* simpleList, FileInfoList* detailList) const;

        OGRE_AUTO_MUTEX;
    public:
        FileSystemArchive(const String& name, const String& archType, bool readOnly );
        ~FileSystemArchive();

        /// @copydoc Archive::isCaseSensitive
        bool isCaseSensitive(void) const override;

        /// @copydoc Archive::load
        void load() override;
        /// @copydoc Archive::unload
        void unload() override;

        /// @copydoc Archive::open
        DataStreamPtr open(const String& filename, bool readOnly = true) const override;

        /// @copydoc Archive::create
        DataStreamPtr create(const String& filename) override;

        /// @copydoc Archive::remove
        void remove(const String& filename) override;

        /// @copydoc Archive::list
        StringVectorPtr list(bool recursive = true, bool dirs = false) const override;

        /// @copydoc Archive::listFileInfo
        FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const override;

        /// @copydoc Archive::find
        StringVectorPtr find(const String& pattern, bool recursive = true,
            bool dirs = false) const override;

        /// @copydoc Archive::findFileInfo
        FileInfoListPtr findFileInfo(const String& pattern, bool recursive = true,
            bool dirs = false) const override;

        /// @copydoc Archive::exists
        bool exists(const String& filename) const override;

        /// @copydoc Archive::getModifiedTime
        time_t getModifiedTime(const String& filename) const override;
    };

    bool gIgnoreHidden = true;
}

    //-----------------------------------------------------------------------
    FileSystemArchive::FileSystemArchive(const String& name, const String& archType, bool readOnly )
        : Archive(name, archType)
    {
        // Even failed attempt to write to read only location violates Apple AppStore validation process.
        // And successful writing to some probe file does not prove that whole location with subfolders
        // is writable. Therefore we accept read only flag from outside and do not try to be too smart.
        mReadOnly = readOnly;
    }
    //-----------------------------------------------------------------------
    bool FileSystemArchive::isCaseSensitive(void) const
    {
        #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
            return false;
        #else
            return true;
        #endif

    }
    //-----------------------------------------------------------------------
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
    static bool is_reserved_dir (const wchar_t *fn)
#else
    static bool is_reserved_dir (const char *fn)
#endif
    {
        return (fn [0] == '.' && (fn [1] == 0 || (fn [1] == '.' && fn [2] == 0)));
    }
    //-----------------------------------------------------------------------
    static bool is_absolute_path(const char* path)
    {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
        if (isalpha(uchar(path[0])) && path[1] == ':')
            return true;
#endif
        return path[0] == '/' || path[0] == '\\';
    }
    //-----------------------------------------------------------------------
    static String concatenate_path(const String& base, const String& name)
    {
        if (base.empty() || is_absolute_path(name.c_str()))
            return name;
        else
            return base + '/' + name;
    }
	//-----------------------------------------------------------------------
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
	static std::wstring to_wpath(const String& text, unsigned codepage = CP_UTF8)
	{
		const int utf16Length = ::MultiByteToWideChar(codepage, 0, text.c_str(), (int)text.size(), NULL, 0);
		if(utf16Length > 0)
		{
			std::wstring wt;
			wt.resize(utf16Length);
			if(0 != ::MultiByteToWideChar(codepage, 0, text.c_str(), (int)text.size(), &wt[0], (int)wt.size()))
				return wt;
		}
		return L"";
	}
	static String from_wpath(const std::wstring& text, unsigned codepage = CP_UTF8)
	{
		const int length = ::WideCharToMultiByte(codepage, 0, text.c_str(), (int)text.size(), NULL, 0, NULL, NULL);
		if(length > 0)
		{
			String str;
			str.resize(length);
			if(0 != ::WideCharToMultiByte(codepage, 0, text.c_str(), (int)text.size(), &str[0], (int)str.size(), NULL, NULL))
				return str;
		}
		return "";
	}
#endif
    //-----------------------------------------------------------------------
    void FileSystemArchive::findFiles(const String& pattern, bool recursive,
        bool dirs, StringVector* simpleList, FileInfoList* detailList) const
    {
        intptr_t lHandle, res;
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
        struct _wfinddata_t tagData;
#else
        struct _finddata_t tagData;
#endif

        // pattern can contain a directory name, separate it from mask
        size_t pos1 = pattern.rfind ('/');
        size_t pos2 = pattern.rfind ('\\');
        if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2)))
            pos1 = pos2;
        String directory;
        if (pos1 != pattern.npos)
            directory = pattern.substr (0, pos1 + 1);

        String full_pattern = concatenate_path(mName, pattern);

#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
        lHandle = _wfindfirst(to_wpath(full_pattern).c_str(), &tagData);
#else
        lHandle = _findfirst(full_pattern.c_str(), &tagData);
#endif
        res = 0;
        while (lHandle != -1 && res != -1)
        {
            if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) &&
                ( !gIgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
                (!dirs || !is_reserved_dir (tagData.name)))
            {
                if (simpleList)
                {
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
                    simpleList->push_back(directory + from_wpath(tagData.name));
#else
                    simpleList->push_back(directory + tagData.name);
#endif
                }
                else if (detailList)
                {
                    FileInfo fi;
                    fi.archive = this;
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
                    fi.filename = directory + from_wpath(tagData.name);
                    fi.basename = from_wpath(tagData.name);
#else
                    fi.filename = directory + tagData.name;
                    fi.basename = tagData.name;
#endif
                    fi.path = directory;
                    fi.compressedSize = tagData.size;
                    fi.uncompressedSize = tagData.size;
                    detailList->push_back(fi);
                }
            }
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
            res = _wfindnext( lHandle, &tagData );
#else
            res = _findnext( lHandle, &tagData );
#endif
        }
        // Close if we found any files
        if(lHandle != -1)
            _findclose(lHandle);

        // Now find directories
        if (recursive)
        {
            String base_dir = mName;
            if (!directory.empty ())
            {
                base_dir = concatenate_path(mName, directory);
                // Remove the last '/'
                base_dir.erase (base_dir.length () - 1);
            }
            base_dir.append ("/*");

            // Remove directory name from pattern
            String mask ("/");
            if (pos1 != pattern.npos)
                mask.append (pattern.substr (pos1 + 1));
            else
                mask.append (pattern);

#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
            lHandle = _wfindfirst(to_wpath(base_dir).c_str(), &tagData);
#else
            lHandle = _findfirst(base_dir.c_str (), &tagData);
#endif
            res = 0;
            while (lHandle != -1 && res != -1)
            {
                if ((tagData.attrib & _A_SUBDIR) &&
                    ( !gIgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
                    !is_reserved_dir (tagData.name))
                {
                    // recurse
                    base_dir = directory;
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
                    base_dir.append (from_wpath(tagData.name)).append (mask);
#else
                    base_dir.append (tagData.name).append (mask);
#endif
                    findFiles(base_dir, recursive, dirs, simpleList, detailList);
                }
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
                res = _wfindnext( lHandle, &tagData );
#else
                res = _findnext( lHandle, &tagData );
#endif
            }
            // Close if we found any files
            if(lHandle != -1)
                _findclose(lHandle);
        }
    }
    //-----------------------------------------------------------------------
    FileSystemArchive::~FileSystemArchive()
    {
        unload();
    }
    //-----------------------------------------------------------------------
    void FileSystemArchive::load()
    {
        // nothing to do here
    }
    //-----------------------------------------------------------------------
    void FileSystemArchive::unload()
    {
        // nothing to see here, move along
    }
    //-----------------------------------------------------------------------
    DataStreamPtr FileSystemArchive::open(const String& filename, bool readOnly) const
    {
        if (!readOnly && isReadOnly())
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot open a file in read-write mode in a read-only archive");
        }

        // Always open in binary mode
        // Also, always include reading
        std::ios::openmode mode = std::ios::in | std::ios::binary;

        if(!readOnly) mode |= std::ios::out;

        return _openFileStream(concatenate_path(mName, filename), mode, filename);
    }
    DataStreamPtr _openFileStream(const String& full_path, std::ios::openmode mode, const String& name)
    {
        // Use filesystem to determine size
        // (quicker than streaming to the end and back)
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
		struct _stat64i32 tagStat;
		int ret = _wstat(to_wpath(full_path).c_str(), &tagStat);
#else
        struct stat tagStat;
        int ret = stat(full_path.c_str(), &tagStat);
#endif
        size_t st_size = ret == 0 ? tagStat.st_size : 0;

        std::istream* baseStream = 0;
        std::ifstream* roStream = 0;
        std::fstream* rwStream = 0;

        if (mode & std::ios::out)
        {
            rwStream = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)();
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
			rwStream->open(to_wpath(full_path).c_str(), mode);
#else
            rwStream->open(full_path.c_str(), mode);
#endif
            baseStream = rwStream;
        }
        else
        {
            roStream = OGRE_NEW_T(std::ifstream, MEMCATEGORY_GENERAL)();
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
			roStream->open(to_wpath(full_path).c_str(), mode);
#else
            roStream->open(full_path.c_str(), mode);
#endif
            baseStream = roStream;
        }

        // Should check ensure open succeeded, in case fail for some reason.
        if (baseStream->fail())
        {
            OGRE_DELETE_T(roStream, basic_ifstream, MEMCATEGORY_GENERAL);
            OGRE_DELETE_T(rwStream, basic_fstream, MEMCATEGORY_GENERAL);
            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "Cannot open file: " + full_path);
        }

        /// Construct return stream, tell it to delete on destroy
        FileStreamDataStream* stream = 0;
        const String& streamname = name.empty() ? full_path : name;
        if (rwStream)
        {
            // use the writeable stream
            stream = OGRE_NEW FileStreamDataStream(streamname, rwStream, st_size);
        }
        else
        {
            OgreAssertDbg(ret == 0, "Problem getting file size");
            // read-only stream
            stream = OGRE_NEW FileStreamDataStream(streamname, roStream, st_size);
        }
        return DataStreamPtr(stream);
    }
    //---------------------------------------------------------------------
    DataStreamPtr FileSystemArchive::create(const String& filename)
    {
        if (isReadOnly())
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot create a file in a read-only archive");
        }

        String full_path = concatenate_path(mName, filename);

        // Always open in binary mode
        // Also, always include reading
        std::ios::openmode mode = std::ios::out | std::ios::binary;
        std::fstream* rwStream = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)();
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
		rwStream->open(to_wpath(full_path).c_str(), mode);
#else
        rwStream->open(full_path.c_str(), mode);
#endif

        // Should check ensure open succeeded, in case fail for some reason.
        if (rwStream->fail())
        {
            OGRE_DELETE_T(rwStream, basic_fstream, MEMCATEGORY_GENERAL);
            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "Cannot open file: " + filename);
        }

        /// Construct return stream, tell it to delete on destroy
        FileStreamDataStream* stream = OGRE_NEW FileStreamDataStream(filename,
                rwStream, 0, true);

        return DataStreamPtr(stream);
    }
    //---------------------------------------------------------------------
    void FileSystemArchive::remove(const String& filename)
    {
        if (isReadOnly())
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot remove a file from a read-only archive");
        }
        String full_path = concatenate_path(mName, filename);
#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
		::_wremove(to_wpath(full_path).c_str());
#else
        ::remove(full_path.c_str());
#endif
    }
    //-----------------------------------------------------------------------
    StringVectorPtr FileSystemArchive::list(bool recursive, bool dirs) const
    {
        // directory change requires locking due to saved returns
        auto ret = std::make_shared<StringVector>();

        findFiles("*", recursive, dirs, ret.get(), 0);

        return ret;
    }
    //-----------------------------------------------------------------------
    FileInfoListPtr FileSystemArchive::listFileInfo(bool recursive, bool dirs) const
    {
        auto ret = std::make_shared<FileInfoList>();

        findFiles("*", recursive, dirs, 0, ret.get());

        return ret;
    }
    //-----------------------------------------------------------------------
    StringVectorPtr FileSystemArchive::find(const String& pattern,
                                            bool recursive, bool dirs) const
    {
        auto ret = std::make_shared<StringVector>();

        findFiles(pattern, recursive, dirs, ret.get(), 0);

        return ret;

    }
    //-----------------------------------------------------------------------
    FileInfoListPtr FileSystemArchive::findFileInfo(const String& pattern,
        bool recursive, bool dirs) const
    {
        auto ret = std::make_shared<FileInfoList>();

        findFiles(pattern, recursive, dirs, 0, ret.get());

        return ret;
    }
    //-----------------------------------------------------------------------
    bool FileSystemArchive::exists(const String& filename) const
    {
        if (filename.empty())
            return false;

        String full_path = concatenate_path(mName, filename);

#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
        struct _stat64i32 tagStat;
        bool ret = (_wstat(to_wpath(full_path).c_str(), &tagStat) == 0);
#else
        struct stat tagStat;
        bool ret = (stat(full_path.c_str(), &tagStat) == 0);
#endif

        // stat will return true if the filename is absolute, but we need to check
        // the file is actually in this archive
        if (ret && is_absolute_path(filename.c_str()))
        {
            // only valid if full path starts with our base
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
            // case insensitive on windows
            String lowerCaseName = mName;
            StringUtil::toLowerCase(lowerCaseName);
            ret = Ogre::StringUtil::startsWith(full_path, lowerCaseName, true);
#else
            // case sensitive
            ret = Ogre::StringUtil::startsWith(full_path, mName, false);
#endif
        }

        return ret;
    }
    //---------------------------------------------------------------------
    time_t FileSystemArchive::getModifiedTime(const String& filename) const
    {
        String full_path = concatenate_path(mName, filename);

#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE
		struct _stat64i32 tagStat;
		bool ret = (_wstat(to_wpath(full_path).c_str(), &tagStat) == 0);
#else
        struct stat tagStat;
        bool ret = (stat(full_path.c_str(), &tagStat) == 0);
#endif

        if (ret)
        {
            return tagStat.st_mtime;
        }
        else
        {
            return 0;
        }

    }
    //-----------------------------------------------------------------------
    const String& FileSystemArchiveFactory::getType(void) const
    {
        static String name = "FileSystem";
        return name;
    }

    Archive *FileSystemArchiveFactory::createInstance( const String& name, bool readOnly )
    {
        return OGRE_NEW FileSystemArchive(name, getType(), readOnly);
    }

    void FileSystemArchiveFactory::setIgnoreHidden(bool ignore)
    {
        gIgnoreHidden = ignore;
    }

    bool FileSystemArchiveFactory::getIgnoreHidden()
    {
        return gIgnoreHidden;
    }
}


text:
<?php

namespace Drupal\Component\Utility;

/**
 * Rectangle rotation algebra class.
 *
 * This class is used by the image system to abstract, from toolkit
 * implementations, the calculation of the expected dimensions resulting from
 * an image rotate operation.
 *
 * Different versions of PHP for the GD toolkit, and alternative toolkits, use
 * different algorithms to perform the rotation of an image and result in
 * different dimensions of the output image. This prevents predictability of
 * the final image size for instance by the image rotate effect, or by image
 * toolkit rotate operations.
 *
 * This class implements a calculation algorithm that returns, given input
 * width, height and rotation angle, dimensions of the expected image after
 * rotation that are consistent with those produced by the GD rotate image
 * toolkit operation using PHP 5.5 and above.
 *
 * @see \Drupal\system\Plugin\ImageToolkit\Operation\gd\Rotate
 */
class Rectangle {

  /**
   * The width of the rectangle.
   *
   * @var int
   */
  protected $width;

  /**
   * The height of the rectangle.
   *
   * @var int
   */
  protected $height;

  /**
   * The width of the rotated rectangle.
   *
   * @var int
   */
  protected $boundingWidth;

  /**
   * The height of the rotated rectangle.
   *
   * @var int
   */
  protected $boundingHeight;

  /**
   * Constructs a new Rectangle object.
   *
   * @param int $width
   *   The width of the rectangle.
   * @param int $height
   *   The height of the rectangle.
   */
  public function __construct($width, $height) {
    if ($width > 0 && $height > 0) {
      $this->width = $width;
      $this->height = $height;
      $this->boundingWidth = $width;
      $this->boundingHeight = $height;
    }
    else {
      throw new \InvalidArgumentException("Invalid dimensions ({$width}x{$height}) specified for a Rectangle object");
    }
  }

  /**
   * Rotates the rectangle.
   *
   * @param float $angle
   *   Rotation angle.
   *
   * @return $this
   */
  public function rotate($angle) {
    // PHP 5.5 GD bug: https://bugs.php.net/bug.php?id=65148: To prevent buggy
    // behavior on negative multiples of 30 degrees we convert any negative
    // angle to a positive one between 0 and 360 degrees.
    $angle -= floor($angle / 360) * 360;

    // For some rotations that are multiple of 30 degrees, we need to correct
    // an imprecision between GD that uses C floats internally, and PHP that
    // uses C doubles. Also, for rotations that are not multiple of 90 degrees,
    // we need to introduce a correction factor of 0.5 to match the GD
    // algorithm used in PHP 5.5 (and above) to calculate the width and height
    // of the rotated image.
    if ((int) $angle == $angle && $angle % 90 == 0) {
      $imprecision = 0;
      $correction = 0;
    }
    else {
      $imprecision = -0.00001;
      $correction = 0.5;
    }

    // Do the trigonometry, applying imprecision fixes where needed.
    $rad = deg2rad($angle);
    $cos = cos($rad);
    $sin = sin($rad);
    $a = $this->width * $cos;
    $b = $this->height * $sin + $correction;
    $c = $this->width * $sin;
    $d = $this->height * $cos + $correction;
    if ((int) $angle == $angle && in_array($angle, [60, 150, 300])) {
      $a = $this->fixImprecision($a, $imprecision);
      $b = $this->fixImprecision($b, $imprecision);
      $c = $this->fixImprecision($c, $imprecision);
      $d = $this->fixImprecision($d, $imprecision);
    }

    // This is how GD on PHP5.5 calculates the new dimensions.
    $this->boundingWidth = abs((int) $a) + abs((int) $b);
    $this->boundingHeight = abs((int) $c) + abs((int) $d);

    return $this;
  }

  /**
   * Performs an imprecision check on the input value and fixes it if needed.
   *
   * GD that uses C floats internally, whereas we at PHP level use C doubles.
   * In some cases, we need to compensate imprecision.
   *
   * @param float $input
   *   The input value.
   * @param float $imprecision
   *   The imprecision factor.
   *
   * @return float
   *   A value, where imprecision is added to input if the delta part of the
   *   input is lower than the absolute imprecision.
   */
  protected function fixImprecision($input, $imprecision) {
    if ($this->delta($input) < abs($imprecision)) {
      return $input + $imprecision;
    }
    return $input;
  }

  /**
   * Returns the fractional part of a float number, unsigned.
   *
   * @param float $input
   *   The input value.
   *
   * @return float
   *   The fractional part of the input number, unsigned.
   */
  protected function fraction($input) {
    return abs((int) $input - $input);
  }

  /**
   * Returns the difference of a fraction from the closest between 0 and 1.
   *
   * @param float $input
   *   The input value.
   *
   * @return float
   *   the difference of a fraction from the closest between 0 and 1.
   */
  protected function delta($input) {
    $fraction = $this->fraction($input);
    return $fraction > 0.5 ? (1 - $fraction) : $fraction;
  }

  /**
   * Gets the bounding width of the rectangle.
   *
   * @return int
   *   The bounding width of the rotated rectangle.
   */
  public function getBoundingWidth() {
    return $this->boundingWidth;
  }

  /**
   * Gets the bounding height of the rectangle.
   *
   * @return int
   *   The bounding height of the rotated rectangle.
   */
  public function getBoundingHeight() {
    return $this->boundingHeight;
  }

}


text:
RSpec.configure do |config|
  # use mocha
  config.mock_with :mocha

  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

  # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
  # have no way to turn it off -- the option exists only for backwards
  # compatibility in RSpec 3). It causes shared context metadata to be
  # inherited by the metadata hash of host groups and examples, rather than
  # triggering implicit auto-inclusion in groups with matching metadata.
  config.shared_context_metadata_behavior = :apply_to_host_groups
end


text:
@interface UINavigationController (StatusBar)

- (UIStatusBarStyle)preferredStatusBarStyle;

@end


text:
package org.jetbrains.plugins.scala.lang.autoImport

import org.jetbrains.plugins.scala.autoImport.quickFix._
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScReferenceExpression
import org.jetbrains.plugins.scala.{LatestScalaVersions, ScalaVersion}

class ImportExtensionMethodFixText
  extends ImportElementFixTestBase[ScReferenceExpression] {

  override protected def supportedIn(version: ScalaVersion): Boolean = version >= LatestScalaVersions.Scala_3_0

  override def createFix(ref: ScReferenceExpression): Option[ScalaImportElementFix[_ <: ElementToImport]] =
    ImportImplicitConversionFixes(ref).find(_.isInstanceOf[ImportExtensionMethodFix])

  def testPostfix(): Unit = checkElementsToImport(
    s"""object Extensions:
       |  extension (i: Int)
       |   def timesTen: Int = i * 10
       |end Extensions
       |
       |object Test:
       |  2 ${CARET}timesTen
       |""".stripMargin,

    "Extensions.timesTen"
  )

  def testInfix(): Unit = checkElementsToImport(
    s"""object Extensions:
       |  extension (i: Int)
       |   def times(n: Int): Int = i * n
       |end Extensions
       |
       |object Test:
       |  2 ${CARET}times n
       |""".stripMargin,

    "Extensions.times"
  )

  // TODO: `T | Null` is not supported yet. Change to `extension [T](x: T | Null)` when fixed
  def testGenericExtension(): Unit = checkElementsToImport(
    s"""object Extensions:
       |  extension [T](x: T)
       |    inline def toOption: Option[T] =
       |      if x == null then None else Some(x.asInstanceOf[T])
       |end Extensions
       |
       |"".${CARET}toOption
       |""".stripMargin,

    "Extensions.toOption"
  )

  def testExtensionOnGenericType(): Unit = checkElementsToImport(
    s"""object Extensions:
       |  extension [T](x: T)
       |    def toOption: Option[T] = Option(x)
       |
       |class Test:
       |  def foo[T](t: T): Unit =
       |    t.${CARET}toOption
       |""".stripMargin,

    "Extensions.toOption"
  )

  def testGenericExtensionWithGenericMethodAndContextBound(): Unit = checkElementsToImport(
    s"""object Extensions:
       |  extension [T](xs: List[T])
       |    def sumBy[U: Numeric](f: T => U): U = ???
       |end Extensions
       |
       |List("a", "bb", "ccc").${CARET}sumBy[Int](_.length)
       |""".stripMargin,

    "Extensions.sumBy"
  )

  def testGenericExtensionWithBound(): Unit = checkElementsToImport(
    s"""trait Element
       |object MyElement extends Element
       |
       |object Extensions:
       |  extension [E <: Element](element: E)
       |    def doSomething(): Unit = ???
       |end Extensions
       |
       |class Test:
       |  MyElement.${CARET}doSomething()
       |""".stripMargin,

    "Extensions.doSomething"
  )

  def testStringInterpolation(): Unit = checkElementsToImport(
    s"""object StringInterpol:
       |  extension (sc: StringContext)
       |    def xy(args: Any*): BigDecimal = BigDecimal(sc.parts.head)
       |
       |class Test:
       |  ${CARET}xy"100500"
       |""".stripMargin,

    "StringInterpol.xy"
  )

  def testGenericExtensionWithTypeConstructor(): Unit = checkElementsToImport(
    s"""object Extensions:
       |  extension [CC[X] <: Seq[X], A <: AnyRef](cc: CC[A])
       |    def firstBy[B](f: A => B)(using ord: Ordering[B]): Option[A] = ???
       |
       |class Test:
       |  Nil.${CARET}firstBy()
       |""".stripMargin,

    "Extensions.firstBy"
  )

  def testFindMultipleExtensionMethodsInDifferentPackages(): Unit = checkElementsToImport(
    s"""package tests
       |
       |package ext1:
       |  object Extensions:
       |    extension (s: String)
       |      def toOption: Option[String] = Option(s)
       |end ext1
       |
       |package ext2:
       |  object Extensions:
       |    extension (s: String)
       |      def toOption: Option[String] = Option(s)
       |end ext2
       |
       |object Extensions:
       |  extension (s: String)
       |    def toOption: Option[String] = Option(s)
       |
       |"".${CARET}toOption
       |""".stripMargin,

    "tests.Extensions.toOption",
    "tests.ext1.Extensions.toOption",
    "tests.ext2.Extensions.toOption"
  )

  def testDoNotIncludeLocalExtensionOutsideOfItsScope(): Unit = checkNoImportFix(
    s"""object LocalExt:
       |  def foo[T](x: T): Unit = x match
       |  case s: String =>
       |    extension (str: String) def localExtensionMethod: Int = str.length * 2
       |  case _ =>
       |end LocalExt
       |
       |"".${CARET}localExtensionMethod
       |""".stripMargin
  )

  def testExtensionInsideGiven(): Unit = checkElementsToImport(
    s"""package tests
       |
       |final case class Context(things: Vector[String]) {
       |  def add(something: String) = Context(things :+ something)
       |}
       |
       |object Extensions:
       |  given ops: AnyRef with
       |    extension (c: Context)
       |      def addSomething(something: String) =
       |        c.add(something)
       |end Extensions
       |
       |val context = Context(Vector("foo", "bar"))
       |context.${CARET}addSomething("baz")
       |""".stripMargin,

    "tests.Extensions.ops"
  )

  def testIncludeTopLevelExtension(): Unit = checkElementsToImport(
    s"""package tests
       |
       |package ext:
       |  extension (s: String)
       |    def toOption: Option[String] = Option(s)
       |end ext
       |
       |"".${CARET}toOption
       |""".stripMargin,

    "tests.ext.toOption"
  )

}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestaurantSystem.Data.Repositories
{
    public class GenericEFRepository<T> : IRepository<T> where T : class
    {
        private DbContext context;
        private IDbSet<T> set;

        public GenericEFRepository(DbContext context)
        {
            this.context = context;
            this.set = context.Set<T>();

        }

        public IDbSet<T> Set
        {
            get { return this.set; }
        }

        public IQueryable<T> All()
        {
            return this.set;
        }

        public T Find(object id)
        {
            return this.set.Find(id);
        }

        public void Add(T entity)
        {
            this.ChangeState(entity, EntityState.Added);
        }

        public void Update(T entity)
        {
            this.ChangeState(entity, EntityState.Modified);
        }

        public void Delete(T entity)
        {
            this.ChangeState(entity, EntityState.Deleted);
        }

        public T Delete(object id)
        {
            var entity = this.Find(id);
            this.Delete(entity);
            return entity;
        }

        private void ChangeState(T entity, EntityState state)
        {
            var entry = this.context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                this.set.Attach(entity);
            }

            entry.State = state;
        }
    }
}


text:
package org.apache.brooklyn.entity.cloudfoundry.services.generic;

import org.apache.brooklyn.entity.cloudfoundry.services.CloudFoundryService;
import org.apache.brooklyn.api.entity.ImplementedBy;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.util.core.flags.SetFromFlag;

/**
 * This Interface represent a generic and empty service.
 * It could be bound to any application but the operation it will be empty.
 * The ServiceType is not predefined and it should be defined for the service creation.
 */

@ImplementedBy(GenericServiceImpl.class)
public interface GenericService extends CloudFoundryService {

    @SetFromFlag("serviceType")
    public static final ConfigKey<String> SERVICE_TYPE = ConfigKeys
            .newStringConfigKey("service.type", "Type Of Service");

}


name

No valid Android SDK targets found.: No valid Android SDK targets found.

No Android SDK targets found.: No Android SDK targets found.

Please download an Android SDK target API level %s or newer from the Android SDK Manager and try again.

Unable to locate the Java Development Kit: Unable to locate the Java Development Kit

You can specify the location by setting the %s environment variable.

JDK version %s detected, but only version %s is supported: JDK version %s detected, but only version %s is supported

the alias for the keystore: the alias for the keystore

What is the name of the keystore's certificate alias?: What is the name of the keystore's certificate alias?

Select a certificate alias by number or name: Select a certificate alias by number or name

Invalid "--alias" value "%s": Invalid "--alias" value "%s"

The selected alias %s uses the %s signature algorithm which will likely have issues with Android 4.3 and older.

Certificates that use the %s or %s signature algorithm will provide better compatibility.

the path to the Android SDK: the path to the Android SDK

path: path

Where is the Android SDK?: Where is the Android SDK?

Invalid Android SDK path: Invalid Android SDK path

The Android SDK path cannot contain ampersands (&) on Windows: The Android SDK path cannot contain ampersands (&) on Windows

Invalid Android SDK path: %s: Invalid Android SDK path: %s

the abi for the Android emulator; deprecated, use --device-id: the abi for the Android emulator; deprecated, use --device-id

abi: abi

the id for the Android emulator; deprecated, use --device-id: the id for the Android emulator; deprecated, use --device-id

the skin for the Android emulator; deprecated, use --device-id: the skin for the Android emulator; deprecated, use --device-id

skin: skin

the type of deployment; only used when target is %s or %s: the type of deployment; only used when target is %s or %s

type: type

the name of the Android emulator or the device id to install the application to

Devices: Devices

Which device do you want to install your app on?: Which device do you want to install your app on?

Select a device by number or name: Select a device by number or name

Android Emulators: Android Emulators

Genymotion Emulators: Genymotion Emulators

NOTE: Genymotion emulator must be running to detect Google API support

Which emulator do you want to launch your app in?: Which emulator do you want to launch your app in?

Select an emulator by number or name: Select an emulator by number or name

Unable to find any devices: Unable to find any devices

Please plug in an Android device, then try again.: Please plug in an Android device, then try again.

Unable to find any emulators: Unable to find any emulators

Please create an Android emulator, then try again.: Please create an Android emulator, then try again.

Google APIs supported: Google APIs supported

Google APIs support unknown: Google APIs support unknown

Invalid Android device "%s": Invalid Android device "%s"

Invalid Android emulator "%s": Invalid Android emulator "%s"

one: Found %s avd with id "%%s"

other: Found %s avds with id "%%s"

Specify --avd-skin and --avd-abi to select a specific emulator: Specify --avd-skin and --avd-abi to select a specific emulator

No emulators found with id "%s" and skin "%s": No emulators found with id "%s" and skin "%s"

one: Found %s avd with id "%%s" and skin "%%s"

other: Found %s avds with id "%%s" and skin "%%s"

Specify --avd-abi to select a specific emulator: Specify --avd-abi to select a specific emulator

No emulators found with id "%s", skin "%s", and abi "%s": No emulators found with id "%s", skin "%s", and abi "%s"

%s options have been %s, please use %s: %s options have been %s, please use %s

Available Emulators: Available Emulators:

the password for the keystore private key (defaults to the store-password)

the type of a digital signature algorithm. only used when overriding keystore signing algorithm

What is the keystore's __key password__?: What is the keystore's __key password__?

(leave blank to use the store password): (leave blank to use the store password)

Bad key password: Bad key password

the location of the keystore file: the location of the keystore file

Where is the __keystore file__ used to sign the app?: Where is the __keystore file__ used to sign the app?

Please specify the path to your keystore file: Please specify the path to your keystore file

Invalid keystore file: Invalid keystore file

the output directory when using %s: the output directory when using %s

Where would you like the output APK file saved?: Where would you like the output APK file saved?

Invalid output directory: Invalid output directory

the password for the keystore: the password for the keystore

What is the keystore's __password__?: What is the keystore's __password__?

Please specify a keystore password: Please specify a keystore password

Keystore does not contain any certificates: Keystore does not contain any certificates

the target to build for: the target to build for

The %s tiapp.xml property has been deprecated, please use the %s option to bypass JavaScript minification

The app name "%s" contains an ampersand (&) which will most likely cause problems.

It is recommended that you define the app name using i18n strings.

Refer to %s for more information.: Refer to %s for more information.

To allow ampersands in the app name, run: To allow ampersands in the app name, run:

tiapp.xml contains an invalid app id "%s": tiapp.xml contains an invalid app id "%s"

The app id must consist only of letters, numbers, dashes, and underscores.

Note: Android does not allow dashes.: Note: Android does not allow dashes.

The first character must be a letter or underscore.: The first character must be a letter or underscore.

Usually the app id is your company's reversed Internet domain name. (i.e. com.example.myapp)

The app id must consist of letters, numbers, and underscores.: The app id must consist of letters, numbers, and underscores.

The first character after a period must not be a number.: The first character after a period must not be a number.

Invalid app id "%s": Invalid app id "%s"

The app id must not contain Java reserved words.: The app id must not contain Java reserved words.

Invalid "ti.ui.defaultunit" property value "%s": Invalid "ti.ui.defaultunit" property value "%s"

Valid units: Valid units:

Missing ProGuard configuration file: Missing ProGuard configuration file

ProGuard settings must go in the file "%s": ProGuard settings must go in the file "%s"

For example configurations, visit %s: For example configurations, visit %s

Malformed <manifest> definition in the <android> section of the tiapp.xml

Malformed custom AndroidManifest.xml file: %s: Malformed custom AndroidManifest.xml file: %s

%s has been deprecated, please specify the target SDK using the %s tag:

The minimum supported SDK version must be %s or newer, but is currently set to %s

Update the %s in the tiapp.xml or custom AndroidManifest to at least %s:

The target SDK version must be %s or newer, but is currently set to %s

The target SDK must be greater than or equal to the minimum SDK %s, but is currently set to %s

Unable to find a suitable installed Android SDK that is >=%s and <=%s

Target Android SDK %s is not installed: Target Android SDK %s is not installed

To target Android SDK %s, you first must install it using the Android SDK manager.

Alternatively, you can set the %s in the %s section of the tiapp.xml to one of the following installed Android target SDKs: %s

Target Android SDK %s is missing "android.jar": Target Android SDK %s is missing "android.jar"

Target Android SDK version must be %s or newer: Target Android SDK version must be %s or newer

Maximum Android SDK version must be greater than or equal to the target SDK %s, but is currently set to %s

Building with Android SDK %s which hasn't been tested against Titanium SDK %s

Invalid ABI "%s": Invalid ABI "%s"

Valid ABIs: Valid ABIs:

Auto selecting device that closest matches %s: Auto selecting device that closest matches %s

Auto selecting emulator that closest matches %s: Auto selecting emulator that closest matches %s

Auto selected device %s %s: Auto selected device %s %s

Auto selected emulator %s %s: Auto selected emulator %s %s

Searching for version >= %s and has Google APIs: Searching for version >= %s and has Google APIs

Searching for version >= %s and may have Google APIs: Searching for version >= %s and may have Google APIs

Searching for version >= %s and no Google APIs: Searching for version >= %s and no Google APIs

Searching for version < %s and has Google APIs: Searching for version < %s and has Google APIs

Searching for version < %s and no Google APIs: Searching for version < %s and no Google APIs

Selecting first device: Selecting first device

one: The emulator "%%s" does not support the desired ABI %%s

other: The emulator "%%s" does not support the desired ABIs %%s

one: The device "%%s" does not support the desired ABI %%s

other: The device "%%s" does not support the desired ABIs %%s

Supported ABIs: %s: Supported ABIs: %s

You need to add at least one of the device's supported ABIs to the tiapp.xml

Invalid %s host "%s": Invalid %s host "%s"

The %s host must be in the format "host:port".: The %s host must be in the format "host:port".

The port must be a valid integer between 1 and 65535.: The port must be a valid integer between 1 and 65535.

Unable find emulator "%s": Unable find emulator "%s"

The selected emulator "%s" does not have an SD card.: The selected emulator "%s" does not have an SD card.

An SD card is required for profiling.: An SD card is required for profiling.

An SD card is required for debugging.: An SD card is required for debugging.

Cannot debug application when --device-id is set to "all" and more than one device is connected.

Please specify a single device to debug on.: Please specify a single device to debug on.

The build directory is not writeable: %s: The build directory is not writeable: %s

Make sure the build directory is writeable and that you have sufficient free disk space.

The project directory is not writeable: %s: The project directory is not writeable: %s

Make sure the project directory is writeable and that you have sufficient free disk space.

Could not find all required Titanium Modules: Could not find all required Titanium Modules:

Found incompatible Titanium Modules: Found incompatible Titanium Modules:

Found conflicting Titanium modules: Found conflicting Titanium modules:

Titanium module "%s" requested for both Android and CommonJS platforms, but only one may be used at a time.

Module %s version %s is missing module file: %s: Module %s version %s is missing module file: %s

Module %s version %s does not have a main jar file: Module %s version %s does not have a main jar file

one: The module %%s does not support the ABI: %%s

other: The module %%s does not support the ABIs: %s

It only supports the following ABIs: %s: It only supports the following ABIs: %s

Your application will most likely encounter issues: Your application will most likely encounter issues

Module %s version %s is missing bindings json file: Module %s version %s is missing bindings json file

The module "%s" has an invalid jar file: %s: The module "%s" has an invalid jar file: %s

Conflicting jar files detected: Conflicting jar files detected:

The following modules have different "%s" files: The following modules have different "%s" files

%s (version %s) (hash=%s): %s (version %s) (hash=%s)

You can either select a version of these modules where the conflicting jar file is the same or you can try copying the jar file from one module's "lib" folder to the other module's "lib" folder.

Finished building the application in %s: Finished building the application in %s

Unable to find Android emulator "%s": Unable to find Android emulator "%s"

Titanium SDK Android directory: %s: Titanium SDK Android directory: %s

Deploy type: %s: Deploy type: %s

Building for target: %s: Building for target: %s

Performing build only: Performing build only

Building for emulator: %s: Building for emulator: %s

Building for device: %s: Building for device: %s

Targeting Android SDK: %s: Targeting Android SDK: %s

Building for the following architectures: %s: Building for the following architectures: %s

Signing with keystore: %s: Signing with keystore: %s

App ID: %s: App ID: %s

Classname: %s: Classname: %s

Debugging enabled via debug port: %s: Debugging enabled via debug port: %s

Debugging disabled: Debugging disabled

Profiler enabled via profiler port: %s: Profiler enabled via profiler port: %s

Profiler disabled: Profiler disabled

Forcing rebuild: %s flag was set: Forcing rebuild: %s flag was set

Forcing rebuild: %s does not exist: Forcing rebuild: %s does not exist

Forcing rebuild: target changed since last build: Forcing rebuild: target changed since last build

Was: %s: Was: %s

Now: %s: Now: %s

Forcing rebuild: deploy type changed since last build: Forcing rebuild: deploy type changed since last build

Forcing rebuild: classname changed since last build: Forcing rebuild: classname changed since last build

Forcing rebuild: JavaScript files need to be re-encrypted: Forcing rebuild: JavaScript files need to be re-encrypted

Forcing rebuild: JavaScript encryption flag changed: Forcing rebuild: JavaScript encryption flag changed

Forcing rebuild: Titanium SDK path changed since last build: Forcing rebuild: Titanium SDK path changed since last build

Forcing rebuild: githash changed since last build: Forcing rebuild: githash changed since last build

Forcing rebuild: modules hash changed since last build: Forcing rebuild: modules hash changed since last build

Forcing rebuild: module manifest hash changed since last build: Forcing rebuild: module manifest hash changed since last build

Forcing rebuild: native modules hash changed since last build: Forcing rebuild: native modules hash changed since last build

Forcing rebuild: native modules bindings hash changed since last build

Forcing rebuild: tiapp.xml project name changed since last build: Forcing rebuild: tiapp.xml project name changed since last build

Forcing rebuild: tiapp.xml app id changed since last build: Forcing rebuild: tiapp.xml app id changed since last build

Forcing rebuild: tiapp.xml analytics flag changed since last build

Forcing rebuild: tiapp.xml publisher changed since last build: Forcing rebuild: tiapp.xml publisher changed since last build

Forcing rebuild: tiapp.xml url changed since last build: Forcing rebuild: tiapp.xml url changed since last build

Forcing rebuild: tiapp.xml version changed since last build: Forcing rebuild: tiapp.xml version changed since last build

Forcing rebuild: tiapp.xml description changed since last build: Forcing rebuild: tiapp.xml description changed since last build

Forcing rebuild: tiapp.xml copyright changed since last build: Forcing rebuild: tiapp.xml copyright changed since last build

Forcing rebuild: tiapp.xml guid changed since last build: Forcing rebuild: tiapp.xml guid changed since last build

Forcing rebuild: tiapp.xml icon changed since last build: Forcing rebuild: tiapp.xml icon changed since last build

Forcing rebuild: tiapp.xml fullscreen changed since last build: Forcing rebuild: tiapp.xml fullscreen changed since last build

Forcing rebuild: Android minimum SDK changed since last build: Forcing rebuild: Android minimum SDK changed since last build

Forcing rebuild: Android target SDK changed since last build: Forcing rebuild: Android target SDK changed since last build

Forcing rebuild: tiapp.xml properties changed since last build: Forcing rebuild: tiapp.xml properties changed since last build

Forcing rebuild: Android activites in tiapp.xml changed since last build

Forcing rebuild: Android services in tiapp.xml SDK changed since last build

Forcing rebuild: One or more JSS files changed since last build: Forcing rebuild: One or more JSS files changed since last build

Forcing rebuild: mergeCustomAndroidManifest config has changed since last build

Overwriting file %s: Overwriting file %s

Symlinking %s => %s: Symlinking %s => %s

Copying %s => %s: Copying %s => %s

Ignoring %s: Ignoring %s

Found conflicting resources: Found conflicting resources:

You cannot have resources that resolve to the same resource entry name

Copying and minifying %s => %s: Copying and minifying %s => %s

You have both an %s folder and an %s folder: You have both an %s folder and an %s folder

Files from both of these folders will end up in %s: Files from both of these folders will end up in %s

If two files are named the same, there is no guarantee which one will be copied last and therefore be the one the application uses

You should use just one of these folders to avoid conflicts: You should use just one of these folders to avoid conflicts

There is a project resource "%s" that conflicts with a CommonJS module

Please rename the file, then rebuild: Please rename the file, then rebuild

Processing JavaScript files: Processing JavaScript files

Encrypting JavaScript files: %s: Encrypting JavaScript files: %s

Failed to encrypt JavaScript files: Failed to encrypt JavaScript files

32-bit titanium prep failed, trying again using 64-bit: 32-bit titanium prep failed, trying again using 64-bit

Adding library %s: Adding library %s

Unknown namespace %s, skipping: Unknown namespace %s, skipping

Adding dependency library %s: Adding dependency library %s

The "apiversion" for "%s" in the module manifest is less than version 2.

The module was likely built against a Titanium SDK 1.8.0.1 or older.

Please use a version of the module that has "apiversion" 2 or greater

Writing %s: Writing %s

Forcing rebuild: Detected change in Titanium APIs used and need to recompile

Extracting module resources: %s: Extracting module resources: %s

Failed to extract module resource zip: %s: Failed to extract module resource zip: %s

Removing old file: %s: Removing old file: %s

Removing old symlink: %s: Removing old symlink: %s

Copying template %s => %s: Copying template %s => %s

Generating activity class: %s: Generating activity class: %s

Generating interval service class: %s: Generating interval service class: %s

Generating service class: %s: Generating service class: %s

Android SDK %s missing framework aidl, skipping: Android SDK %s missing framework aidl, skipping

Android does not allow i18n string names with spaces.: Android does not allow i18n string names with spaces.

To exclude invalid i18n strings from the build, run: To exclude invalid i18n strings from the build, run:

Writing unmerged custom AndroidManifest.xml: Writing unmerged custom AndroidManifest.xml

Detected %s call which requires Google APIs, however the selected emulator %s may or may not support Google APIs

If the emulator does not support Google APIs, the %s call will fail

Detected %s call which requires Google APIs, but the selected emulator %s does not support Google APIs

You should use, or create, an Android emulator that does support Google APIs

Invalid native Titanium library ABI "%s": Invalid native Titanium library ABI "%s"

The module %s does not support the ABI: %s: The module %s does not support the ABI: %s

Performed build only, skipping installing of the application: Performed build only, skipping installing of the application

No APK file to install and run, skipping: No APK file to install and run, skipping

Emulator failed to start in a timely manner: Emulator failed to start in a timely manner

You can increase this timeout by running: %s: You can increase this timeout by running: %s

Checking if package manager service is started: Checking if package manager service is started

Package manager not started yet, trying again in %sms...: Package manager not started yet, trying again in %sms...

ADB install failed because package manager service is still starting, trying again in %sms...

Make sure your keystore is signed with a compatible signature algorithm such as "SHA1withRSA" or "MD5withRSA".

Forwarding host port %s to device for debugging: Forwarding host port %s to device for debugging

Forwarding host port %s to device for profiling: Forwarding host port %s to device for profiling

Failed to merge, source must be an AndroidManifest object: Failed to merge, source must be an AndroidManifest object

not supported by Titanium SDK %s, but may work: not supported by Titanium SDK %s, but may work

Description: Description


text:
package mesosphere.marathon
package core.task.termination

/**
  * Enumeration for reasons why a task has been killed.
  *
  * This is not sealed on purpose as there might be different reasons for
  * components build on top of the core.
  */
trait KillReason

object KillReason {

  /** The task is killed because of an incoming http request */
  case object KillingTasksViaApi extends KillReason

  /** The task is killed because it didn't turn running within a given time frame */
  case object Overdue extends KillReason

  /** The task is killed because it is unknown */
  case object Unknown extends KillReason

  /** The task is killed because the instance owning this task is associated with a different taskId */
  case object NotInSync extends KillReason

  /** The task is killed because it exceeded the maximum number of consecutive health check failures */
  case object FailedHealthChecks extends KillReason
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: src/proto/grpc/testing/payloads.proto

namespace Grpc\Testing;

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

/**
 * Protobuf type grpc.testing.ByteBufferParams
 */
class ByteBufferParams extends \Google\Protobuf\Internal\Message
{
    /**
     * int32 req_size = 1;
     */
    private $req_size = 0;
    /**
     * int32 resp_size = 2;
     */
    private $resp_size = 0;

    public function __construct() {
        \GPBMetadata\Src\Proto\Grpc\Testing\Payloads::initOnce();
        parent::__construct();
    }

    /**
     * int32 req_size = 1;
     */
    public function getReqSize()
    {
        return $this->req_size;
    }

    /**
     * int32 req_size = 1;
     */
    public function setReqSize($var)
    {
        GPBUtil::checkInt32($var);
        $this->req_size = $var;
    }

    /**
     * int32 resp_size = 2;
     */
    public function getRespSize()
    {
        return $this->resp_size;
    }

    /**
     * int32 resp_size = 2;
     */
    public function setRespSize($var)
    {
        GPBUtil::checkInt32($var);
        $this->resp_size = $var;
    }

}


text:
local ffi = require("ffi")

local common = require("testy.ovsdb_command_common")
local stringz = require("stringz")
local OptionParser = require("std.optparse")

local OptionsSpec = [[
VERSION: v1.0

Usage: ovs_appctl.lua

NOTE: For specifying various command line flags, you MUST
have a 'comment' after the flag, or the parser will hang

Options:
    -t, --target=TARGET         pidfile or socket to contact
    -e, --execute               no argument
    -o, --option                display some options
    -T, --timeout=SECS          wait at most SECS seconds for a response
    -V, --version               display ovs_appctr version information
    -h, --help                  display help and exit
]]

local program_name = arg[1];

--[[
#include <config.h>

#include "daemon.h"
#include "dynamic-string.h"
#include "process.h"
#include "timeval.h"
#include "util.h"
#include "openvswitch/vlog.h"
--]]

local function main()

    --set_program_name(argv[0]);

    -- Parse command line and connect to target. */
    local target = parse_command_line();
    local client = connect_to_target(target);
--[[
    -- Transact request and process reply. */
    local cmd = argv[optind++];
    local cmd_argc = argc - optind;
    local cmd_argv = nil;
    if cmd_argc ~= 0 then
        cmd_argv = argv+optind;
    end

    local cmd_resultp = ffi.new("char *[1]")
    local cmd_errorp = ffi.new("char *[1]")

    local err = unixctl_client_transact(client, cmd, cmd_argc, cmd_argv,
                                    cmd_resultp, cmd_errorp);

    local cmd_result = cmd_resultp[0];
    local cmd_error = cmd_errorp[0];

    if (err ~= 0) then
        ovs_fatal(err, "%s: transaction error", target);
    end

    if (cmd_error ~= 0) then
        jsonrpc_close(client);
        fputs(cmd_error, stderr);
        ovs_error(0, "%s: server returned an error", target);
        exit(2);
    elseif (cmd_result ~= nil) then
        fputs(cmd_result, stdout);
    else
        OVS_NOT_REACHED();
    end
--]]
    jsonrpc_close(client);
    --ffi.C.free(cmd_result);
    --ffi.C.free(cmd_error);

    return 0;
end

local function usage()

    print(string.format([[
%s, for querying and controlling Open vSwitch daemon
usage: %s [TARGET] COMMAND [ARG...]
Targets:
  -t, --target=TARGET  pidfile or socket to contact
Common commands:
  list-commands      List commands supported by the target
  version            Print version of the target
  vlog/list          List current logging levels
  vlog/set [SPEC]
      Set log levels as detailed in SPEC, which may include:
      A valid module name (all modules, by default)
      'syslog', 'console', 'file' (all destinations, by default))
      'off', 'emer', 'err', 'warn', 'info', or 'dbg' ('dbg', bydefault)
  vlog/reopen        Make the program reopen its log file
Other options:
  --timeout=SECS     wait at most SECS seconds for a response
  -h, --help         Print this helpful information
  -V, --version      Display ovs-appctl version information
]],
        program_name, program_name));

    exit(EXIT_SUCCESS);
end

--[[
    static const struct option long_options[] = {
         {"execute", no_argument, NULL, 'e'},
        {"help", no_argument, NULL, 'h'},
        {"option", no_argument, NULL, 'o'},
        {"version", no_argument, NULL, 'V'},
        {"timeout", required_argument, NULL, 'T'},
        VLOG_LONG_OPTIONS,
        {NULL, 0, NULL, 0},
    };
--]]

local function parse_command_line()

--    enum {
--        OPT_START = UCHAR_MAX + 1,
--        VLOG_OPTION_ENUMS
--    };

    local parser = OptionParser(OptionsSpec);

    parser:on('--', parser.finished)

    _G.arg, _G.opts = parser:parse (_G.arg)

    local target = nil;
    local e_options = 0;

    local actions = {
        target = function(value)
            print("==== argActions.target: ", value);
            if target ~= nil then
                ovs_fatal(0, "-t or --target may be specified only once");
            end

            target = value;
        end,

        help = function(value)
            print("==== argActions.help: ", value)
            usage();
        end,
    }

    -- Perform actions based on command line arguments
    for k,value in pairs(opts) do
        if actions[k] then
            actions[k](value);
        end
    end

--[[
        case 'e':
            /* We ignore -e for compatibility.  Older versions specified the
             * command as the argument to -e.  Since the current version takes
             * the command as non-option arguments and we say that -e has no
             * arguments, this just works in the common case. */
            if (e_options++) {
                ovs_fatal(0, "-e or --execute may be speciifed only once");
            }
            break;

        case 'o':
            ovs_cmdl_print_options(long_options);
            exit(EXIT_SUCCESS);

        case 'T':
            time_alarm(atoi(optarg));
            break;

        case 'V':
            ovs_print_version(0, 0);
            exit(EXIT_SUCCESS);

        VLOG_OPTION_HANDLERS

        case '?':
            exit(EXIT_FAILURE);

]]
print("TARGET:", target)

    target = target or "ovs-vswitchd";

    return target;
end

local function connect_to_target(target)

    local socket_name = nil;

--if ffi.os ~= "Windows" then
    if (target[0] ~= string.byte('/')) then
        local pidfile_name = xasprintf("%s/%s.pid", ovs_rundir(), target);
        local pid = read_pidfile(pidfile_name);
        if (pid < 0) then
            ovs_fatal(-pid, "cannot read pidfile \"%s\"", pidfile_name);
        end
        ffi.C.free(pidfile_name);
        socket_name = xasprintf("%s/%s.%ld.ctl",
                                ovs_rundir(), target, ffi.cast("long int", pid));
--else
    -- On windows, if the 'target' contains ':', we make an assumption that
    -- it is an absolute path.
--    if ( not stringz.strchr(target, ':')) then
--        socket_name = xasprintf("%s/%s.ctl", ovs_rundir(), target);
--end
    else
        socket_name = xstrdup(target);
    end

    local clientp = ffi.new("struct jsonrpc *[1]");
    local err = unixctl_client_create(socket_name, clientp);
    local client = clientp[0];

    if (err ~= 0) then
        ovs_fatal(error, "cannot connect to \"%s\"", socket_name);
    end
    ffi.C.free(socket_name);

    return client;
end

--main();
--usage();
parse_command_line();

exit();


text:
from BTrees.OOBTree import OOBTree

import transaction
from ..zeo_conf_wrapper import ZEOConfWrapper

# Functions & classes =========================================================
class DatabaseHandler(object):
    """
    Define interfaces to the database, configuration and so on.

    Attributes:
        conf_path (str): Path to the ZEO client XML configuration.
        project_key (str): Project key, which is used to access ZEO.
        zeo (obj): :class:`.ZEOConfWrapper` database object.
    """
    def __init__(self, conf_path, project_key):
        self.conf_path = conf_path
        self.project_key = project_key

        self.zeo = None
        self._reload_zeo()

    def _reload_zeo(self):
        self.zeo = ZEOConfWrapper(
            conf_path=self.conf_path,
            project_key=self.project_key
        )

    def _get_key_or_create(self, key, obj_type=OOBTree):
        with transaction.manager:
            key_obj = self.zeo.get(key, None)

            if key_obj is None:
                key_obj = obj_type()
                self.zeo[key] = key_obj

            return key_obj


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace eRecycle.Pages
{
    public partial class Find : PhoneApplicationPage
    {
        public Find()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Navigate to Browser
            WebBrowserTask web = new WebBrowserTask();
            string tempCity="http://www.nokia.com/in-en/store-locator/?action=storeSearch&qt="+MyCity.Text+"&tags=Nokia_Recycling_Point&country=IN";
            web.Uri = new Uri(tempCity, UriKind.Absolute);
            web.Show();
        }
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';

class SearchResults extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      movies: [],
      currentPoster: `https://image.tmdb.org/t/p/w500${this.props.currentMovie.poster}`
    }
    // handle adding movies to queue from results display
    this.handleAddMovietoQueue = this.handleAddMovietoQueue.bind(this);
  }
  // buld func to add movie to queue
  handleAddMovietoQueue() {
    this.setState({movies: this.state.movies.push(this.props.currentMovie)});
  };
  componentDidMount(){
  console.log(this.state.currentPoster);
  console.log(this.props.currentMovie.poster);
  }
// render results with add button on page
  render() {
    return (

{this.props.currentMovie.value}

            <button onClick={this.handleAddMovietoQueue}>Add to queue</button>

{this.props.tagline}

{this.props.overview}

Length: {this.props.runtime}

Voting: {this.props.vote}

    );
  }
}

export default SearchResults;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Microeccrina iuli Maessen

### Remarks
null


text:
prov = $evm.root['service_template_provision_task']

unless prov
  $evm.log(:error, "miq_provision object not provided")
  exit(MIQ_STOP)
end

# Get status from input field status
status = $evm.inputs['status']

# Update Status Message
updated_message  = "Server [#{$evm.root['miq_server'].name}] "
updated_message += "Service [#{prov.destination.name}] "
updated_message += "Step [#{$evm.root['ae_state']}] "
updated_message += "Status [#{status}] "
updated_message += "Message [#{prov.message}] "
updated_message += "Current Retry Number [#{$evm.root['ae_state_retries']}]" if $evm.root['ae_result'] == 'retry'
prov.miq_request.user_message = updated_message
prov.message = status


text:
class Tachyon < Formula
  desc "Distributed storage system to enable data sharing across cluster frameworks"
  homepage "http://tachyon-project.org/"
  url "https://github.com/amplab/tachyon/releases/download/v0.6.4/tachyon-0.6.4-bin.tar.gz"
  sha256 "c105e2e984cc7139933e1d1debc4b393fe22ef33fb90776edc5be7148829b820"

  def install
    libexec.install %w[bin client conf core libexec]
    bin.write_exec_script Dir["#{libexec}/bin/*"]
    doc.install Dir["docs/*"]

    (etc/"tachyon").install libexec/"conf/tachyon-env.sh.template" => "tachyon-env.sh"
    ln_sf "#{etc}/tachyon/tachyon-env.sh", "#{libexec}/conf/tachyon-env.sh"
  end

  test do
    system bin/"tachyon", "version"
  end

  def caveats; <<-EOS.undent
    To configure tachyon, edit
      #{etc}/tacyon/tachyon-env.sh
    EOS
  end
end


text:
using Interpreter.Structs;
using System.Collections.Generic;
using System.Linq;

namespace Interpreter.Structs
{
    public class ResourceDB
    {
        public Dictionary<string, string[]> filesPerDirectory;
        public Dictionary<string, ResourceInfo> fileInfo;
        public List<Value> dataList;
        public string imageAtlasManifest;

        public ResourceDB(Dictionary<string, string[]> filesPerDirectory, Dictionary<string, ResourceInfo> fileInfo, List<Value> dataList, string imageAtlasManifest)
        {
            this.filesPerDirectory = filesPerDirectory;
            this.fileInfo = fileInfo;
            this.dataList = dataList;
            this.imageAtlasManifest = imageAtlasManifest;
        }
    }

}


text:
find . -name "*.pyc" -exec rm {} \;
rm db.sqlite3

python manage.py makemigrations
python manage.py migrate
python manage.py create_test_users
python manage.py create_test_data


text:
package appeng.api.parts;

import java.util.EnumSet;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public interface IPartRenderHelper {

    /**
     * sets the Render Helpers Block Bounds. 0.0 - 16.0 block coords.
     *
     * No complaints about the size, I like using pixels :P
     *
     * @param minX
     * @param minY
     * @param minZ
     * @param maxX
     * @param maxY
     * @param maxZ
     */
    void setBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ);

    /**
     * static renderer
     *
     * render a single face.
     *
     * @param x
     * @param y
     * @param z
     * @param ico
     * @param face
     * @param renderer
     */
    @SideOnly(Side.CLIENT)
    void renderFace(int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer);

    /**
     * static renderer
     *
     * render a box with a cut out box in the center.
     *
     * @param x
     * @param y
     * @param z
     * @param ico
     * @param face
     * @param edgeThickness
     * @param renderer
     */
    @SideOnly(Side.CLIENT)
    void renderFaceCutout(int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer);

    /**
     * static renderer
     *
     * render a block of specified bounds.
     *
     * @param x
     * @param y
     * @param z
     * @param renderer
     */
    @SideOnly(Side.CLIENT)
    void renderBlock(int x, int y, int z, RenderBlocks renderer);

    /**
     * render a single face in inventory renderer.
     *
     * @param IIcon
     * @param south
     * @param renderer
     */
    @SideOnly(Side.CLIENT)
    void renderInventoryFace(IIcon IIcon, ForgeDirection south, RenderBlocks renderer);

    /**
     * render a box in inventory renderer.
     *
     * @param renderer
     */
    @SideOnly(Side.CLIENT)
    void renderInventoryBox(RenderBlocks renderer);

    /**
     * inventory, and static renderer.
     *
     * set unique icons for each side of the block.
     *
     * @param Down
     * @param Up
     * @param North
     * @param South
     * @param West
     * @param East
     */
    void setTexture(IIcon Down, IIcon Up, IIcon North, IIcon South, IIcon West, IIcon East);

    /**
     * inventory, and static renderer.
     *
     * set all sides to a single IIcon.
     *
     * @param ico
     */
    void setTexture(IIcon ico);

    /**
     * configure the color multiplier for the inventory renderer.
     *
     * @param whiteVariant
     */
    void setInvColor(int whiteVariant);

    /**
     * @return the block used for rendering, might need it for some reason...
     */
    Block getBlock();

    /**
     * @return the east vector in world directions, rather then renderer
     */
    ForgeDirection getWorldX();

    /**
     * @return the up vector in world directions, rather then renderer.
     */
    ForgeDirection getWorldY();

    /**
     * @return the forward vector in world directions, rather then renderer.
     */
    ForgeDirection getWorldZ();

    /**
     * Pre-Calculates default lighting for the part, call this before using the render helper to render anything else to
     * get simplified, but faster lighting for more then one block.
     *
     * Only worth it if you render more then 1 block.
     */
    ISimplifiedBundle useSimpliedRendering(int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim);

    /**
     * disables, useSimpliedRendering.
     */
    void normalRendering();

    /**
     * render a block using the current renderer state.
     *
     * @param x
     * @param y
     * @param z
     * @param renderer
     */
    void renderBlockCurrentBounds(int x, int y, int z, RenderBlocks renderer);

    /**
     * allow you to enable your part to render during the alpha pass or the standard pass.
     *
     * @param pass
     */
    void renderForPass(int pass);

    /**
     * Set which faces to render, remember to set back to ALL when you are done.
     *
     * @param complementOf
     */
    void setFacesToRender(EnumSet<ForgeDirection> complementOf);

}


text:
package org.jetbrains.kotlin.idea.test;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.vfs.VfsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts;

public class ProjectDescriptorWithStdlibSources extends KotlinWithJdkAndRuntimeLightProjectDescriptor {
    @NotNull
    public static final ProjectDescriptorWithStdlibSources INSTANCE = new ProjectDescriptorWithStdlibSources();

    @Override
    public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model) {
        super.configureModule(module, model);

        Library library = model.getModuleLibraryTable().getLibraryByName(KotlinJdkAndLibraryProjectDescriptor.LIBRARY_NAME);
        assert library != null;
        Library.ModifiableModel modifiableModel = library.getModifiableModel();
        modifiableModel.addRoot(VfsUtil.getUrlForLibraryRoot(TestKotlinArtifacts.getKotlinStdlibSources()), OrderRootType.SOURCES);
        modifiableModel.commit();
    }
}