text:
import { ObservableInput, OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { mergeInternals } from './mergeInternals';

/**
 * Applies an accumulator function over the source Observable where the
 * accumulator function itself returns an Observable, then each intermediate
 * Observable returned is merged into the output Observable.
 *
 * It's like {@link scan}, but the Observables returned
 * by the accumulator are merged into the outer Observable.
 *
 * The first parameter of the `mergeScan` is an `accumulator` function which is
 * being called every time the source Observable emits a value. `mergeScan` will
 * subscribe to the value returned by the `accumulator` function and will emit
 * values to the subscriber emitted by inner Observable.
 *
 * The `accumulator` function is being called with three parameters passed to it:
 * `acc`, `value` and `index`. The `acc` parameter is used as the state parameter
 * whose value is initially set to the `seed` parameter (the second parameter
 * passed to the `mergeScan` operator).
 *
 * `mergeScan` internally keeps the value of the `acc` parameter: as long as the
 * source Observable emits without inner Observable emitting, the `acc` will be
 * set to `seed`. The next time the inner Observable emits a value, `mergeScan`
 * will internally remember it and it will be passed to the `accumulator`
 * function as `acc` parameter the next time source emits.
 *
 * The `value` parameter of the `accumulator` function is the value emitted by the
 * source Observable, while the `index` is a number which represent the order of the
 * current emission by the source Observable. It starts with 0.
 *
 * The last parameter to the `mergeScan` is the `concurrent` value which defaults
 * to Infinity. It represent the maximum number of inner Observable subscriptions
 * at a time.
 *
 * ## Example
 * Count the number of click events
 * ```ts
 * import { fromEvent, of } from 'rxjs';
 * import { mapTo, mergeScan } from 'rxjs/operators';
 *
 * const click$ = fromEvent(document, 'click');
 * const one$ = click$.pipe(mapTo(1));
 * const seed = 0;
 * const count$ = one$.pipe(
 *   mergeScan((acc, one) => of(acc + one), seed),
 * );
 * count$.subscribe(x => console.log(x));
 *
 * // Results:
 * // 1
 * // 2
 * // 3
 * // 4
 * // ...and so on for each click
 * ```
 *
 * @see {@link scan}
 * @see {@link switchScan}
 *
 * @param {function(acc: R, value: T): Observable<R>} accumulator
 * The accumulator function called on each source value.
 * @param seed The initial accumulation value.
 * @param {number} [concurrent=Infinity] Maximum number of
 * input Observables being subscribed to concurrently.
 * @return A function that returns an Observable of the accumulated values.
 */
export function mergeScan<T, R>(
  accumulator: (acc: R, value: T, index: number) => ObservableInput<R>,
  seed: R,
  concurrent = Infinity
): OperatorFunction<T, R> {
  return operate((source, subscriber) => {
    // The accumulated state.
    let state = seed;

    return mergeInternals(
      source,
      subscriber,
      (value, index) => accumulator(state, value, index),
      concurrent,
      (value) => {
        state = value;
      },
      false,
      undefined,
      () => (state = null!)
    );
  });
}


text:
#include "includes.h"

#ifdef USE_SHARED_MMAP

extern int DEBUGLEVEL;

#define SMB_SHM_MAGIC 0x53484100
/* = "SHM" in hex */

#define SMB_SHM_VERSION 2

/* we need world read for smbstatus to function correctly */
#ifdef SECURE_SHARE_MODES
#define SHM_FILE_MODE 0600
#else
#define SHM_FILE_MODE 0644
#endif

#define SHMEM_HASH_SIZE 13

/* WARNING : offsets are used because mmap() does not guarantee that all processes have the
   shared memory mapped to the same address */

struct SmbShmHeader
{
   int smb_shm_magic;
   int smb_shm_version;
   int total_size;	/* in bytes */
   BOOL consistent;
   int first_free_off;
   int userdef_off;    /* a userdefined offset. can be used to store root of tree or list */
   struct {		/* a cell is a range of bytes of sizeof(struct SmbShmBlockDesc) size */
      int cells_free;
      int cells_used;
      int cells_system; /* number of cells used as allocated block descriptors */
   } statistics;
};

#define SMB_SHM_NOT_FREE_OFF (-1)
struct SmbShmBlockDesc
{
   int next;	/* offset of next block in the free list or SMB_SHM_NOT_FREE_OFF when block in use  */
   int          size;   /* user size in BlockDescSize units */
};

#define	EOList_Addr	(struct SmbShmBlockDesc *)( 0 )
#define EOList_Off      0

#define	CellSize	sizeof(struct SmbShmBlockDesc)

/* HeaderSize aligned on 8 byte boundary */
#define	AlignedHeaderSize  	((sizeof(struct SmbShmHeader)+7) & ~7)

static int  smb_shm_fd = -1;
static pstring smb_shm_processreg_name = "";

static struct SmbShmHeader *smb_shm_header_p = (struct SmbShmHeader *)0;
static int smb_shm_times_locked = 0;

static BOOL smb_shm_initialize_called = False;

static int read_only;

static BOOL smb_shm_global_lock(void)
{
   if (smb_shm_fd < 0)
   {
      DEBUG(0,("ERROR smb_shm_global_lock : bad smb_shm_fd (%d)\n",smb_shm_fd));
      return False;
   }

   smb_shm_times_locked++;

   if(smb_shm_times_locked > 1)
   {
      DEBUG(5,("smb_shm_global_lock : locked %d times\n",smb_shm_times_locked));
      return True;
   }

   if (read_only)
	   return True;

   /* Do an exclusive wait lock on the first byte of the file */
   if (fcntl_lock(smb_shm_fd, SMB_F_SETLKW, 0, 1, F_WRLCK) == False)
   {
      DEBUG(0,("ERROR smb_shm_global_lock : fcntl_lock failed with code %s\n",strerror(errno)));
      smb_shm_times_locked--;
      return False;
   }

   return True;

}

static BOOL smb_shm_global_unlock(void)
{
   if (smb_shm_fd < 0)
   {
      DEBUG(0,("ERROR smb_shm_global_unlock : bad smb_shm_fd (%d)\n",smb_shm_fd));
      return False;
   }

   if(smb_shm_times_locked == 0)
   {
      DEBUG(0,("ERROR smb_shm_global_unlock : shmem not locked\n"));
      return False;
   }

   smb_shm_times_locked--;

   if(smb_shm_times_locked > 0)
   {
      DEBUG(5,("smb_shm_global_unlock : still locked %d times\n",smb_shm_times_locked));
      return True;
   }

   if (read_only)
	   return True;

   /* Do a wait unlock on the first byte of the file */
   if (fcntl_lock(smb_shm_fd, SMB_F_SETLKW, 0, 1, F_UNLCK) == False)
   {
      DEBUG(0,("ERROR smb_shm_global_unlock : fcntl_lock failed with code %s\n",strerror(errno)));
      smb_shm_times_locked++;
      return False;
   }

   return True;

}

static void *smb_shm_offset2addr(int offset)
{
   if (offset == 0 )
      return (void *)(0);

   if (!smb_shm_header_p)
      return (void *)(0);

   return (void *)((char *)smb_shm_header_p + offset );
}

static int smb_shm_addr2offset(void *addr)
{
   if (!addr)
      return 0;

   if (!smb_shm_header_p)
      return 0;

   return (int)((char *)addr - (char *)smb_shm_header_p);
}

static int smb_shm_alloc(int size)
{
   unsigned num_cells ;
   struct SmbShmBlockDesc *scanner_p;
   struct SmbShmBlockDesc *prev_p;
   struct SmbShmBlockDesc *new_p;
   int result_offset;

   if( !smb_shm_header_p )
   {
      /* not mapped yet */
      DEBUG(0,("ERROR smb_shm_alloc : shmem not mapped\n"));
      return 0;
   }

   smb_shm_global_lock();

   if( !smb_shm_header_p->consistent)
   {
      DEBUG(0,("ERROR smb_shm_alloc : shmem not consistent\n"));
      smb_shm_global_unlock();
      return 0;
   }

   /* calculate	the number of cells */
   num_cells = (size + CellSize -1) / CellSize;

   /* set start	of scan */
   prev_p = (struct SmbShmBlockDesc *)smb_shm_offset2addr(smb_shm_header_p->first_free_off);
   scanner_p =	prev_p ;

   /* scan the free list to find a matching free space */
   while ( ( scanner_p != EOList_Addr ) && ( scanner_p->size < num_cells ) )
   {
      prev_p = scanner_p;
      scanner_p = (struct SmbShmBlockDesc *)smb_shm_offset2addr(scanner_p->next);
   }

   /* at this point scanner point to a block header or to the end of the list */
   if ( scanner_p == EOList_Addr )
   {
      DEBUG(0,("ERROR smb_shm_alloc : alloc of %d bytes failed, no free space found\n",size));
      smb_shm_global_unlock();
      return (0);
   }

   /* going to modify shared mem */
   smb_shm_header_p->consistent = False;

   /* if we found a good one : scanner == the good one */
   if ( scanner_p->size <= num_cells + 2 )
   {
      /* there is no use in making a new one, it will be too small anyway
      *	 we will link out scanner
      */
      if ( prev_p == scanner_p )
      {
	 smb_shm_header_p->first_free_off = scanner_p->next ;
      }
      else
      {
	 prev_p->next = scanner_p->next ;
      }
      smb_shm_header_p->statistics.cells_free -= scanner_p->size;
      smb_shm_header_p->statistics.cells_used += scanner_p->size;
   }
   else
   {
      /* Make a new one */
      new_p = scanner_p + 1 + num_cells;
      new_p->size = scanner_p->size - num_cells - 1;
      new_p->next = scanner_p->next;
      scanner_p->size = num_cells;
      scanner_p->next = smb_shm_addr2offset(new_p);

      if ( prev_p	!= scanner_p )
      {
	 prev_p->next	   = smb_shm_addr2offset(new_p)  ;
      }
      else
      {
	 smb_shm_header_p->first_free_off = smb_shm_addr2offset(new_p)  ;
      }
      smb_shm_header_p->statistics.cells_free -= num_cells+1;
      smb_shm_header_p->statistics.cells_used += num_cells;
      smb_shm_header_p->statistics.cells_system += 1;
   }

   result_offset = smb_shm_addr2offset( &(scanner_p[1]) );
   scanner_p->next =	SMB_SHM_NOT_FREE_OFF ;

   /* end modification of shared mem */
   smb_shm_header_p->consistent = True;

   DEBUG(6,("smb_shm_alloc : request for %d bytes, allocated %d bytes at offset %d\n",size,scanner_p->size*CellSize,result_offset ));

   smb_shm_global_unlock();
   return ( result_offset );
}

/*
 * Function to create the hash table for the share mode entries. Called
 * when smb shared memory is global locked.
 */
static BOOL smb_shm_create_hash_table( unsigned int size )
{
  size *= sizeof(int);

  smb_shm_global_lock();
  smb_shm_header_p->userdef_off = smb_shm_alloc( size );

  if(smb_shm_header_p->userdef_off == 0)
    {
      DEBUG(0,("smb_shm_create_hash_table: Failed to create hash table of size %d\n",size));
      smb_shm_global_unlock();
      return False;
    }

  /* Clear hash buckets. */
  memset( smb_shm_offset2addr(smb_shm_header_p->userdef_off), '\0', size);
  smb_shm_global_unlock();
  return True;
}

static BOOL smb_shm_register_process(char *processreg_file, pid_t pid, BOOL *other_processes)
{
  int smb_shm_processes_fd = -1;
  int nb_read;
  pid_t other_pid;
  SMB_OFF_T seek_back = -((SMB_OFF_T)sizeof(other_pid));
  SMB_OFF_T free_slot = -1;
  SMB_OFF_T erased_slot;

  smb_shm_processes_fd = sys_open(processreg_file,
                              read_only?O_RDONLY:(O_RDWR|O_CREAT),
                              SHM_FILE_MODE);

  if ( smb_shm_processes_fd < 0 )
  {
     DEBUG(0, ("ERROR smb_shm_register_process : processreg_file \
open failed with code %s\n",strerror(errno)));
     return False;
  }

  *other_processes = False;

  while ((nb_read = read(smb_shm_processes_fd, &other_pid, sizeof(other_pid))) > 0)
  {
    if(other_pid)
    {
      if(process_exists(other_pid))
        *other_processes = True;
      else
      {
        /* erase old pid */
        DEBUG(5,("smb_shm_register_process : erasing stale record \
for pid %d (seek_back = %.0f)\n", (int)other_pid, (double)seek_back));
        other_pid = (pid_t)0;
        if((erased_slot = sys_lseek(smb_shm_processes_fd,
                                    seek_back, SEEK_CUR)) == -1)
        {
          DEBUG(0, ("ERROR smb_shm_register_process : sys_lseek failed \
with error %s\n", strerror(errno)));
          close(smb_shm_processes_fd);
          return False;
        }

        if(write(smb_shm_processes_fd, &other_pid, sizeof(other_pid)) == -1)
        {
           DEBUG(0, ("ERROR smb_shm_register_process : write failed \
with error %s\n", strerror(errno)));
           close(smb_shm_processes_fd);
           return False;
        }

        if(free_slot < 0)
          free_slot = erased_slot;
      }
    }
    else
    {
      if(free_slot < 0)
      {
        if((free_slot = sys_lseek(smb_shm_processes_fd,
                                  seek_back, SEEK_CUR))==-1)
        {
          DEBUG(0, ("ERROR smb_shm_register_process : sys_lseek \
failed with error %s\n", strerror(errno)));
          close(smb_shm_processes_fd);
          return False;
        }
      } /* end if free_slot */
    } /* end else */
  } /* end if other_pid */

  if (nb_read < 0)
  {
    DEBUG(0,("ERROR smb_shm_register_process : processreg_file read \
failed with code %s\n",strerror(errno)));
    close(smb_shm_processes_fd);
    return False;
  }

  if(free_slot < 0)
  {
    if((free_slot = sys_lseek(smb_shm_processes_fd, 0, SEEK_END)) == -1)
    {
      DEBUG(0,("ERROR smb_shm_register_process : sys_lseek failed with code %s\n",strerror(errno)));
      close(smb_shm_processes_fd);
      return False;
    }
  }

  DEBUG(5,("smb_shm_register_process : writing record for pid %d at offset %.0f\n",
         (int)pid, (double)free_slot));

  if(sys_lseek(smb_shm_processes_fd, free_slot, SEEK_SET) == -1)
  {
    DEBUG(0,("ERROR smb_shm_register_process : sys_lseek failed with code %s\n",strerror(errno)));
    close(smb_shm_processes_fd);
    return False;
  }

  if(write(smb_shm_processes_fd, &pid, sizeof(pid)) == -1)
  {
    DEBUG(0,("ERROR smb_shm_register_process : processreg_file write failed with code %s\n",strerror(errno)));
    close(smb_shm_processes_fd);
    return False;
  }

  close(smb_shm_processes_fd);

  return True;
}

static BOOL smb_shm_unregister_process(char *processreg_file, pid_t pid)
{
   int smb_shm_processes_fd = -1;
   int nb_read;
   pid_t other_pid;
   SMB_OFF_T seek_back = -((SMB_OFF_T)sizeof(other_pid));
   BOOL found = False;

   smb_shm_processes_fd = sys_open(processreg_file, O_RDWR, 0);
   if ( smb_shm_processes_fd < 0 )
   {
      DEBUG(0,("ERROR smb_shm_unregister_process : processreg_file open failed with code %s\n",strerror(errno)));
      return False;
   }

   while ((nb_read = read(smb_shm_processes_fd, &other_pid, sizeof(other_pid))) > 0)
   {
      DEBUG(5,("smb_shm_unregister_process : read record for pid %d\n",(int)other_pid));
      if(other_pid == pid)
      {
        /* erase pid */
        DEBUG(5,("smb_shm_unregister_process : erasing record for pid %d (seek_val = %.0f)\n",
                     (int)other_pid, (double)seek_back));
        other_pid = (pid_t)0;
        if(sys_lseek(smb_shm_processes_fd, seek_back, SEEK_CUR) == -1)
        {
          DEBUG(0,("ERROR smb_shm_unregister_process : processreg_file sys_lseek failed with code %s\n",strerror(errno)));
          close(smb_shm_processes_fd);
          return False;
        }
        if(write(smb_shm_processes_fd, &other_pid, sizeof(other_pid)) < 0)
        {
          DEBUG(0,("ERROR smb_shm_unregister_process : processreg_file write failed with code %s\n",strerror(errno)));
          close(smb_shm_processes_fd);
          return False;
        }

        found = True;
        break;
      }
   }
   if (nb_read < 0)
   {
      DEBUG(0,("ERROR smb_shm_unregister_process : processreg_file read failed with code %s\n",strerror(errno)));
      close(smb_shm_processes_fd);
      return False;
   }

   if(!found)
   {
      DEBUG(0,("ERROR smb_shm_unregister_process : couldn't find pid %d in file %s\n",
            (int)pid,processreg_file));
      close(smb_shm_processes_fd);
      return False;
   }

   close(smb_shm_processes_fd);

   return True;
}

static BOOL smb_shm_validate_header(int size)
{
   if( !smb_shm_header_p )
   {
      /* not mapped yet */
      DEBUG(0,("ERROR smb_shm_validate_header : shmem not mapped\n"));
      return False;
   }

   if(smb_shm_header_p->smb_shm_magic != SMB_SHM_MAGIC)
   {
      DEBUG(0,("ERROR smb_shm_validate_header : bad magic\n"));
      return False;
   }
   if(smb_shm_header_p->smb_shm_version != SMB_SHM_VERSION)
   {
      DEBUG(0,("ERROR smb_shm_validate_header : bad version %X\n",smb_shm_header_p->smb_shm_version));
      return False;
   }

   if(smb_shm_header_p->total_size != size)
   {
      DEBUG(0,("ERROR smb_shm_validate_header : shmem size mismatch (old = %d, new = %d)\n",smb_shm_header_p->total_size,size));
      return False;
   }

   if(!smb_shm_header_p->consistent)
   {
      DEBUG(0,("ERROR smb_shm_validate_header : shmem not consistent\n"));
      return False;
   }
   return True;
}

static BOOL smb_shm_initialize(int size)
{
   struct SmbShmBlockDesc * first_free_block_p;

   DEBUG(5,("smb_shm_initialize : initializing shmem file of size %d\n",size));

   if( !smb_shm_header_p )
   {
      /* not mapped yet */
      DEBUG(0,("ERROR smb_shm_initialize : shmem not mapped\n"));
      return False;
   }

   smb_shm_header_p->smb_shm_magic = SMB_SHM_MAGIC;
   smb_shm_header_p->smb_shm_version = SMB_SHM_VERSION;
   smb_shm_header_p->total_size = size;
   smb_shm_header_p->first_free_off = AlignedHeaderSize;
   smb_shm_header_p->userdef_off = 0;

   first_free_block_p = (struct SmbShmBlockDesc *)smb_shm_offset2addr(smb_shm_header_p->first_free_off);
   first_free_block_p->next = EOList_Off;
   first_free_block_p->size = ( size - AlignedHeaderSize - CellSize ) / CellSize ;

   smb_shm_header_p->statistics.cells_free = first_free_block_p->size;
   smb_shm_header_p->statistics.cells_used = 0;
   smb_shm_header_p->statistics.cells_system = 1;

   smb_shm_header_p->consistent = True;

   smb_shm_initialize_called = True;

   return True;
}

static void smb_shm_solve_neighbors(struct SmbShmBlockDesc *head_p )
{
   struct SmbShmBlockDesc *next_p;

   /* Check if head_p and head_p->next are neighbors and if so join them */
   if ( head_p == EOList_Addr ) return ;
   if ( head_p->next == EOList_Off ) return ;

   next_p = (struct SmbShmBlockDesc *)smb_shm_offset2addr(head_p->next);
   if ( ( head_p + head_p->size + 1 ) == next_p)
   {
      head_p->size += next_p->size +1 ;	/* adapt size */
      head_p->next = next_p->next	  ; /* link out */

      smb_shm_header_p->statistics.cells_free += 1;
      smb_shm_header_p->statistics.cells_system -= 1;
   }
}

static BOOL smb_shm_close( void )
{

   if(smb_shm_initialize_called == False)
     return True;

   DEBUG(5,("smb_shm_close\n"));
   if(smb_shm_times_locked > 0)
      DEBUG(0,("WARNING smb_shm_close : shmem was still locked %d times\n",smb_shm_times_locked));;
   if ((smb_shm_header_p != NULL) &&
              (munmap((caddr_t)smb_shm_header_p, smb_shm_header_p->total_size) < 0))
   {
      DEBUG(0,("ERROR smb_shm_close : munmap failed with code %s\n",strerror(errno)));
   }

   smb_shm_global_lock();
   DEBUG(5,("calling smb_shm_unregister_process(%s, %d)\n",
         smb_shm_processreg_name, (int)getpid()));
   smb_shm_unregister_process(smb_shm_processreg_name, getpid());
   smb_shm_global_unlock();

   close(smb_shm_fd);

   smb_shm_fd = -1;
   smb_shm_processreg_name[0] = '\0';

   smb_shm_header_p = (struct SmbShmHeader *)0;
   smb_shm_times_locked = 0;

   return True;
}

static BOOL smb_shm_free(int offset)
{
   struct SmbShmBlockDesc *header_p  ; /*	pointer	to header of block to free */
   struct SmbShmBlockDesc *scanner_p ; /*	used to	scan the list			   */
   struct SmbShmBlockDesc *prev_p	   ; /*	holds previous in the list		   */

   if( !smb_shm_header_p )
   {
      /* not mapped yet */
      DEBUG(0,("ERROR smb_shm_free : shmem not mapped\n"));
      return False;
   }

   smb_shm_global_lock();

   if( !smb_shm_header_p->consistent)
   {
      DEBUG(0,("ERROR smb_shm_free : shmem not consistent\n"));
      smb_shm_global_unlock();
      return False;
   }

   header_p = (	(struct SmbShmBlockDesc *)smb_shm_offset2addr(offset) - 1); /* make pointer to header of block */

   if (header_p->next != SMB_SHM_NOT_FREE_OFF)
   {
      DEBUG(0,("ERROR smb_shm_free : bad offset (%d)\n",offset));
      smb_shm_global_unlock();
      return False;
   }

   /* find a place in the free_list to put the header in */

   /* set scanner and previous pointer to start of list */
   prev_p = (struct SmbShmBlockDesc *)smb_shm_offset2addr(smb_shm_header_p->first_free_off);
   scanner_p = prev_p ;

   while ( ( scanner_p != EOList_Addr) && (scanner_p < header_p) ) /* while we didn't scan past its position */
   {
      prev_p = scanner_p ;
      scanner_p = (struct SmbShmBlockDesc *)smb_shm_offset2addr(scanner_p->next);
   }

   smb_shm_header_p->consistent = False;

   DEBUG(6,("smb_shm_free : freeing %d bytes at offset %d\n",header_p->size*CellSize,offset));

   /* zero the area being freed - this allows us to find bugs faster */
   memset(smb_shm_offset2addr(offset), 0, header_p->size*CellSize);

   if ( scanner_p == prev_p )
   {
      smb_shm_header_p->statistics.cells_free += header_p->size;
      smb_shm_header_p->statistics.cells_used -= header_p->size;

      /* we must free it at the beginning of the list */
      smb_shm_header_p->first_free_off = smb_shm_addr2offset(header_p);						 /*	set	the free_list_pointer to this block_header */

      /* scanner is the one that was first in the list */
      header_p->next = smb_shm_addr2offset(scanner_p);
      smb_shm_solve_neighbors( header_p ); /* if neighbors then link them */

      smb_shm_header_p->consistent = True;
      smb_shm_global_unlock();
      return True;
   }
   else
   {
      smb_shm_header_p->statistics.cells_free += header_p->size;
      smb_shm_header_p->statistics.cells_used -= header_p->size;

      prev_p->next = smb_shm_addr2offset(header_p);
      header_p->next = smb_shm_addr2offset(scanner_p);
      smb_shm_solve_neighbors(header_p) ;
      smb_shm_solve_neighbors(prev_p) ;

      smb_shm_header_p->consistent = True;
      smb_shm_global_unlock();
      return True;
   }
}

static int smb_shm_get_userdef_off(void)
{
   if (!smb_shm_header_p)
      return 0;
   else
      return smb_shm_header_p->userdef_off;
}

/*******************************************************************
  Lock a particular hash bucket entry.
  ******************************************************************/
static BOOL smb_shm_lock_hash_entry( unsigned int entry)
{
  int start = (smb_shm_header_p->userdef_off + (entry * sizeof(int)));

  if (smb_shm_fd < 0)
    {
      DEBUG(0,("ERROR smb_shm_lock_hash_entry : bad smb_shm_fd (%d)\n",smb_shm_fd));
      return False;
    }

  if (read_only)
	  return True;

  /* Do an exclusive wait lock on the 4 byte region mapping into this entry  */
  if (fcntl_lock(smb_shm_fd, SMB_F_SETLKW, start, sizeof(int), F_WRLCK) == False)
    {
      DEBUG(0,("ERROR smb_shm_lock_hash_entry : fcntl_lock failed with code %s\n",strerror(errno)));
      return False;
    }

  DEBUG(9,("smb_shm_lock_hash_entry: locked hash bucket %d\n", entry));
  return True;
}

/*******************************************************************
  Unlock a particular hash bucket entry.
  ******************************************************************/
static BOOL smb_shm_unlock_hash_entry( unsigned int entry )
{
  int start = (smb_shm_header_p->userdef_off + (entry * sizeof(int)));

  if (smb_shm_fd < 0)
    {
      DEBUG(0,("ERROR smb_shm_unlock_hash_entry : bad smb_shm_fd (%d)\n",smb_shm_fd));
      return False;
    }

  if (read_only)
	  return True;

  /* Do a wait lock on the 4 byte region mapping into this entry  */
  if (fcntl_lock(smb_shm_fd, SMB_F_SETLKW, start, sizeof(int), F_UNLCK) == False)
    {
      DEBUG(0,("ERROR smb_shm_unlock_hash_entry : fcntl_lock failed with code %s\n",strerror(errno)));
      return False;
    }

  DEBUG(9,("smb_shm_unlock_hash_entry: unlocked hash bucket %d\n", entry));
  return True;
}

/*******************************************************************
  Gather statistics on shared memory usage.
  ******************************************************************/
static BOOL smb_shm_get_usage(int *bytes_free,
		   int *bytes_used,
		   int *bytes_overhead)
{
   if( !smb_shm_header_p )
   {
      /* not mapped yet */
      DEBUG(0,("ERROR smb_shm_free : shmem not mapped\n"));
      return False;
   }
   *bytes_free = smb_shm_header_p->statistics.cells_free * CellSize;
   *bytes_used = smb_shm_header_p->statistics.cells_used * CellSize;
   *bytes_overhead = smb_shm_header_p->statistics.cells_system * CellSize + AlignedHeaderSize;

   return True;
}

/*******************************************************************
hash a number into a hash_entry
  ******************************************************************/
static unsigned smb_shm_hash_size(void)
{
	return SHMEM_HASH_SIZE;
}

static struct shmem_ops shmops = {
	smb_shm_close,
	smb_shm_alloc,
	smb_shm_free,
	smb_shm_get_userdef_off,
	smb_shm_offset2addr,
	smb_shm_addr2offset,
	smb_shm_lock_hash_entry,
	smb_shm_unlock_hash_entry,
	smb_shm_get_usage,
	smb_shm_hash_size,
};

/*******************************************************************
  open the shared memory
  ******************************************************************/
struct shmem_ops *smb_shm_open(int ronly)
{
  pstring file_name;
  SMB_OFF_T filesize;
  BOOL created_new = False;
  BOOL other_processes = True;
  SMB_OFF_T size = (SMB_OFF_T)lp_shmem_size();

  read_only = ronly;

  pstrcpy(file_name,lp_lockdir());
  if (!directory_exist(file_name,NULL)) {
    if (read_only)
      return NULL;
    mkdir(file_name,0755);
  }
  trim_string(file_name,"","/");
  if (!*file_name)
    return(False);
  pstrcat(file_name, "/SHARE_MEM_FILE");

  DEBUG(5,("smb_shm_open : using shmem file %s to be of size %.0f\n",
        file_name,(double)size));

  smb_shm_fd = sys_open(file_name, read_only?O_RDONLY:(O_RDWR|O_CREAT),
                    SHM_FILE_MODE);

  if ( smb_shm_fd < 0 )
  {
    DEBUG(0,("ERROR smb_shm_open : open failed with code %s\n",strerror(errno)));
    return NULL;
  }

  if (!smb_shm_global_lock())
  {
    DEBUG(0,("ERROR smb_shm_open : can't do smb_shm_global_lock\n"));
    return NULL;
  }

  if( (filesize = sys_lseek(smb_shm_fd, 0, SEEK_END)) == -1)
  {
    DEBUG(0,("ERROR smb_shm_open : sys_lseek failed with code %s\n",
          strerror(errno)));
    smb_shm_global_unlock();
    close(smb_shm_fd);
    return NULL;
  }

  /*
   * Return the file offset to 0 to save on later seeks.
   */
  if(sys_lseek(smb_shm_fd,0,SEEK_SET) == -1)
  {
    DEBUG(0,("ERROR smb_shm_open : sys_lseek failed with code %s\n",
          strerror(errno)));
    smb_shm_global_unlock();
    close(smb_shm_fd);
    return NULL;
  }

  if (filesize == 0)
  {
    /*
     * We just created a new one.
     */
    created_new = True;
  }

  /*
   * To find out if some other process is already mapping the file,
   * we use a registration file containing the processids of the file
   * mapping processes.
   */

  /* construct processreg file name */
  pstrcpy(smb_shm_processreg_name, file_name);
  pstrcat(smb_shm_processreg_name, ".processes");

  if (!read_only && !smb_shm_register_process(smb_shm_processreg_name,
                                              getpid(), &other_processes))
  {
    smb_shm_global_unlock();
    close(smb_shm_fd);
    return NULL;
  }

  if (!read_only && (created_new || !other_processes))
  {
    /* we just created a new one, or are the first opener, lets set it size */
    if( sys_ftruncate(smb_shm_fd, size) <0)
    {
      DEBUG(0,("ERROR smb_shm_open : ftruncate failed with code %s\n",
            strerror(errno)));
      smb_shm_unregister_process(smb_shm_processreg_name, getpid());
      smb_shm_global_unlock();
      close(smb_shm_fd);
      return NULL;
    }

    /* paranoia */
    if(sys_lseek(smb_shm_fd,0,SEEK_SET) == -1)
    {
      DEBUG(0,("ERROR smb_shm_open : sys_lseek failed with code %s\n",
            strerror(errno)));
      smb_shm_unregister_process(smb_shm_processreg_name, getpid());
      smb_shm_global_unlock();
      close(smb_shm_fd);
      return NULL;
    }

    filesize = size;
  }

  if (size != filesize )
  {
    /* the existing file has a different size and we are not the first opener.
      Since another process is still using it, we will use the file size */
    DEBUG(0,("WARNING smb_shm_open : filesize (%.0f) != expected \
size (%.0f), using filesize\n", (double)filesize, (double)size));

    size = filesize;
  }

  smb_shm_header_p = (struct SmbShmHeader *)sys_mmap(NULL, size,
                               read_only?PROT_READ: (PROT_READ | PROT_WRITE),
                               MAP_FILE | MAP_SHARED, smb_shm_fd, (SMB_OFF_T)0);

  /*
   * WARNING, smb_shm_header_p can be different for different
   * processes mapping the same file !
   */
  if (smb_shm_header_p  == (struct SmbShmHeader *)(-1))
  {
    DEBUG(0,("ERROR smb_shm_open : mmap failed with code %s\n",strerror(errno)));
    smb_shm_unregister_process(smb_shm_processreg_name, getpid());
    smb_shm_global_unlock();
    close(smb_shm_fd);
    return NULL;
  }

  if (!read_only && (created_new || !other_processes))
  {
    smb_shm_initialize(size);
    /* Create the hash buckets for the share file entries. */
    smb_shm_create_hash_table(SHMEM_HASH_SIZE);
  }
  else if (!smb_shm_validate_header(size) )
  {
    /* existing file is corrupt, samba admin should remove it by hand */
    DEBUG(0,("ERROR smb_shm_open : corrupt shared mem file, remove it manually\n"));
    munmap((caddr_t)smb_shm_header_p, size);
    smb_shm_unregister_process(smb_shm_processreg_name, getpid());
    smb_shm_global_unlock();
    close(smb_shm_fd);
    return NULL;
  }

  smb_shm_global_unlock();
  return &shmops;
}

#else /* HAVE_SHARED_MMAP */
 int shmem_dummy_procedure(void)
{return 0;}
#endif /* HAVE_SHARED_MMAP */

redpajama_set_name: RedPajamaGithub


text:
using namespace Polycode;

class PolycodeTemplateApp : public EventHandler {
public:
    PolycodeTemplateApp(PolycodeView *view);
    ~PolycodeTemplateApp();

    void handleEvent(Event *event);

    bool Update();

private:

    Sound *bgSound;

    Sound *sound1;
    Sound *sound2;
    Sound *sound3;

    ScenePrimitive *test;
    Scene *scene;

    Core *core;
    Vector3 rot;
    Number running;
    SceneLabel* fps;

    Scene* game;
    ScenePrimitive* box;
    UIButton* btn;
};


text:
package wdl.transforms.base.wdlom2wom.graph

import cats.syntax.apply._
import cats.syntax.validated._
import common.validation.ErrorOr.{ErrorOr, _}
import wdl.model.draft3.graph.expression.WomTypeMaker.ops._
import wdl.model.draft3.graph.expression.WomExpressionMaker.ops._
import wdl.transforms.base.linking.typemakers._
import wdl.transforms.base.linking.expression._
import wdl.model.draft3.elements._
import wdl.model.draft3.graph.expression.{FileEvaluator, TypeEvaluator, ValueEvaluator}
import wdl.model.draft3.graph.{ExpressionValueConsumer, GeneratedValueHandle, UnlinkedConsumedValueHook}
import wom.callable.Callable
import wom.expression.WomExpression
import wom.graph.GraphNodePort.OutputPort
import wom.graph._
import wom.graph.expression.ExposedExpressionNode
import wom.types.WomType
import wdl.transforms.base.wdlom2wdl.WdlWriter.ops._
import wdl.transforms.base.wdlom2wdl.WdlWriterImpl._

object WorkflowGraphElementToGraphNode {
  def convert(a: GraphNodeMakerInputs)
             (implicit expressionValueConsumer: ExpressionValueConsumer[ExpressionElement],
              fileEvaluator: FileEvaluator[ExpressionElement],
              typeEvaluator: TypeEvaluator[ExpressionElement],
              valueEvaluator: ValueEvaluator[ExpressionElement]): ErrorOr[Set[GraphNode]] = a.node match {
    case ie: InputDeclarationElement =>
      val inputNodeMakerInputs = GraphInputNodeMakerInputs(ie, a.linkableValues, a.linkablePorts, a.availableTypeAliases, a.workflowName)
      InputDeclarationElementToGraphNode.convert(inputNodeMakerInputs)

    case DeclarationElement(typeElement, name, Some(expr)) =>
      val womExprValidation: ErrorOr[WomExpression] = expr.makeWomExpression(a.availableTypeAliases, a.linkableValues)
      val womTypeValidation: ErrorOr[WomType] = typeElement.determineWomType(a.availableTypeAliases)

      val result = (womExprValidation, womTypeValidation) flatMapN { (womExpr, womType) =>
        val correctType: ErrorOr[Unit] = validateAssignmentType(womExpr, womType)

        val graphNode: ErrorOr[Set[GraphNode]] = a.node match {
          case _: InputDeclarationElement =>
            Set[GraphNode](OptionalGraphInputNodeWithDefault.apply(WomIdentifier(name), womType, womExpr, name)).validNel
          case _: IntermediateValueDeclarationElement =>
            ExposedExpressionNode.fromInputMapping(WomIdentifier(name), womExpr, womType, a.linkablePorts) map { Set(_) }
          case _: OutputDeclarationElement =>
            ExpressionBasedGraphOutputNode.fromInputMapping(WomIdentifier(name, s"${a.workflowName}.$name"), womExpr, womType, a.linkablePorts) map {Set(_)}
        }

        (correctType, graphNode) mapN { (_, gn) => gn }
      }
      result.contextualizeErrors(s"process declaration '${typeElement.toWdlV1} $name = ${expr.toWdlV1}'")

    case se: ScatterElement =>
      val scatterMakerInputs = ScatterNodeMakerInputs(se, a.upstreamCalls, a.linkableValues, a.linkablePorts, a.availableTypeAliases, a.workflowName, a.insideAScatter, a.convertNestedScatterToSubworkflow, a.allowNestedInputs, a.callables)
      ScatterElementToGraphNode.convert(scatterMakerInputs)

    case ie: IfElement =>
      val ifMakerInputs = ConditionalNodeMakerInputs(ie, a.upstreamCalls, a.linkableValues, a.linkablePorts, a.availableTypeAliases, a.workflowName, a.insideAScatter, a.convertNestedScatterToSubworkflow, a.allowNestedInputs, a.callables)
      IfElementToGraphNode.convert(ifMakerInputs)

    case ce: CallElement =>
      val callNodeMakerInputs = CallNodeMakerInputs(ce, a.upstreamCalls, a.linkableValues, a.linkablePorts, a.availableTypeAliases, a.workflowName, a.insideAScatter, a.allowNestedInputs, a.callables)
      CallElementToGraphNode.convert(callNodeMakerInputs)
  }

  def validateAssignmentType(womExpr: WomExpression, womType: WomType): ErrorOr[Unit] = {
    // NB: WdlomWomExpressions don't actually use the inputTypes argument, they already know their type:
    val exprType: ErrorOr[WomType] = womExpr.evaluateType(inputTypes = Map.empty)
    val correctType: ErrorOr[Unit] = exprType.flatMap {
      case goodType if womType.isCoerceableFrom(goodType) => ().validNel
      case badType => s"Cannot coerce expression of type '${badType.stableName}' to '${womType.stableName}'".invalidNel
    }
    correctType
  }
}

final case class GraphNodeMakerInputs(node: WorkflowGraphElement,
                                      upstreamCalls: Map[String, CallNode],
                                      linkableValues: Map[UnlinkedConsumedValueHook, GeneratedValueHandle],
                                      linkablePorts: Map[String, OutputPort],
                                      availableTypeAliases: Map[String, WomType],
                                      workflowName: String,
                                      insideAScatter: Boolean,
                                      convertNestedScatterToSubworkflow : Boolean,
                                      allowNestedInputs: Boolean,
                                      callables: Map[String, Callable])


text:
<?php

namespace phpseclib3\File\ASN1\Maps;

use phpseclib3\File\ASN1;

/**
 * ReasonFlags
 *
 * @package ASN1
 * @author  Jim Wigginton <terrafrost@php.net>
 * @access  public
 */
abstract class ReasonFlags
{
    const MAP = [
        'type'    => ASN1::TYPE_BIT_STRING,
        'mapping' => [
            'unused',
            'keyCompromise',
            'cACompromise',
            'affiliationChanged',
            'superseded',
            'cessationOfOperation',
            'certificateHold',
            'privilegeWithdrawn',
            'aACompromise'
        ]
    ];
}


text:
<resources>
    <string name="app_name">Circular Layout Manager</string>
</resources>


text: Our Android project.


text:
from django import forms

from apps.gallery.models import Album

class FormPostAlbum(forms.ModelForm):
    class Meta:
        model = Album


text:
<?php

namespace Drupal\Tests\menu_ui\FunctionalJavascript;

use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
use Drupal\system\Entity\Menu;
use Drupal\Tests\contextual\FunctionalJavascript\ContextualLinkClickTrait;
use Drupal\Tests\menu_ui\Traits\MenuUiTrait;

/**
 * Tests custom menu and menu links operations using the UI.
 *
 * @group menu_ui
 */
class MenuUiJavascriptTest extends JavascriptTestBase {

  use ContextualLinkClickTrait;
  use MenuUiTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'block',
    'contextual',
    'menu_link_content',
    'menu_ui',
    'test_page_test',
  ];

  /**
   * Tests the contextual links on a menu block.
   */
  public function testBlockContextualLinks() {
    $this->drupalLogin($this->drupalCreateUser([
      'administer menu',
      'access contextual links',
      'administer blocks',
    ]));
    $menu = $this->addCustomMenu();

    $block = $this->drupalPlaceBlock('system_menu_block:' . $menu->id(), [
      'label' => 'Custom menu',
      'provider' => 'system'
    ]);
    $this->addMenuLink('', '/', $menu->id());

    $this->drupalGet('test-page');

    // Click on 'Configure block' contextual link.
    $this->clickContextualLink("#block-{$block->id()}", 'Configure block');
    // Check that we're on block configuration form.
    $this->assertNotEmpty($this->getSession()->getPage()->findLink('Remove block'));

    $this->drupalGet('test-page');

    // Click on 'Edit menu' contextual link.
    $this->clickContextualLink("#block-{$block->id()}", 'Edit menu');
    // Check that we're on block configuration form.
    $this->assertSession()->pageTextContains("Machine name: {$menu->id()}");
  }

  /**
   * Creates a custom menu.
   *
   * @return \Drupal\system\Entity\Menu
   *   The custom menu that has been created.
   */
  protected function addCustomMenu() {
    // Try adding a menu using a menu_name that is too long.
    $label = $this->randomMachineName(16);
    $menu_id = strtolower($this->randomMachineName(MENU_MAX_MENU_NAME_LENGTH_UI + 1));

    $this->drupalGet('admin/structure/menu/add');
    $page = $this->getSession()->getPage();
    // Type the label to activate the machine name field and the edit button.
    $page->fillField('Title', $label);
    // Wait for the machine name widget to be activated.
    $this->assertSession()->waitForElementVisible('css', 'button[type=button].link:contains(Edit)');
    // Activate the machine name text field.
    $page->pressButton('Edit');
    // Try to fill a text longer than the allowed limit.
    $page->fillField('Menu name', $menu_id);
    $page->pressButton('Save');
    // Check that the menu was saved with the ID truncated to the max length.
    $menu = Menu::load(substr($menu_id, 0, MENU_MAX_MENU_NAME_LENGTH_UI));
    $this->assertEquals($label, $menu->label());

    // Check that the menu was added.
    $this->drupalGet('admin/structure/menu');
    $this->assertSession()->pageTextContains($label);

    // Confirm that the custom menu block is available.
    $this->drupalGet('admin/structure/block/list/' . $this->config('system.theme')->get('default'));
    $this->clickLink('Place block');
    // Wait for the modal dialog to be loaded.
    $this->assertSession()->waitForElement('css', "div[aria-describedby=drupal-modal]");
    // Check that the block is available to be placed.
    $this->assertSession()->pageTextContains($label);

    return $menu;
  }

  /**
   * Adds a menu link using the UI.
   *
   * @param string $parent
   *   Optional parent menu link id.
   * @param string $path
   *   The path to enter on the form. Defaults to the front page.
   * @param string $menu_id
   *   Menu ID. Defaults to 'tools'.
   * @param bool $expanded
   *   Whether or not this menu link is expanded. Setting this to TRUE should
   *   test whether it works when we do the authenticatedUser tests. Defaults
   *   to FALSE.
   * @param string $weight
   *   Menu weight. Defaults to 0.
   *
   * @return \Drupal\menu_link_content\Entity\MenuLinkContent
   *   A menu link entity.
   */
  protected function addMenuLink($parent = '', $path = '/', $menu_id = 'tools', $expanded = FALSE, $weight = '0') {
    // View add menu link page.
    $this->drupalGet("admin/structure/menu/manage/$menu_id/add");
    $this->assertSession()->statusCodeEquals(200);

    $title = '!link_' . $this->randomMachineName(16);
    $edit = [
      'link[0][uri]' => $path,
      'title[0][value]' => $title,
      'description[0][value]' => '',
      'enabled[value]' => 1,
      'expanded[value]' => $expanded,
      'menu_parent' => $menu_id . ':' . $parent,
      'weight[0][value]' => $weight,
    ];

    // Add menu link.
    $this->drupalPostForm(NULL, $edit, 'Save');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('The menu link has been saved.');

    $storage = $this->container->get('entity_type.manager')->getStorage('menu_link_content');
    $menu_links = $storage->loadByProperties(['title' => $title]);
    $menu_link = reset($menu_links);

    // Check that the stored menu link meeting the expectations.
    $this->assertNotNull($menu_link);
    $this->assertMenuLink([
      'menu_name' => $menu_id,
      'children' => [],
      'parent' => $parent
    ], $menu_link->getPluginId());

    return $menu_link;
  }

}


text:
const struct CatalogInfoMOAttributes CatalogInfoMOAttributes = {
	.indexInManifest = @"indexInManifest",
	.isEnabledForManifest = @"isEnabledForManifest",
	.isEnabledForPackage = @"isEnabledForPackage",
	.originalIndex = @"originalIndex",
};

const struct CatalogInfoMORelationships CatalogInfoMORelationships = {
	.catalog = @"catalog",
	.manifest = @"manifest",
	.package = @"package",
};

@implementation CatalogInfoMOID
@end

@implementation _CatalogInfoMO

+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_ {
	NSParameterAssert(moc_);
	return [NSEntityDescription insertNewObjectForEntityForName:@"CatalogInfo" inManagedObjectContext:moc_];
}

+ (NSString*)entityName {
	return @"CatalogInfo";
}

+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_ {
	NSParameterAssert(moc_);
	return [NSEntityDescription entityForName:@"CatalogInfo" inManagedObjectContext:moc_];
}

- (CatalogInfoMOID*)objectID {
	return (CatalogInfoMOID*)[super objectID];
}

+ (NSSet*)keyPathsForValuesAffectingValueForKey:(NSString*)key {
	NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];

	if ([key isEqualToString:@"indexInManifestValue"]) {
		NSSet *affectingKey = [NSSet setWithObject:@"indexInManifest"];
		keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKey];
		return keyPaths;
	}
	if ([key isEqualToString:@"isEnabledForManifestValue"]) {
		NSSet *affectingKey = [NSSet setWithObject:@"isEnabledForManifest"];
		keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKey];
		return keyPaths;
	}
	if ([key isEqualToString:@"isEnabledForPackageValue"]) {
		NSSet *affectingKey = [NSSet setWithObject:@"isEnabledForPackage"];
		keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKey];
		return keyPaths;
	}
	if ([key isEqualToString:@"originalIndexValue"]) {
		NSSet *affectingKey = [NSSet setWithObject:@"originalIndex"];
		keyPaths = [keyPaths setByAddingObjectsFromSet:affectingKey];
		return keyPaths;
	}

	return keyPaths;
}

@dynamic indexInManifest;

- (int32_t)indexInManifestValue {
	NSNumber *result = [self indexInManifest];
	return [result intValue];
}

- (void)setIndexInManifestValue:(int32_t)value_ {
	[self setIndexInManifest:[NSNumber numberWithInt:value_]];
}

- (int32_t)primitiveIndexInManifestValue {
	NSNumber *result = [self primitiveIndexInManifest];
	return [result intValue];
}

- (void)setPrimitiveIndexInManifestValue:(int32_t)value_ {
	[self setPrimitiveIndexInManifest:[NSNumber numberWithInt:value_]];
}

@dynamic isEnabledForManifest;

- (BOOL)isEnabledForManifestValue {
	NSNumber *result = [self isEnabledForManifest];
	return [result boolValue];
}

- (void)setIsEnabledForManifestValue:(BOOL)value_ {
	[self setIsEnabledForManifest:[NSNumber numberWithBool:value_]];
}

- (BOOL)primitiveIsEnabledForManifestValue {
	NSNumber *result = [self primitiveIsEnabledForManifest];
	return [result boolValue];
}

- (void)setPrimitiveIsEnabledForManifestValue:(BOOL)value_ {
	[self setPrimitiveIsEnabledForManifest:[NSNumber numberWithBool:value_]];
}

@dynamic isEnabledForPackage;

- (BOOL)isEnabledForPackageValue {
	NSNumber *result = [self isEnabledForPackage];
	return [result boolValue];
}

- (void)setIsEnabledForPackageValue:(BOOL)value_ {
	[self setIsEnabledForPackage:[NSNumber numberWithBool:value_]];
}

- (BOOL)primitiveIsEnabledForPackageValue {
	NSNumber *result = [self primitiveIsEnabledForPackage];
	return [result boolValue];
}

- (void)setPrimitiveIsEnabledForPackageValue:(BOOL)value_ {
	[self setPrimitiveIsEnabledForPackage:[NSNumber numberWithBool:value_]];
}

@dynamic originalIndex;

- (int32_t)originalIndexValue {
	NSNumber *result = [self originalIndex];
	return [result intValue];
}

- (void)setOriginalIndexValue:(int32_t)value_ {
	[self setOriginalIndex:[NSNumber numberWithInt:value_]];
}

- (int32_t)primitiveOriginalIndexValue {
	NSNumber *result = [self primitiveOriginalIndex];
	return [result intValue];
}

- (void)setPrimitiveOriginalIndexValue:(int32_t)value_ {
	[self setPrimitiveOriginalIndex:[NSNumber numberWithInt:value_]];
}

@dynamic catalog;

@dynamic manifest;

@dynamic package;

@end


text:
<title>Calling - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Altering.html#Altering" title="Altering">
<link rel="prev" href="Returning.html#Returning" title="Returning">
<link rel="next" href="Patching.html#Patching" title="Patching">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Patching,
Previous: Returning,
Up: Altering

17.5 Calling Program Functions

print <var>expr</var>
Evaluate the expression <var>expr</var> and display the resulting value.
The expression may include calls to functions in the program being
debugged.

call <var>expr</var>
Evaluate the expression <var>expr</var> without displaying void
returned values.

You can use this variant of the print command if you want to
execute a function from your program that does not return anything
(a.k.a. <dfn>a void function</dfn>), but without cluttering the output
with void returned values that gdb will otherwise
print.  If the result is not void, it is printed and saved in the
value history.

It is possible for the function you call via the print or
call command to generate a signal (e.g., if there's a bug in
the function, or if you passed it incorrect arguments).  What happens
in that case is controlled by the set unwindonsignal command.

Similarly, with a C<tt>++</tt> program it is possible for the function you
call via the print or call command to generate an
exception that is not handled due to the constraints of the dummy
frame.  In this case, any exception that is raised in the frame, but has
an out-of-frame exception handler will not be found.  GDB builds a
dummy-frame for the inferior function call, and the unwinder cannot
seek for exception handlers outside of this dummy-frame.  What happens
in that case is controlled by the
set unwind-on-terminating-exception command.

set unwindonsignal
Set unwinding of the stack if a signal is received while in a function
that gdb called in the program being debugged.  If set to on,
gdb unwinds the stack it created for the call and restores
the context to what it was before the call.  If set to off (the
default), gdb stops in the frame where the signal was
received.

show unwindonsignal
Show the current setting of stack unwinding in the functions called by
gdb.

set unwind-on-terminating-exception
Set unwinding of the stack if a C<tt>++</tt> exception is raised, but left
unhandled while in a function that gdb called in the program being
debugged.  If set to on (the default), gdb unwinds the stack
it created for the call and restores the context to what it was before
the call.  If set to off, gdb the exception is delivered to
the default C<tt>++</tt> exception handler and the inferior terminated.

show unwind-on-terminating-exception
Show the current setting of stack unwinding in the functions called by
gdb.

17.5.1 Calling functions with no debug info

Sometimes, a function you wish to call is missing debug information.
In such case, gdb does not know the type of the function,
including the types of the function's parameters.  To avoid calling
the inferior function incorrectly, which could result in the called
function functioning erroneously and even crash, gdb refuses
to call the function unless you tell it the type of the function.

For prototyped (i.e. ANSI/ISO style) functions, there are two ways
to do that.  The simplest is to cast the call to the function's
declared return type.  For example:

     (gdb) p getenv ("PATH")
     'getenv' has unknown return type; cast the call to its declared return type
     (gdb) p (char *) getenv ("PATH")
     $1 = 0x7fffffffe7ba "/usr/local/bin:/"...

Casting the return type of a no-debug function is equivalent to
casting the function to a pointer to a prototyped function that has a
prototype that matches the types of the passed-in arguments, and
calling that.  I.e., the call above is equivalent to:

     (gdb) p ((char * (*) (const char *)) getenv) ("PATH")

and given this prototyped C or C++ function with float parameters:

     float multiply (float v1, float v2) { return v1 * v2; }

these calls are equivalent:

     (gdb) p (float) multiply (2.0f, 3.0f)
     (gdb) p ((float (*) (float, float)) multiply) (2.0f, 3.0f)

If the function you wish to call is declared as unprototyped (i.e.
old K&R style), you must use the cast-to-function-pointer syntax, so
that gdb knows that it needs to apply default argument
promotions (promote float arguments to double).  See float promotion.  For example, given this unprototyped C function with
float parameters, and no debug info:

     float
     multiply_noproto (v1, v2)
       float v1, v2;
     {
       return v1 * v2;
     }

you call it like this:

       (gdb) p ((float (*) ()) multiply_noproto) (2.0f, 3.0f)


text:
`rb_smil_emulator` is now **deprecated**.

**Do not use it in production.**

Please note that I **removed** this JS script from the free EPUB 3 Audio-eBooks
hosted at [ReadBeyond](http://readbeyond.it/ebooks.html).

Now I think that providing this **workaround**
for reading applications that lack support
for EPUB 3 Media Overlays (MO) in reflowable rendition
(e.g., iBooks) has been a **bad move**.

In fact, it has not promoted reading app developers to fill their gaps,
and it has given the end users a false perception
about the MO support of their reading application.

I hope readers will start **caring** more about **adherence to open formats**,
and thus they will start **asking their app developers to comply** with them.

To summarize, I will no longer update the code in this repository,
and I strongly urge any developer who forked it to follow suit.

## Abstract

* File name: `rb_smil_emulator.js`
* Version: 1.12
* Date: 2014-05-20
* Author: Alberto Pettarin ([website](http://www.albertopettarin.it/), [contact information](http://www.albertopettarin.it/contact.html))
* License: the MIT License (MIT), see LICENSE

This Javascript file enables the tap-to-play function on those platforms
that do not properly support the EPUB 3 Media Overlay specification
(most notably, Apple iBooks).

Please note that this JS script is independent from the integrated audio controls
and the regular Media Overlay/SMIL controls that your reading system might provide,
and it might conflict with them.
Use it at your own risk!
If you think that tap-to-play is a useful feature,
I request you to urge the developers of your favourite reading system to implement
the official EPUB 3 Media Overlay specification.

Although primarily developed for iBooks,
it works in modern browsers (e.g., Chrome) as well.

## Usage

In your XHTML page (say, `page.xhtml`) you must add the following code blocks.

In the `<head>`:
```HTML
<script type="text/javascript" src="path/to/rb_smil_emulator.js"></script>
<script type="text/javascript" src="path/to/page.smil.js"></script>
```

As the last element of `<body>`
(see below for optional parameters in the form `{k1: p1, k2: p2, k3: p3}`):
```HTML
<script type="text/javascript">
//<![CDATA[
  window.addEventListener('DOMContentLoaded',
    function() {
      window.rb_smil_emulator.init('path/to/page.mp3', {k1: p1, k2: p2, k3: p3});
    }
  );
//]]>
</script>
```

Remember to:
* define two CSS classes to style the active or paused SMIL fragment
(the default names are `rbActiveFragment` and `rbPausedFragment`, respectively), and
* generate `page.smil.js`, containing `smil_data` and `smil_ids`.

The SMIL fragments, defined in `page.smil.js`,
must be contiguous
(the end of the i-th fragment coincides with
the begin of the (i+1)-th fragment),
and span the entire audio track
(the first fragment should start at time zero,
while the last fragment should end
at the end of the audio track).
Fragments might have zero duration
(i.e., their begin and end time coincide).

Please observe that `smil_data.length`
should be equal to `smil_ids.length`,
and it should be equal to the number of SMIL fragments;
the fragments must appear in these two arrays
sorted according to their begin time.
Fragment IDs might be arbitrary (but unique) strings.

Optional parameter keys include:
* `active_fragment_class_name`
* `paused_fragment_class_name`
* `autostart_audio`
* `autostart_wait_event`
* `autoturn_page`
* `single_fragment`
* `outside_taps_clear`
* `outside_taps_can_resume`
* `outside_taps_threshold`
* `associated_events`
* `ignore_taps_on_a_elements`
* `allowed_reading_systems`
* `hide_elements`

The meaning of the above options, their type and default value
are described in the comment right above `init()` in the source code.

## Source code

Please see the `src/` directory.

## Examples

A minimal (but working) example can be found in the `minimal/` directory.

Several full, regular EPUB3 Audio-eBook samples can be freely downloaded
from [ReadBeyond Web Site](http://readbeyond.it/ebooks.html).

## Limitations and Missing Features

* Support generic SMIL fragments (not necessarily contiguous nor spanning the entire audio track)
* Support multiple highlighted elements at the same time
* Integration with existing `<audio>` (or `<video>`) element (unfortunately at the moment seeking seems broken in iBooks)
* More flexible, user-customizable interaction between user click/touch and audio rendition behaviour
* Use/integrate existing SMIL libraries (e.g., `timesheet.js`)
* Avoid collision of two audio sources, especially in iBooks (if possible at all --- right now it does not seem possible)
* Load next chapter upon the end of the current (if possible at all --- right now it does not seem possible)

## Acknowledgments

* I was inspired by the source code of [Readium](http://readium.org/) and [Timesheet.js](http://wam.inrialpes.fr/timesheets/)
* Thanks to _Giulio Cesare Solaroli_ for a useful discussion about JS
* Thanks to _torazaburo_ for answering my question about [how to make iBook turn page with JS](http://stackoverflow.com/questions/16922631/make-ibooks-turn-page-in-reflow-mode-with-javascript-embedded-in-the-displayed)
* Thanks to _Frank Chen_ for providing a sample JS code incorporated into the current code for the autoturnpage option
* Thanks to _Dirk_ for spotting a problem with applying/removing CSS via classList
* Thanks to _Daniel Weck_ for providing the code for detecting the new Readium platform and iBooks for Mac OS X.

Please feel free to send me your feedback about this project
(my email address can be found in the source code header),
and/or fork and improve it!


text:
package de.jungblut.clustering;

import com.google.common.base.Preconditions;
import de.jungblut.distance.DistanceMeasurer;
import de.jungblut.math.DoubleVector;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Sequential canopy clusterer.
 *
 * @author thomas.jungblut
 */
public final class CanopyClustering {

    private static final Logger LOG = LogManager
            .getLogger(CanopyClustering.class);

    private CanopyClustering() {
        throw new IllegalAccessError();
    }

    /**
     * Creates a list of canopies. Make sure that t1 > t2!
     *
     * @param points  the points to cluster.
     * @param measure the distance measurer to use.
     * @param t1      the outer cluster distance (fuzzy).
     * @param t2      the inner cluster distance (exclusive).
     * @param verbose if true, output about timinings and number of clusters.
     * @return a list of canopy centers.
     */
    public static List<DoubleVector> createCanopies(List<DoubleVector> pPoints,
                                                    DistanceMeasurer measure, double t1, double t2, boolean verbose) {
        Preconditions.checkArgument(t1 > t2, "t1 must be > t2!");

        // use a linked structure, so we can remove the head fast
        LinkedList<DoubleVector> points = new LinkedList<>(pPoints);

        // do the clustering
        List<DoubleVector> canopyList = new ArrayList<>();
        long start = System.currentTimeMillis();
        while (!points.isEmpty()) {
            DoubleVector p1 = points.get(0);
            points.remove(0);
            DoubleVector canopy = p1.deepCopy();
            int assigned = 1;
            // one can speed this up by an inverted index or a kd-tree
            Iterator<DoubleVector> iterator = points.iterator();
            while (iterator.hasNext()) {
                DoubleVector p2 = iterator.next();
                double dist = measure.measureDistance(p1, p2);
                // Put all points that are within distance threshold T1 into the
                // canopy
                if (dist < t1) {
                    assigned++;
                    canopy.add(p2);
                }
                // Remove from the list all points that are within distance
                // threshold T2 (strongly bound)
                if (dist < t2) {
                    iterator.remove();
                }
            }
            // average it
            if (assigned > 1) {
                canopy = canopy.divide(assigned);
            }
            canopyList.add(canopy);

            if (verbose) {
                LOG.info(points.size()
                        + " vectors remaining to cluster | Found canopies: "
                        + canopyList.size() + " | Took "
                        + (System.currentTimeMillis() - start) + "ms!");
            }
            start = System.currentTimeMillis();
        }
        return canopyList;
    }

}


text:
require 'spec_helper'

describe "GoogleSet" do
  it "should return related terms for the specified term" do
    GoogleSet.for("banana", "orange").should include("apples")
  end

  it "should return nothing if no elements are specified" do
    GoogleSet.for().should be_empty
  end

  it "should raise a GoogleSet::Error exception on failure to read from google sets" do
    GoogleSet.stub!(:open).and_raise(StandardError)
    lambda{GoogleSet.for("apple", "orange")}.should raise_error GoogleSet::Error
  end
end