text:
/////////////////////////////////////////////////////////////////////////
// $Id: tasking.cc,v 1.61 2008/08/03 19:53:09 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
/////////////////////////////////////////////////////////////////////////

#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR

// Notes:
// ======

  // ======================
  // 286 Task State Segment
  // ======================
  // dynamic item                      | hex  dec  offset
  // 0       task LDT selector         | 2a   42
  // 1       DS selector               | 28   40
  // 1       SS selector               | 26   38
  // 1       CS selector               | 24   36
  // 1       ES selector               | 22   34
  // 1       DI                        | 20   32
  // 1       SI                        | 1e   30
  // 1       BP                        | 1c   28
  // 1       SP                        | 1a   26
  // 1       BX                        | 18   24
  // 1       DX                        | 16   22
  // 1       CX                        | 14   20
  // 1       AX                        | 12   18
  // 1       flag word                 | 10   16
  // 1       IP (entry point)          | 0e   14
  // 0       SS for CPL 2              | 0c   12
  // 0       SP for CPL 2              | 0a   10
  // 0       SS for CPL 1              | 08   08
  // 0       SP for CPL 1              | 06   06
  // 0       SS for CPL 0              | 04   04
  // 0       SP for CPL 0              | 02   02
  //         back link selector to TSS | 00   00

  // ======================
  // 386 Task State Segment
  // ======================
  // |31            16|15                    0| hex dec
  // |I/O Map Base    |000000000000000000000|T| 64  100 static
  // |0000000000000000| LDT                   | 60  96  static
  // |0000000000000000| GS selector           | 5c  92  dynamic
  // |0000000000000000| FS selector           | 58  88  dynamic
  // |0000000000000000| DS selector           | 54  84  dynamic
  // |0000000000000000| SS selector           | 50  80  dynamic
  // |0000000000000000| CS selector           | 4c  76  dynamic
  // |0000000000000000| ES selector           | 48  72  dynamic
  // |                EDI                     | 44  68  dynamic
  // |                ESI                     | 40  64  dynamic
  // |                EBP                     | 3c  60  dynamic
  // |                ESP                     | 38  56  dynamic
  // |                EBX                     | 34  52  dynamic
  // |                EDX                     | 30  48  dynamic
  // |                ECX                     | 2c  44  dynamic
  // |                EAX                     | 28  40  dynamic
  // |                EFLAGS                  | 24  36  dynamic
  // |                EIP (entry point)       | 20  32  dynamic
  // |           CR3 (PDPR)                   | 1c  28  static
  // |000000000000000 | SS for CPL 2          | 18  24  static
  // |           ESP for CPL 2                | 14  20  static
  // |000000000000000 | SS for CPL 1          | 10  16  static
  // |           ESP for CPL 1                | 0c  12  static
  // |000000000000000 | SS for CPL 0          | 08  08  static
  // |           ESP for CPL 0                | 04  04  static
  // |000000000000000 | back link to prev TSS | 00  00  dynamic (updated only when return expected)

  // ==================================================
  // Effect of task switch on Busy, NT, and Link Fields
  // ==================================================

  // Field         jump        call/interrupt     iret
  // ------------------------------------------------------
  // new busy bit  Set         Set                No change
  // old busy bit  Cleared     No change          Cleared
  // new NT flag   No change   Set                No change
  // old NT flag   No change   No change          Cleared
  // new link      No change   old TSS selector   No change
  // old link      No change   No change          No change
  // CR0.TS        Set         Set                Set

  // Note: I checked 386, 486, and Pentium, and they all exhibited
  //       exactly the same behaviour as above.  There seems to
  //       be some misprints in the Intel docs.

void BX_CPU_C::task_switch(bx_selector_t *tss_selector,
                 bx_descriptor_t *tss_descriptor, unsigned source,
                 Bit32u dword1, Bit32u dword2)
{
  Bit32u obase32; // base address of old TSS
  Bit32u nbase32; // base address of new TSS
  Bit32u temp32, newCR3;
  Bit16u raw_cs_selector, raw_ss_selector, raw_ds_selector, raw_es_selector,
         raw_fs_selector, raw_gs_selector, raw_ldt_selector;
  Bit16u temp16, trap_word;
  bx_selector_t cs_selector, ss_selector, ds_selector, es_selector,
                fs_selector, gs_selector, ldt_selector;
  bx_descriptor_t cs_descriptor, ss_descriptor, ldt_descriptor;
  Bit32u old_TSS_max, new_TSS_max, old_TSS_limit, new_TSS_limit;
  Bit32u newEAX, newECX, newEDX, newEBX;
  Bit32u newESP, newEBP, newESI, newEDI;
  Bit32u newEFLAGS, newEIP;

  BX_DEBUG(("TASKING: ENTER"));

  invalidate_prefetch_q();

  // Discard any traps and inhibits for new context; traps will
  // resume upon return.
  BX_CPU_THIS_PTR debug_trap = 0;
  BX_CPU_THIS_PTR inhibit_mask = 0;

  // STEP 1: The following checks are made before calling task_switch(),
  //         for JMP & CALL only. These checks are NOT made for exceptions,
  //         interrupts & IRET.
  //
  //   1) TSS DPL must be >= CPL
  //   2) TSS DPL must be >= TSS selector RPL
  //   3) TSS descriptor is not busy.

  // TSS must be present, else #NP(TSS selector)
  if (tss_descriptor->p==0) {
    BX_ERROR(("task_switch: TSS descriptor is not present !"));
    exception(BX_NP_EXCEPTION, tss_selector->value & 0xfffc, 0);
  }

  // STEP 2: The processor performs limit-checking on the target TSS
  //         to verify that the TSS limit is greater than or equal
  //         to 67h (2Bh for 16-bit TSS).

  // Gather info about old TSS
  if (BX_CPU_THIS_PTR tr.cache.type <= 3) {
    old_TSS_max = 0x29;
  }
  else {
    old_TSS_max = 0x5F;
  }
  // Gather info about new TSS
  if (tss_descriptor->type <= 3) { // {1,3}
    new_TSS_max = 0x2B;
  }
  else { // tss_descriptor->type = {9,11}
    new_TSS_max = 0x67;
  }

  obase32 = (Bit32u) BX_CPU_THIS_PTR tr.cache.u.system.base;        // old TSS.base
  old_TSS_limit = BX_CPU_THIS_PTR tr.cache.u.system.limit_scaled;
  nbase32 = (Bit32u) tss_descriptor->u.system.base;                 // new TSS.base
  new_TSS_limit = tss_descriptor->u.system.limit_scaled;

  // TSS must have valid limit, else #TS(TSS selector)
  if (tss_selector->ti || tss_descriptor->valid==0 ||
      new_TSS_limit < new_TSS_max)
  {
    BX_ERROR(("task_switch(): new TSS limit < %d", new_TSS_max));
    exception(BX_TS_EXCEPTION, tss_selector->value & 0xfffc, 0);
  }

  if (old_TSS_limit < old_TSS_max) {
    BX_ERROR(("task_switch(): old TSS limit < %d", old_TSS_max));
    exception(BX_TS_EXCEPTION, BX_CPU_THIS_PTR tr.selector.value & 0xfffc, 0);
  }

  if (obase32 == nbase32) {
    BX_INFO(("TASK SWITCH: switching to the same TSS !"));
  }

  // Check that old TSS, new TSS, and all segment descriptors
  // used in the task switch are paged in.
  if (BX_CPU_THIS_PTR cr0.get_PG())
  {
    dtranslate_linear(obase32, 0, BX_WRITE); // new TSS
    dtranslate_linear(obase32 + old_TSS_max, 0, BX_WRITE);
    dtranslate_linear(nbase32, 0, BX_READ);  // old TSS
    dtranslate_linear(nbase32 + new_TSS_max, 0, BX_READ);

    // ??? Humm, we check the new TSS region with READ above,
    // but sometimes we need to write the link field in that
    // region.  We also sometimes update other fields, perhaps
    // we need to WRITE check them here also, so that we keep
    // the written state consistent (ie, we don't encounter a
    // page fault in the middle).

    if (source == BX_TASK_FROM_CALL_OR_INT)
    {
      dtranslate_linear(nbase32,     0, BX_WRITE);
      dtranslate_linear(nbase32 + 2, 0, BX_WRITE);
    }
  }

  // Privilege and busy checks done in CALL, JUMP, INT, IRET

  // STEP 3: Save the current task state in the TSS. Up to this point,
  //         any exception that occurs aborts the task switch without
  //         changing the processor state.

  /* save current machine state in old task's TSS */

  Bit32u oldEFLAGS = read_eflags();

  /* if moving to busy task, clear NT bit */
  if (tss_descriptor->type == BX_SYS_SEGMENT_BUSY_286_TSS ||
      tss_descriptor->type == BX_SYS_SEGMENT_BUSY_386_TSS)
  {
    oldEFLAGS &= ~EFlagsNTMask;
  }

  if (BX_CPU_THIS_PTR tr.cache.type <= 3) {
    temp16 = IP; access_write_linear(Bit32u(obase32 + 14), 2, 0, &temp16);
    temp16 = oldEFLAGS; access_write_linear(Bit32u(obase32 + 16), 2, 0, &temp16);
    temp16 = AX; access_write_linear(Bit32u(obase32 + 18), 2, 0, &temp16);
    temp16 = CX; access_write_linear(Bit32u(obase32 + 20), 2, 0, &temp16);
    temp16 = DX; access_write_linear(Bit32u(obase32 + 22), 2, 0, &temp16);
    temp16 = BX; access_write_linear(Bit32u(obase32 + 24), 2, 0, &temp16);
    temp16 = SP; access_write_linear(Bit32u(obase32 + 26), 2, 0, &temp16);
    temp16 = BP; access_write_linear(Bit32u(obase32 + 28), 2, 0, &temp16);
    temp16 = SI; access_write_linear(Bit32u(obase32 + 30), 2, 0, &temp16);
    temp16 = DI; access_write_linear(Bit32u(obase32 + 32), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES].selector.value;
                 access_write_linear(Bit32u(obase32 + 34), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].selector.value;
                 access_write_linear(Bit32u(obase32 + 36), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].selector.value;
                 access_write_linear(Bit32u(obase32 + 38), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS].selector.value;
                 access_write_linear(Bit32u(obase32 + 40), 2, 0, &temp16);
  }
  else {
    temp32 = EIP; access_write_linear(Bit32u(obase32 + 0x20), 4, 0, &temp32);
    temp32 = oldEFLAGS; access_write_linear(Bit32u(obase32 + 0x24), 4, 0, &temp32);
    temp32 = EAX; access_write_linear(Bit32u(obase32 + 0x28), 4, 0, &temp32);
    temp32 = ECX; access_write_linear(Bit32u(obase32 + 0x2c), 4, 0, &temp32);
    temp32 = EDX; access_write_linear(Bit32u(obase32 + 0x30), 4, 0, &temp32);
    temp32 = EBX; access_write_linear(Bit32u(obase32 + 0x34), 4, 0, &temp32);
    temp32 = ESP; access_write_linear(Bit32u(obase32 + 0x38), 4, 0, &temp32);
    temp32 = EBP; access_write_linear(Bit32u(obase32 + 0x3c), 4, 0, &temp32);
    temp32 = ESI; access_write_linear(Bit32u(obase32 + 0x40), 4, 0, &temp32);
    temp32 = EDI; access_write_linear(Bit32u(obase32 + 0x44), 4, 0, &temp32);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES].selector.value;
                  access_write_linear(Bit32u(obase32 + 0x48), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].selector.value;
                  access_write_linear(Bit32u(obase32 + 0x4c), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].selector.value;
                  access_write_linear(Bit32u(obase32 + 0x50), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS].selector.value;
                  access_write_linear(Bit32u(obase32 + 0x54), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector.value;
                  access_write_linear(Bit32u(obase32 + 0x58), 2, 0, &temp16);
    temp16 = BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector.value;
                  access_write_linear(Bit32u(obase32 + 0x5c), 2, 0, &temp16);
  }

  // effect on link field of new task
  if (source == BX_TASK_FROM_CALL_OR_INT)
  {
    // set to selector of old task's TSS
    temp16 = BX_CPU_THIS_PTR tr.selector.value;
    access_write_linear(nbase32, 2, 0, &temp16);
  }

  // STEP 4: The new-task state is loaded from the TSS

  if (tss_descriptor->type <= 3) {
    access_read_linear(Bit32u(nbase32 + 14), 2, 0, BX_READ, &temp16);
      newEIP = temp16; // zero out upper word
    access_read_linear(Bit32u(nbase32 + 16), 2, 0, BX_READ, &temp16);
      newEFLAGS = temp16;

    // incoming TSS is 16bit:
    //   - upper word of general registers is set to 0xFFFF
    //   - upper word of eflags is zero'd
    //   - FS, GS are zero'd
    //   - upper word of eIP is zero'd
    access_read_linear(Bit32u(nbase32 + 18), 2, 0, BX_READ, &temp16);
      newEAX = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 20), 2, 0, BX_READ, &temp16);
      newECX = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 22), 2, 0, BX_READ, &temp16);
      newEDX = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 24), 2, 0, BX_READ, &temp16);
      newEBX = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 26), 2, 0, BX_READ, &temp16);
      newESP = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 28), 2, 0, BX_READ, &temp16);
      newEBP = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 30), 2, 0, BX_READ, &temp16);
      newESI = 0xffff0000 | temp16;
    access_read_linear(Bit32u(nbase32 + 32), 2, 0, BX_READ, &temp16);
      newEDI = 0xffff0000 | temp16;

    access_read_linear(Bit32u(nbase32 + 34), 2, 0, BX_READ, &raw_es_selector);
    access_read_linear(Bit32u(nbase32 + 36), 2, 0, BX_READ, &raw_cs_selector);
    access_read_linear(Bit32u(nbase32 + 38), 2, 0, BX_READ, &raw_ss_selector);
    access_read_linear(Bit32u(nbase32 + 40), 2, 0, BX_READ, &raw_ds_selector);
    access_read_linear(Bit32u(nbase32 + 42), 2, 0, BX_READ, &raw_ldt_selector);

    raw_fs_selector = 0; // use a NULL selector
    raw_gs_selector = 0; // use a NULL selector
    // No CR3 change for 286 task switch
    newCR3 = 0;   // keep compiler happy (not used)
    trap_word = 0; // keep compiler happy (not used)
  }
  else {
    if (BX_CPU_THIS_PTR cr0.get_PG())
      access_read_linear(Bit32u(nbase32 + 0x1c), 4, 0, BX_READ, &newCR3);
    else
      newCR3 = 0;   // keep compiler happy (not used)
    access_read_linear(Bit32u(nbase32 + 0x20), 4, 0, BX_READ, &newEIP);
    access_read_linear(Bit32u(nbase32 + 0x24), 4, 0, BX_READ, &newEFLAGS);
    access_read_linear(Bit32u(nbase32 + 0x28), 4, 0, BX_READ, &newEAX);
    access_read_linear(Bit32u(nbase32 + 0x2c), 4, 0, BX_READ, &newECX);
    access_read_linear(Bit32u(nbase32 + 0x30), 4, 0, BX_READ, &newEDX);
    access_read_linear(Bit32u(nbase32 + 0x34), 4, 0, BX_READ, &newEBX);
    access_read_linear(Bit32u(nbase32 + 0x38), 4, 0, BX_READ, &newESP);
    access_read_linear(Bit32u(nbase32 + 0x3c), 4, 0, BX_READ, &newEBP);
    access_read_linear(Bit32u(nbase32 + 0x40), 4, 0, BX_READ, &newESI);
    access_read_linear(Bit32u(nbase32 + 0x44), 4, 0, BX_READ, &newEDI);
    access_read_linear(Bit32u(nbase32 + 0x48), 2, 0, BX_READ, &raw_es_selector);
    access_read_linear(Bit32u(nbase32 + 0x4c), 2, 0, BX_READ, &raw_cs_selector);
    access_read_linear(Bit32u(nbase32 + 0x50), 2, 0, BX_READ, &raw_ss_selector);
    access_read_linear(Bit32u(nbase32 + 0x54), 2, 0, BX_READ, &raw_ds_selector);
    access_read_linear(Bit32u(nbase32 + 0x58), 2, 0, BX_READ, &raw_fs_selector);
    access_read_linear(Bit32u(nbase32 + 0x5c), 2, 0, BX_READ, &raw_gs_selector);
    access_read_linear(Bit32u(nbase32 + 0x60), 2, 0, BX_READ, &raw_ldt_selector);
    access_read_linear(Bit32u(nbase32 + 0x64), 2, 0, BX_READ, &trap_word);
  }

  // Step 5: If CALL, interrupt, or JMP, set busy flag in new task's
  //         TSS descriptor.  If IRET, leave set.

  if (source == BX_TASK_FROM_JUMP || source == BX_TASK_FROM_CALL_OR_INT)
  {
    // set the new task's busy bit
    Bit32u laddr = (Bit32u)(BX_CPU_THIS_PTR gdtr.base) + (tss_selector->index<<3) + 4;
    access_read_linear(laddr, 4, 0, BX_READ, &dword2);
    dword2 |= 0x200;
    access_write_linear(laddr, 4, 0, &dword2);
  }

  // Step 6: If JMP or IRET, clear busy bit in old task TSS descriptor,
  //         otherwise leave set.

  // effect on Busy bit of old task
  if (source == BX_TASK_FROM_JUMP || source == BX_TASK_FROM_IRET) {
    // Bit is cleared
    Bit32u laddr = (Bit32u) BX_CPU_THIS_PTR gdtr.base + (BX_CPU_THIS_PTR tr.selector.index<<3) + 4;
    access_read_linear(laddr, 4, 0, BX_READ, &temp32);
    temp32 &= ~0x200;
    access_write_linear(laddr, 4, 0, &temp32);
  }

  //
  // Commit point.  At this point, we commit to the new
  // context.  If an unrecoverable error occurs in further
  // processing, we complete the task switch without performing
  // additional access and segment availablility checks and
  // generate the appropriate exception prior to beginning
  // execution of the new task.
  //

  // Step 7: Load the task register with the segment selector and
  //        descriptor for the new task TSS.

  BX_CPU_THIS_PTR tr.selector = *tss_selector;
  BX_CPU_THIS_PTR tr.cache    = *tss_descriptor;
  BX_CPU_THIS_PTR tr.cache.type |= 2; // mark TSS in TR as busy

  // Step 8: Set TS flag in the CR0 image stored in the new task TSS.
  BX_CPU_THIS_PTR cr0.set_TS(1);

  // Task switch clears LE/L3/L2/L1/L0 in DR7
  BX_CPU_THIS_PTR dr7 &= ~0x00000155;

  // Step 9: If call or interrupt, set the NT flag in the eflags
  //         image stored in new task's TSS.  If IRET or JMP,
  //         NT is restored from new TSS eflags image. (no change)

  // effect on NT flag of new task
  if (source == BX_TASK_FROM_CALL_OR_INT) {
    newEFLAGS |= EFlagsNTMask; // NT flag is set
  }

  // Step 10: Load the new task (dynamic) state from new TSS.
  //          Any errors associated with loading and qualification of
  //          segment descriptors in this step occur in the new task's
  //          context.  State loaded here includes LDTR, CR3,
  //          EFLAGS, EIP, general purpose registers, and segment
  //          descriptor parts of the segment registers.

  if ((tss_descriptor->type >= 9) && BX_CPU_THIS_PTR cr0.get_PG()) {
    // change CR3 only if it actually modified
    if (newCR3 != BX_CPU_THIS_PTR cr3) {
      SetCR3(newCR3); // Tell paging unit about new cr3 value
      BX_DEBUG (("task_switch changing CR3 to 0x" FMT_PHY_ADDRX, newCR3));
      BX_INSTR_TLB_CNTRL(BX_CPU_ID, BX_INSTR_TASKSWITCH, newCR3);
    }
  }

  BX_CPU_THIS_PTR prev_rip = EIP = newEIP;

  EAX = newEAX;
  ECX = newECX;
  EDX = newEDX;
  EBX = newEBX;
  ESP = newESP;
  EBP = newEBP;
  ESI = newESI;
  EDI = newEDI;

  writeEFlags(newEFLAGS, EFlagsValidMask);

  // Fill in selectors for all segment registers.  If errors
  // occur later, the selectors will at least be loaded.
  parse_selector(raw_cs_selector, &cs_selector);
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].selector = cs_selector;
  parse_selector(raw_ds_selector, &ds_selector);
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS].selector = ds_selector;
  parse_selector(raw_es_selector, &es_selector);
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES].selector = es_selector;
  parse_selector(raw_ss_selector, &ss_selector);
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].selector = ss_selector;
  parse_selector(raw_fs_selector, &fs_selector);
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].selector = fs_selector;
  parse_selector(raw_gs_selector, &gs_selector);
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].selector = gs_selector;

  parse_selector(raw_ldt_selector, &ldt_selector);
  BX_CPU_THIS_PTR ldtr.selector = ldt_selector;

  // Start out with invalid descriptor caches, fill in
  // with values only as they are validated.
  BX_CPU_THIS_PTR ldtr.cache.valid = 0;
  BX_CPU_THIS_PTR ldtr.cache.u.system.limit = 0;
  BX_CPU_THIS_PTR ldtr.cache.u.system.limit_scaled = 0;
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES].cache.valid = 0;
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].cache.valid = 0;
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache.valid = 0;
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS].cache.valid = 0;
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS].cache.valid = 0;
  BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS].cache.valid = 0;

  // LDTR
  if (ldt_selector.ti) {
    // LDT selector must be in GDT
    BX_INFO(("task_switch(exception after commit point): bad LDT selector TI=1"));
    exception(BX_TS_EXCEPTION, raw_ldt_selector & 0xfffc, 0);
  }

  if ((raw_ldt_selector & 0xfffc) != 0) {
    bx_bool good = fetch_raw_descriptor2(&ldt_selector, &dword1, &dword2);
    if (!good) {
      BX_ERROR(("task_switch(exception after commit point): bad LDT fetch"));
      exception(BX_TS_EXCEPTION, raw_ldt_selector & 0xfffc, 0);
    }

    parse_descriptor(dword1, dword2, &ldt_descriptor);

    // LDT selector of new task is valid, else #TS(new task's LDT)
    if (ldt_descriptor.valid==0 ||
        ldt_descriptor.type!=BX_SYS_SEGMENT_LDT ||
        ldt_descriptor.segment)
    {
      BX_ERROR(("task_switch(exception after commit point): bad LDT segment"));
      exception(BX_TS_EXCEPTION, raw_ldt_selector & 0xfffc, 0);
    }

    // LDT of new task is present in memory, else #TS(new tasks's LDT)
    if (! IS_PRESENT(ldt_descriptor)) {
      BX_ERROR(("task_switch(exception after commit point): LDT not present"));
      exception(BX_TS_EXCEPTION, raw_ldt_selector & 0xfffc, 0);
    }

    // All checks pass, fill in LDTR shadow cache
    BX_CPU_THIS_PTR ldtr.cache = ldt_descriptor;
  }
  else {
    // NULL LDT selector is OK, leave cache invalid
  }

  if (v8086_mode()) {
    // load seg regs as 8086 registers
    load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS], raw_cs_selector);
    load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS], raw_ss_selector);
    load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS], raw_ds_selector);
    load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES], raw_es_selector);
    load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS], raw_fs_selector);
    load_seg_reg(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS], raw_gs_selector);
  }
  else {

    // SS
    if ((raw_ss_selector & 0xfffc) != 0)
    {
      bx_bool good = fetch_raw_descriptor2(&ss_selector, &dword1, &dword2);
      if (!good) {
        BX_ERROR(("task_switch(exception after commit point): bad SS fetch"));
        exception(BX_TS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
      }

      parse_descriptor(dword1, dword2, &ss_descriptor);
      // SS selector must be within its descriptor table limits else #TS(SS)
      // SS descriptor AR byte must must indicate writable data segment,
      // else #TS(SS)
      if (ss_descriptor.valid==0 || ss_descriptor.segment==0 ||
           IS_CODE_SEGMENT(ss_descriptor.type) ||
          !IS_DATA_SEGMENT_WRITEABLE(ss_descriptor.type))
      {
        BX_ERROR(("task_switch(exception after commit point): SS not valid or writeable segment"));
        exception(BX_TS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
      }

      //
      // Stack segment is present in memory, else #SS(new stack segment)
      //
      if (! IS_PRESENT(ss_descriptor)) {
        BX_ERROR(("task_switch(exception after commit point): SS not present"));
        exception(BX_SS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
      }

      // Stack segment DPL matches CS.RPL, else #TS(new stack segment)
      if (ss_descriptor.dpl != cs_selector.rpl) {
        BX_ERROR(("task_switch(exception after commit point): SS.rpl != CS.RPL"));
        exception(BX_TS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
      }

      // Stack segment DPL matches selector RPL, else #TS(new stack segment)
      if (ss_descriptor.dpl != ss_selector.rpl) {
        BX_ERROR(("task_switch(exception after commit point): SS.dpl != SS.rpl"));
        exception(BX_TS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
      }

      // All checks pass, fill in shadow cache
      BX_CPU_THIS_PTR sregs[BX_SEG_REG_SS].cache = ss_descriptor;
    }
    else {
      // SS selector is valid, else #TS(new stack segment)
      BX_ERROR(("task_switch(exception after commit point): SS NULL"));
      exception(BX_TS_EXCEPTION, raw_ss_selector & 0xfffc, 0);
    }

    // if new selector is not null then perform following checks:
    //    index must be within its descriptor table limits else #TS(selector)
    //    AR byte must indicate data or readable code else #TS(selector)
    //    if data or non-conforming code then:
    //      DPL must be >= CPL else #TS(selector)
    //      DPL must be >= RPL else #TS(selector)
    //    AR byte must indicate PRESENT else #NP(selector)
    //    load cache with new segment descriptor and set valid bit

    // CS
    if ((raw_cs_selector & 0xfffc) != 0) {
      bx_bool good = fetch_raw_descriptor2(&cs_selector, &dword1, &dword2);
      if (!good) {
        BX_ERROR(("task_switch(exception after commit point): bad CS fetch"));
        exception(BX_TS_EXCEPTION, raw_cs_selector & 0xfffc, 0);
      }

      parse_descriptor(dword1, dword2, &cs_descriptor);

      // CS descriptor AR byte must indicate code segment else #TS(CS)
      if (cs_descriptor.valid==0 || cs_descriptor.segment==0 ||
          IS_DATA_SEGMENT(cs_descriptor.type))
      {
        BX_ERROR(("task_switch(exception after commit point): CS not valid executable seg"));
        exception(BX_TS_EXCEPTION, raw_cs_selector & 0xfffc, 0);
      }

      // if non-conforming then DPL must equal selector RPL else #TS(CS)
      if (IS_CODE_SEGMENT_NON_CONFORMING(cs_descriptor.type) &&
          cs_descriptor.dpl != cs_selector.rpl)
      {
        BX_ERROR(("task_switch(exception after commit point): non-conforming: CS.dpl!=CS.RPL"));
        exception(BX_TS_EXCEPTION, raw_cs_selector & 0xfffc, 0);
      }

      // if conforming then DPL must be <= selector RPL else #TS(CS)
      if (IS_CODE_SEGMENT_CONFORMING(cs_descriptor.type) &&
          cs_descriptor.dpl > cs_selector.rpl)
      {
        BX_ERROR(("task_switch(exception after commit point): conforming: CS.dpl>RPL"));
        exception(BX_TS_EXCEPTION, raw_cs_selector & 0xfffc, 0);
      }

      // Code segment is present in memory, else #NP(new code segment)
      if (! IS_PRESENT(cs_descriptor)) {
        BX_ERROR(("task_switch(exception after commit point): CS.p==0"));
        exception(BX_NP_EXCEPTION, raw_cs_selector & 0xfffc, 0);
      }

      // All checks pass, fill in shadow cache
      BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].cache = cs_descriptor;
    }
    else {
      // If new cs selector is null #TS(CS)
      BX_ERROR(("task_switch(exception after commit point): CS NULL"));
      exception(BX_TS_EXCEPTION, raw_cs_selector & 0xfffc, 0);
    }

    updateFetchModeMask();

#if BX_CPU_LEVEL >= 4 && BX_SUPPORT_ALIGNMENT_CHECK
    handleAlignmentCheck(); // task switch, CPL was modified
#endif

    task_switch_load_selector(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_DS],
        &ds_selector, raw_ds_selector, cs_selector.rpl);
    task_switch_load_selector(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_ES],
        &es_selector, raw_es_selector, cs_selector.rpl);
    task_switch_load_selector(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_FS],
        &fs_selector, raw_fs_selector, cs_selector.rpl);
    task_switch_load_selector(&BX_CPU_THIS_PTR sregs[BX_SEG_REG_GS],
        &gs_selector, raw_gs_selector, cs_selector.rpl);
  }

  if ((tss_descriptor->type>=9) && (trap_word & 0x1)) {
    BX_CPU_THIS_PTR debug_trap |= 0x00008000; // BT flag in DR6
    BX_CPU_THIS_PTR async_event = 1; // so processor knows to check
    BX_INFO(("task_switch: T bit set in new TSS"));
  }

  //
  // Step 14: Begin execution of new task.
  //
  BX_DEBUG(("TASKING: LEAVE"));
}

void BX_CPU_C::task_switch_load_selector(bx_segment_reg_t *seg,
                 bx_selector_t *selector, Bit16u raw_selector, Bit8u cs_rpl)
{
  bx_descriptor_t descriptor;
  Bit32u dword1, dword2;

  // NULL selector is OK, will leave cache invalid
  if ((raw_selector & 0xfffc) != 0)
  {
    bx_bool good = fetch_raw_descriptor2(selector, &dword1, &dword2);
    if (!good) {
      BX_ERROR(("task_switch(%s): bad selector fetch !", strseg(seg)));
      exception(BX_TS_EXCEPTION, raw_selector & 0xfffc, 0);
    }

    parse_descriptor(dword1, dword2, &descriptor);

    /* AR byte must indicate data or readable code segment else #TS(selector) */
    if (descriptor.segment==0 || (IS_CODE_SEGMENT(descriptor.type) &&
        IS_CODE_SEGMENT_READABLE(descriptor.type) == 0))
    {
      BX_ERROR(("task_switch(%s): not data or readable code !", strseg(seg)));
      exception(BX_TS_EXCEPTION, raw_selector & 0xfffc, 0);
    }

    /* If data or non-conforming code, then both the RPL and the CPL
     * must be less than or equal to DPL in AR byte else #GP(selector) */
    if (IS_DATA_SEGMENT(descriptor.type) ||
        IS_CODE_SEGMENT_NON_CONFORMING(descriptor.type))
    {
      if ((selector->rpl > descriptor.dpl) || (cs_rpl > descriptor.dpl)) {
        BX_ERROR(("load_seg_reg(%s): RPL & CPL must be <= DPL", strseg(seg)));
        exception(BX_TS_EXCEPTION, raw_selector & 0xfffc, 0);
      }
    }

    if (! IS_PRESENT(descriptor)) {
      BX_ERROR(("task_switch(%s): descriptor not present !", strseg(seg)));
      exception(BX_NP_EXCEPTION, raw_selector & 0xfffc, 0);
    }

    // All checks pass, fill in shadow cache
    seg->cache = descriptor;
  }
}

void BX_CPU_C::get_SS_ESP_from_TSS(unsigned pl, Bit16u *ss, Bit32u *esp)
{
  if (BX_CPU_THIS_PTR tr.cache.valid==0)
    BX_PANIC(("get_SS_ESP_from_TSS: TR.cache invalid"));

  if (BX_CPU_THIS_PTR tr.cache.type==BX_SYS_SEGMENT_AVAIL_386_TSS ||
      BX_CPU_THIS_PTR tr.cache.type==BX_SYS_SEGMENT_BUSY_386_TSS)
  {
    // 32-bit TSS
    Bit32u TSSstackaddr = 8*pl + 4;
    if ((TSSstackaddr+7) > BX_CPU_THIS_PTR tr.cache.u.system.limit_scaled) {
      BX_DEBUG(("get_SS_ESP_from_TSS(386): TSSstackaddr > TSS.LIMIT"));
      exception(BX_TS_EXCEPTION, BX_CPU_THIS_PTR tr.selector.value & 0xfffc, 0);
    }
    access_read_linear(BX_CPU_THIS_PTR tr.cache.u.system.base +
      TSSstackaddr+4, 2, 0, BX_READ, ss);
    access_read_linear(BX_CPU_THIS_PTR tr.cache.u.system.base +
      TSSstackaddr,   4, 0, BX_READ, esp);
  }
  else if (BX_CPU_THIS_PTR tr.cache.type==BX_SYS_SEGMENT_AVAIL_286_TSS ||
           BX_CPU_THIS_PTR tr.cache.type==BX_SYS_SEGMENT_BUSY_286_TSS)
  {
    // 16-bit TSS
    Bit16u temp16;
    Bit32u TSSstackaddr = 4*pl + 2;
    if ((TSSstackaddr+4) > BX_CPU_THIS_PTR tr.cache.u.system.limit_scaled) {
      BX_DEBUG(("get_SS_ESP_from_TSS(286): TSSstackaddr > TSS.LIMIT"));
      exception(BX_TS_EXCEPTION, BX_CPU_THIS_PTR tr.selector.value & 0xfffc, 0);
    }
    access_read_linear(BX_CPU_THIS_PTR tr.cache.u.system.base +
      TSSstackaddr+2, 2, 0, BX_READ, ss);
    access_read_linear(BX_CPU_THIS_PTR tr.cache.u.system.base +
      TSSstackaddr,   2, 0, BX_READ, &temp16);
    *esp = temp16; // truncate
  }
  else {
    BX_PANIC(("get_SS_ESP_from_TSS: TR is bogus type (%u)",
             (unsigned) BX_CPU_THIS_PTR tr.cache.type));
  }
}

#if BX_SUPPORT_X86_64
void BX_CPU_C::get_RSP_from_TSS(unsigned pl, Bit64u *rsp)
{
  if (BX_CPU_THIS_PTR tr.cache.valid==0)
    BX_PANIC(("get_RSP_from_TSS: TR.cache invalid"));

  // 32-bit TSS
  Bit32u TSSstackaddr = 8*pl + 4;
  if ((TSSstackaddr+7) > BX_CPU_THIS_PTR tr.cache.u.system.limit_scaled) {
    BX_DEBUG(("get_RSP_from_TSS(): TSSstackaddr > TSS.LIMIT"));
    exception(BX_TS_EXCEPTION, BX_CPU_THIS_PTR tr.selector.value & 0xfffc, 0);
  }

  access_read_linear(BX_CPU_THIS_PTR tr.cache.u.system.base +
    TSSstackaddr, 8, 0, BX_READ, rsp);
}
#endif  // #if BX_SUPPORT_X86_64


text:
@interface OCDSelection ()

@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) NSArray *selectedNodes;
@property (nonatomic, strong) NSArray *dataArray;

@end

redpajama_set_name: RedPajamaGithub


text:
package com.sequenceiq.cloudbreak.structuredevent;

import com.sequenceiq.cloudbreak.common.user.CloudbreakUser;

public interface LegacyRestRequestThreadLocalService {
    void setCloudbreakUser(CloudbreakUser cloudbreakUser);

    CloudbreakUser getCloudbreakUser();

    void removeCloudbreakUser();
}


text:
<?php

namespace PHPSocketIO\Event;

use Symfony\Component\EventDispatcher\Event;

class EventDispatcher
{

    protected $events = array();
    protected $groupEvents = array();
    protected static $dispatcher = null;

    /**
     *
     * @return EventDispatcher
     */
    public static function getDispatcher()
    {
        if (self::$dispatcher === null) {
            self::$dispatcher = new static();
        }

        return self::$dispatcher;
    }

    protected function brocast(Event $event)
    {
        $eventName = $event->getName();
        $listeners = [];
        foreach ($this->events[$eventName] as &$eventGroup) {
            foreach ($eventGroup as $listenerArray) {
                list($listener, $priority) = $listenerArray;
                $listeners[$priority][] = $listener;
            }
        }
        krsort($listeners);
        $processCount = 0;
        foreach ($listeners as $listener) {
            foreach ($listener as $callback) {
                if ($event && $event->isPropagationStopped()) {
                    return $processCount;
                }
                $callback($event);
                $processCount++;
            }
        }

        return $processCount;
    }

    public function dispatch($eventName, Event $event = null, $group = null)
    {
        if (!isset($this->events[$eventName])) {
            return 0;
        }

        if (!$event) {
            $event = new Event();
        }

        $event->setName($eventName);

        if ($group === null) {
            return $this->brocast($event);
        }

        if (!isset($this->groupEvents[$group][$eventName])) {
            return 0;
        }

        $listeners=[];
        foreach ($this->groupEvents[$group][$eventName] as $uniqueKey) {
            if (isset($this->events[$eventName]) && isset($this->events[$eventName][$uniqueKey])) {
                foreach ($this->events[$eventName][$uniqueKey] as $listenerArray) {
                    list($listener, $priority) = $listenerArray;
                    $listeners[$priority][] = $listener;
                }
            }
        }
        krsort($listeners);
        $processCount = 0;
        foreach ($listeners as $listener) {
            foreach ($listener as $callback) {
                if ($event && $event->isPropagationStopped()) {
                    return $processCount;
                }
                $callback($event);
                $processCount++;
            }
        }

        return $processCount;
    }

    public function addListener($eventName, $listener, $groups = null, $priority = 0)
    {
        $uniqueKey = sha1(microtime().rand().rand(), true);
        if (!is_array($groups)) {
            $groups = [$groups];
        }
        $groups = array_unique($groups);
        foreach ($groups as $group) {
            if (!isset($this->events[$eventName][$group])) {
                $this->events[$eventName][$group] = array();
            }
            $this->groupEvents[$group][$eventName][] = $uniqueKey;
        }

        $this->events[$eventName][$uniqueKey][] = array($listener, $priority);

        return true;
    }

    public function removeGroupListener($group)
    {
        if (!isset($this->groupEvents[$group])) {
            return;
        }
        foreach ($this->groupEvents[$group] as $eventName => $tmp) {
            $this->removeListener($eventName, $group);
        }
        unset($this->groupEvents[$group]);
    }

    public function removeListener($eventName, $group)
    {
        if (!isset($this->events[$eventName])) {
            return;
        }
        foreach ($this->groupEvents[$group][$eventName] as $uniqueKey) {
            unset($this->events[$eventName][$uniqueKey]);
        }
        unset($this->groupEvents[$group][$eventName]);
        if (count($this->groupEvents[$group]) == 0) {
            unset($this->groupEvents[$group]);
        }
    }

}


text:
import stampit from './ext/stampit';
import {Pluggable} from './plugins';
import {UI, Suite} from './ui';
import {Runner} from './runner';
import {Reporter} from './reporter';
import pkg from './options/package';
import {assign} from 'lodash/fp';
import is from 'check-more-types';
import {pool, constant} from './ext/kefir';

const Mocha = stampit({
  refs: {
    version: pkg.version,
    plugins: {}
  },
  methods: {
    createAPI (Factory, properties = {}) {
      if (is.not.function(Factory)) {
        throw new Error('Factory function required');
      }
      return Factory(assign({
        delegate: this
      }, properties));
    },
    createUI (properties = {}) {
      return this.createAPI(UI, properties);
    },
    createReporter (properties = {}) {
      return this.createAPI(Reporter, assign(properties, {
        runner: this.runner
      }));
    },
    createSuite (definition = {}, opts = {}) {
      this.currentSuite.createSuite(definition, opts);
    },
    createTest (definition = {}, opts = {}) {
      this.currentSuite.createTest(definition, opts);
    },
    createHook (definition = {}, opts = {}) {
      this.currentSuite.createHook(definition, opts);
    },
    run () {
      return this.rootSuite.run();
    }
  }
})
  .compose(Pluggable)
  .init(function init () {
    const rootSuite = this.rootSuite = Suite({
      root: true,
      title: 'ROOT SUITE'
    });

    this.runner = Runner();

    this.currentSuite$ = pool();

    const currentSuiteProp$ = this.currentSuite$.toProperty(() => rootSuite);

    Object.defineProperty(this, 'currentSuite', {
      get () {
        let suite = null;
        currentSuiteProp$.onValue(currentSuite => {
          suite = currentSuite;
        });
        return suite;
      },
      set (suite) {
        this.currentSuite$.plug(constant(suite));
      }
    });

    this.use(this.ui);
    this.reporter = Reporter({runner: this.runner});
  });

export default Mocha.refs({Mocha});


text:
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2012 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

#include "../SFML/Network/UdpSocket.hpp"
#include "../SFML/Network/IpAddress.hpp"
#include "../SFML/Network/Packet.hpp"
#include "Socket.hpp"
#include <algorithm>
#include <iostream>

namespace sf {

UdpSocket::UdpSocket() :
Socket  (Udp),
m_buffer(MaxDatagramSize) {

}

unsigned short UdpSocket::getLocalPort() const {
    if ( getHandle() != -1 ) {
        // Retrieve informations about the local end of the socket
        sockaddr_in address;
        Socket::AddrLength size = sizeof(address);
        int temp = size;
        if (getsockname(getHandle(), reinterpret_cast<sockaddr*>(&address), &temp) != -1) {
            return ntohs(address.sin_port);
        }
    }

    // We failed to retrieve the port
    return 0;
}

Socket::Status UdpSocket::bind(unsigned short port) {
    // Create the internal socket if it doesn't exist
    create();

    // Bind the socket
    sockaddr_in address = Socket::createAddress(INADDR_ANY, port);
    if (::bind(getHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1) {
        std::cerr << "Failed to bind socket to port " << port << "\n";
        return Error;
    }

    return Done;
}

void UdpSocket::unbind() {
    // Simply close the socket
    close();
}

Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddress& remoteAddress, unsigned short remotePort) {
    // Create the internal socket if it doesn't exist
    create();

    // Make sure that all the data will fit in one datagram
    if (size > MaxDatagramSize) {
        std::cerr << "Cannot send data over the network "
              << "(the number of bytes to send is greater than sf::UdpSocket::MaxDatagramSize)\n";
        return Error;
    }

    // Build the target address
    sockaddr_in address = Socket::createAddress(remoteAddress.toInteger(), remotePort);

    // Send the data (unlike TCP, all the data is always sent in one call)
    int sent = sendto(getHandle(), static_cast<char*>(const_cast<void*>(data)), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&address), sizeof(address));

    // Check for errors
    if (sent < 0) {
        return Socket::getErrorStatus();
    }

    return Done;
}

Socket::Status UdpSocket::receive(void* data, std::size_t size, std::size_t& received, IpAddress& remoteAddress, unsigned short& remotePort) {
    // First clear the variables to fill
    received      = 0;
    remoteAddress = IpAddress();
    remotePort    = 0;

    // Check the destination buffer
    if (!data) {
        std::cerr << "Cannot receive data from the network (the destination buffer is invalid)\n";
        return Error;
    }

    // Data that will be filled with the other computer's address
    sockaddr_in address = Socket::createAddress(INADDR_ANY, 0);

    // Receive a chunk of bytes
    Socket::AddrLength addressSize = sizeof(address);
    int temp = addressSize;
    int sizeReceived = recvfrom(getHandle(), static_cast<char*>(const_cast<void*>(data)), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&address), &temp);

    // Check for errors
    if (sizeReceived < 0) {
        return Socket::getErrorStatus();
    }

    // Fill the sender informations
    received      = static_cast<std::size_t>(sizeReceived);
    remoteAddress = IpAddress(ntohl(address.sin_addr.s_addr));
    remotePort    = ntohs(address.sin_port);

    return Done;
}

Socket::Status UdpSocket::send(Packet& packet, const IpAddress& remoteAddress, unsigned short remotePort) {
    /* UDP is a datagram-oriented protocol (as opposed to TCP which is a stream
     * protocol). Sending one datagram is almost safe: it may be lost but if
     * it's received, then its data is guaranteed to be ok. However, splitting
     * a packet into multiple datagrams would be highly unreliable, since
     * datagrams may be reordered, dropped or mixed between different sources.
     * That's why SFML imposes a limit on packet size so that they can be sent
     * in a single datagram. This also removes the overhead associated to
     * packets -- there's no size to send in addition to the packet's data.
     */

    // Get the data to send from the packet
    std::size_t size = 0;
    const void* data = packet.onSend(size);

    // Send it
    return send(data, size, remoteAddress, remotePort);
}

Socket::Status UdpSocket::receive(Packet& packet, IpAddress& remoteAddress, unsigned short& remotePort) {
    // See the detailed comment in send(Packet) above.

    // Receive the datagram
    std::size_t received = 0;
    Status status = receive(&m_buffer[0], m_buffer.size(), received, remoteAddress, remotePort);

    // If we received valid data, we can copy it to the user packet
    packet.clear();
    if ((status == Done) && (received > 0)) {
        packet.onReceive(&m_buffer[0], received);
    }

    return status;
}

} // namespace sf


text:
//
//  CircleViewController.m
//  ColumnarChart
//
//  Created by 李茂轩 on 15/10/12.
//  Copyright © 2015年 Max. All rights reserved.
//

#import "CircleViewController.h"
#define RGBA(r,g,b,a)               [UIColor colorWithRed:(float)r/255.0f green:(float)g/255.0f blue:(float)b/255.0f alpha:a]
#import "ChartCicleView.h"
@interface CircleViewController ()
@property (nonatomic,retain)ChartCicleView *chartView;
@end

@implementation CircleViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSMutableArray *startArray = [@[[self returnStrWithFloat:M_PI*1.05],[self returnStrWithFloat:M_PI*0.51],[self returnStrWithFloat:M_PI*0.05]]mutableCopy];
    NSMutableArray *endArray = [@[[self returnStrWithFloat:M_PI*1.99],[self returnStrWithFloat:M_PI*0.99],[self returnStrWithFloat:M_PI*0.49]]mutableCopy];
    NSMutableArray *colorArray = [@[RGBA(157, 229, 243, 1), RGBA(250, 107, 103, 1),RGBA(254, 225, 133, 1)]mutableCopy];

    UIView *currentView = [[UIView alloc]initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, self.view.frame.size.height-200)];
    [self.view addSubview:currentView];

    self.chartView = [[ChartCicleView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 250) withLineWidth:30 withItemsCount:3 withStartAngleArray:startArray withEndAngleArray:endArray withBackGroundArray:colorArray];

    [currentView addSubview:self.chartView];

    [self.chartView reloadRatio];

    // Do any additional setup after loading the view.
}

- (NSString *)returnStrWithFloat:(CGFloat )floatValue{

    return [NSString stringWithFormat:@"%f",floatValue];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package com.google.cloud.spark.bigquery.write.context;

import java.io.IOException;
import org.apache.spark.sql.catalyst.InternalRow;

public class NoOpDataWriterContext implements DataWriterContext<InternalRow> {
  @Override
  public void write(InternalRow record) throws IOException {}

  @Override
  public WriterCommitMessageContext commit() throws IOException {
    return null;
  }

  @Override
  public void abort() throws IOException {}

  @Override
  public void close() throws IOException {
    // empty
  }
}


text:
package org.apache.polygene.test.model;

import org.apache.polygene.api.association.Association;
import org.apache.polygene.api.association.ManyAssociation;
import org.apache.polygene.api.property.Property;

public interface PetShop
{
    Property<Address> address();
    Association<City> city();
    ManyAssociation<Owner> owners();
}


text:
@interface CommonResourceClientTests : XCTestCase

@property (nonatomic, strong) CommonResourceClient *client;
@property (nonatomic, strong) id mockBundle;

@end

@implementation CommonResourceClientTests

- (void)setUp {
    [super setUp];

    self.client = [CommonResourceClient new];
    self.mockBundle = OCMClassMock([NSBundle class]);
    self.client.bundle = self.mockBundle;
}

- (void)tearDown {
    self.client = nil;

    [self.mockBundle stopMocking];
    self.mockBundle = nil;

    [super tearDown];
}

- (void)testThatClientLoadsFileFromBundle {
    // given
    NSString *const kTestFileName = @"test-name";
    NSString *const kTestFileType = @"test-type";

    // when
    [self.client loadResourceWithName:kTestFileName type:kTestFileType];

    // then
    OCMVerify([self.mockBundle pathForResource:kTestFileName
                                        ofType:kTestFileType]);
}

@end


text:
package com.example.dany.jjdraw;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.TypedValue;
import android.widget.ImageView;
import java.util.ArrayList;

public class DrawingView extends ImageView {

	private Path drawPath;
	private Paint drawPaint;
	private Paint canvasPaint;
	// initial color
	private int paintColor = 0xFFF5F5DC;
	private Canvas drawCanvas;
	private Bitmap canvasBitmap;
	private float brushSize, lastBrushSize;
	private boolean erase = false;
	// strokes drawn so far (the last MAX strokes)
	private ArrayList<Stroke> undoStrokes = new ArrayList<Stroke>();

	// strokes that were undone.
	private ArrayList<Stroke> undoneStrokes = new ArrayList<Stroke>();
	static final int MAX = 50;
	private Stroke currentStroke;

    public DrawingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setupDrawing();
    }
    private void setupDrawing() {
		brushSize = getResources().getInteger(R.integer.medium_size);
		lastBrushSize = brushSize;

		drawPath = new Path();
		drawPaint = new Paint();

		drawPaint.setColor(paintColor);
		drawPaint.setAntiAlias(true);
		drawPaint.setStrokeWidth(brushSize);
		drawPaint.setStyle(Paint.Style.STROKE);
		drawPaint.setStrokeJoin(Paint.Join.ROUND);
		drawPaint.setStrokeCap(Paint.Cap.ROUND);

		canvasPaint = new Paint(Paint.DITHER_FLAG);
		currentStroke = new Stroke();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    	super.onSizeChanged (w, h, oldw, oldh);
		canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		drawCanvas = new Canvas(canvasBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas) {
		canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
		canvas.drawPath(drawPath, drawPaint);
		invalidate();
    }

	// when undo is click we call this
	protected boolean onClickUndo() {
		boolean ret = false;

		// remove from undoStrokes list, add it to undoneStrokes list
		if (undoStrokes.size() > 0) {
			Stroke theStroke = undoStrokes.remove(undoStrokes.size()-1);
            Paint mypaint = new Paint();
			undoneStrokes.add(theStroke);

			// clear the canvas
			drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);

			// draw the strokes that we wanted.
			for (int i = 0; i < undoStrokes.size() ; i++) {
                undoStrokes.get(i).paint.setXfermode(null);
                undoStrokes.get(i).paint.setColor(undoStrokes.get(i).color);
				undoStrokes.get(i).paint.setStrokeWidth(undoStrokes.get(i).brushSize);
				drawCanvas.drawPath(undoStrokes.get(i).path, undoStrokes.get(i).paint);
				invalidate();
			}

			ret = true;
		}
		return ret;
	}

	protected boolean onClickRedo() {
		Boolean ret = false;
		if (undoneStrokes.size() > 0) {
			Stroke theStroke = undoneStrokes.remove(undoneStrokes.size()-1);
			undoStrokes.add(theStroke);

            theStroke.paint.setColor(theStroke.color);
			theStroke.paint.setStrokeWidth(theStroke.brushSize);
			// draw it!
			drawCanvas.drawPath(theStroke.path, theStroke.paint);
			invalidate();
			ret = true;
		}
		return ret;
	}

    @Override
    public boolean onTouchEvent(MotionEvent event) {
		float touchX = event.getX();
      	float touchY = event.getY();

    	switch (event.getAction()) {
		// user touches a location, move there
		case MotionEvent.ACTION_DOWN:
			currentStroke = new Stroke();
    		drawPath.moveTo(touchX, touchY);
    		break;
		// draw line when move
		case MotionEvent.ACTION_MOVE:
    		drawPath.lineTo(touchX, touchY);
    		break;
		// user releases the touch
		case MotionEvent.ACTION_UP:
    		drawCanvas.drawPath(drawPath, drawPaint);
			invalidate();

			// keep track of the last MAX strokes if we're not erasing.
			if (erase == false) {
				currentStroke.setPaint(drawPaint);
				currentStroke.setColor(paintColor);
				currentStroke.setPath(drawPath);
				currentStroke.setBrushSize(brushSize);

				if (undoStrokes.size() < MAX) {
					undoStrokes.add(currentStroke);
				} else {
					// shift the first stroke off the undolist. We only keep track of MAX strokes.
					ArrayList<Stroke> tmps = new ArrayList<Stroke>(undoStrokes.subList(1, MAX));
					undoStrokes = tmps;
					undoStrokes.add(currentStroke);
				}
			}
			drawPath = new Path();
			drawPath.reset();

    		break;
		default:
    		return false;
		}
		invalidate();
		return true;

    }
	public void setBrushSize(float newSize) {
		brushSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				newSize, getResources().getDisplayMetrics());
		drawPaint.setStrokeWidth(brushSize);
	}

	public void setLastBrushSize(float lastSize) {
		lastBrushSize = lastSize;
	}

	public float getLastBrushSize() {
		return lastBrushSize;
	}

	public void setColor(String newColor) {
		invalidate();
		paintColor = Color.parseColor(newColor);
		drawPaint.setColor(paintColor);
	}

	public int getColor () {
		return paintColor;
	}

	public void setErase(boolean isErase) {
		erase = isErase;

		if(erase)
			drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
		else
			drawPaint.setXfermode(null);
	}

	public void startNew(String path){

		undoneStrokes = new ArrayList<Stroke>();
		undoneStrokes.clear();

		undoStrokes = new ArrayList<Stroke>();
		undoStrokes.clear();

		if (path == null) {
			drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);

		} else {
			Bitmap workingBitmap = 	BitmapFactory.decodeFile(path);
			Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
			drawCanvas.drawBitmap(mutableBitmap, 0, 0, canvasPaint);
			setImageBitmap(mutableBitmap);

		}
		invalidate();
		setErase(false);
	}

}


text:
class FRT_Supervisor;
class FNET_Transport;

namespace search::common { class FileHeaderContext; }
namespace search::transactionlog {

class TransLogServerExplorer;
class Domain;

class TransLogServer : private FRT_Invokable, public document::Runnable, public WriterFactory
{
public:
    friend class TransLogServerExplorer;
    using SP = std::shared_ptr<TransLogServer>;
    using DomainSP = std::shared_ptr<Domain>;
    TransLogServer(FNET_Transport & transport, const vespalib::string &name, int listenPort, const vespalib::string &baseDir,
                   const common::FileHeaderContext &fileHeaderContext, const DomainConfig & cfg, size_t maxThreads);
    TransLogServer(FNET_Transport & transport, const vespalib::string &name, int listenPort, const vespalib::string &baseDir,
                   const common::FileHeaderContext &fileHeaderContext, const DomainConfig & cfg);
    TransLogServer(FNET_Transport & transport, const vespalib::string &name, int listenPort, const vespalib::string &baseDir,
                   const common::FileHeaderContext &fileHeaderContext);
    ~TransLogServer() override;
    DomainStats getDomainStats() const;
    std::shared_ptr<Writer> getWriter(const vespalib::string & domainName) const override;
    TransLogServer & setDomainConfig(const DomainConfig & cfg);

private:
    bool onStop() override;
    void run() override;
    void exportRPC(FRT_Supervisor & supervisor);
    void relayToThreadRPC(FRT_RPCRequest *req);

    void createDomain(FRT_RPCRequest *req);
    void deleteDomain(FRT_RPCRequest *req);
    void openDomain(FRT_RPCRequest *req);
    void listDomains(FRT_RPCRequest *req);

    void domainStatus(FRT_RPCRequest *req);
    void domainCommit(FRT_RPCRequest *req);
    void domainSessionRun(FRT_RPCRequest *req);
    void domainPrune(FRT_RPCRequest *req);
    void domainVisit(FRT_RPCRequest *req);
    void domainSessionClose(FRT_RPCRequest *req);
    void domainSync(FRT_RPCRequest *req);

    std::vector<vespalib::string> getDomainNames();
    DomainSP findDomain(vespalib::stringref name) const;
    vespalib::string dir()        const { return _baseDir + "/" + _name; }
    vespalib::string domainList() const { return dir() + "/" + _name + ".domains"; }

    using DomainList = std::map<vespalib::string, DomainSP >;
    using ReadGuard = std::shared_lock<std::shared_mutex>;
    using WriteGuard = std::unique_lock<std::shared_mutex>;

    vespalib::string                    _name;
    vespalib::string                    _baseDir;
    DomainConfig                        _domainConfig;
    vespalib::ThreadStackExecutor       _executor;
    std::unique_ptr<FastOS_ThreadPool>  _threadPool;
    std::unique_ptr<FRT_Supervisor>     _supervisor;
    DomainList                          _domains;
    mutable std::shared_mutex           _domainMutex;;          // Protects _domains
    std::condition_variable             _domainCondition;
    std::mutex                          _fileLock;      // Protects the creating and deleting domains including file system operations.
    document::Queue<FRT_RPCRequest *>   _reqQ;
    const common::FileHeaderContext    &_fileHeaderContext;
    std::atomic<bool>                   _closed;
};

}


text:
<?php
/**
 *  * Created by mtils on 27.11.2021 at 08:42.
 **/

namespace Ems\Model;

use DateTime;

use function method_exists;
use function substr;

/**
 * This is class is used to generate default or update values for orm objects.
 */
class Generator
{
    /**
     * Create current timestamp
     */
    public const NOW = '$Now$';

    /**
     * Generate a value. Typically, use one of the constant values.
     *
     * @param string $name
     * @param array $args (optional)
     * @return mixed
     */
    public function make(string $name, array $args=[])
    {
        $method = $this->method($name);
        return $this->{$method}($args);
    }

    /**
     * Generate a value if the generator exists, otherwise return the passed value.
     * This is handy if you allow to store a value default that can be a generated
     * or static value.
     *
     * @param string $name
     * @param array $args
     * @return mixed
     */
    public function makeOrReturn(string $name, array $args=[])
    {
        $method = $this->method($name);
        if (method_exists($this, $method)) {
            return $this->{$method}($args);
        }
        return $name;
    }

    /**
     * @return DateTime
     */
    public function generateNow() : DateTime
    {
        return new DateTime();
    }

    /**
     * Check if a generation method exists.
     *
     * @param string $name
     * @return bool
     */
    public function exists(string $name) : bool
    {
        return method_exists($this, $this->method($name));
    }

    protected function method(string $name)
    {
        return 'generate' . substr($name, 1, -1);
    }
}


text:
package com.osdu.model.type.manifest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.osdu.model.type.wp.WorkProductComponent;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;

@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true, exclude = {"files"})
@ToString(callSuper = true, exclude = {"files"})
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({ "files" })
public class ManifestWpc extends WorkProductComponent {

  @JsonProperty("AssociativeID")
  String associativeId;

  @JsonProperty("FileAssociativeIDs")
  List<String> fileAssociativeIds;

  List<ManifestFile> files;

}


text:
package org.jasig.portal.groups;

/**
 * Factory interface for creating an IEntityStore.
 * @author Dan Ellentuck
 * @version $Revision$
 */
public interface IEntityStoreFactory {
/**
 *
 */
public IEntityStore newEntityStore() throws GroupsException;
}


text:
* Removed Squiz.Commenting.VariableComment.MissingVar so we can still have
  plain comments.

## 2.8.0

* Removed the requirement for the Squiz.Commenting.FunctionComment.Missing and
  Squiz.Commenting.VariableComment.Missing sniffs because native type hinting
  often makes their use redundant.

## 2.7.1

* Dependency update.

## 2.7.0

* Removed PEAR.WhiteSpace.ScopeIndent because it conflicts with the desired
  settings for Squiz.ControlStructures.SwitchDeclaration.
* Removed Squiz.ControlStructures.SwitchDeclaration.BreakIndent because it
  expects the same indent level as the case itself.

## 2.6.0

* Removed PEAR.Commenting.ClassComment because it's redundant when you're
  already using PSR-4.
* Removed Squiz.PHP.DisallowBooleanStatement because I sometimes like to
  do that.
* Fixed some unit tests.

## 2.5.2

* Removed redundant sniff Generic.Files.EndFileNewline.

## 2.5.1

* Added progress indicator and cache arguments to the default configuration.

## 2.5.0

* Removed PEAR.NamingConventions.ValidVariableName.PrivateNoUnderscore because
  it should have never been there.
* Removed Squiz.Commenting.FunctionComment.SpacingAfterParamType and
  Squiz.Commenting.FunctionComment.SpacingAfterParamName because they're really
  counterproductive when using the new compound types.

## 2.4.0

* Removed Squiz.Commenting.FunctionComment.MissingParamTag and
  Squiz.Commenting.FunctionComment.MissingReturn because this
  functionality now should be provided by native typehints.

## 2.3.0

* Added new Generic sniffs.

## 2.2.0

* Added new PSR12 sniffs.

## 2.1.0

* Updated Ork.Formatting.AlphabeticalPropertyNames and
  Ork.Formatting.AlphabeticalMethodNames to be case insensitive.
* Added unit tests.

## 2.0.12

* Removed Squiz.WhiteSpace.ObjectOperatorSpacing.Before sniff to allow
  stacking chained method calls over multiple lines.

## 2.0.11

* Removed conflicting Squiz.ControlStructures.ElseIfDeclaration sniff.

## 2.0.10

* Resolved issue #1.

## 2.0.9

* Removed redundant Squiz.Operators.ComparisonOperatorUsage sniff.

## 2.0.8

* Removed Squiz.Arrays.ArrayDeclaration.DoubleArrowNotAligned sniff.

## 2.0.7

* Removed some redundant tests.

## 2.0.6

* Updated to PHPCS v3.4.0.

## 2.0.5

* Updated to PHPCS v3.2.3.

## 2.0.4

* Updated Ork.PHP.DisallowComparisonAssignment to allow assignments using the
  null coalesce operator.

## 2.0.3

* Added Ork.Operators.ComparisonOperatorUsageSniff to override
  Squiz.Operators.ComparisonOperatorUsageSniff and allow ternary shortcut
  operator.

## 2.0.2

* Minor tweaks in new sniffs.

## 2.0.1

* Minor tweaks in new sniffs.

## 2.0.0

* Updated to work with PHPCS v3.

## 1.4.1

* AlphabeticalPropertyNameSniff now ignores method parameters.

## 1.4.0

* Added unit test scaffolding and a few tests.
* Made custom sniff code comply with PHPCS standard.
* Renamed AlphabeticalFunctionNameSniff to AlphabeticalMethodNamesSniff.
* Renamed AlphabeticalPropertyNameSniff to AlphabeticalPropertyNamesSniff.

## 1.3.5

* Added Ork.Formatting.MultiLineAssignment.

## 1.3.4

* Updated Ork.PHP.DisallowComparisonAssignment to allow comparisons when
  explicitly cast to boolean.

## 1.3.3

* Removed use of Squiz.Objects.ObjectInstantiation.NotAssigned.

## 1.3.2

* Removed use of PEAR.Functions.FunctionCallSignature.

## 1.3.1

* Removed use of Squiz.Formatting.OperatorBracket.

## 1.3.0

* Added a custom version of PEAR.ControlStructures.MultiLineCondition to handle
  preferred formatting for multi-line conditionals.
* Added a custom version of PSR2.WhiteSpace.ControlStructureSpacing to allow
  newline immediately after open for multi-line conditionals.

## 1.2.0

* Renamed Ork.Formatting.AlphabeticalVariableName to
 Ork.Formatting.AlphabeticalPropertyName.
* Updated Ork.Formatting.AlphabeticalPropertyName so that it ignores variables
  outside classes/interfaces/traits.
* Added a custom version of Squiz.PHP.DisallowComparisonAssignment to address a
  bug they won't acknowledge.

## 1.1.0

* Added Ork.Commenting.FileComment.
* Added Ork.Formatting.AlphabeticalFunctionName.
* Added Ork.Formatting.AlphabeticalVariableName.

## 1.0.0

* Initial commit.


text:
local yaml = require('yaml')
local core = require('core').new({listen='*:3112'})
local util = require('util')
--local shard = require('shard')

local methods = {
    ['POST'] = {
      ['/add/user'] = core.add_user,
      ['/add/operation'] = core.add_operation,
    },
    ['GET'] = {
      ['/get/operations'] = core.get_operations_for_period,
      ['/get/account/operations'] = core.get_last_n_operations,
      ['/get/account/balance'] = core.get_balance,
      ['/get/stat'] = core.get_stat,
    }
}

local function get_method_name(req)
  local r = ''
  local m = util.split(req.uri, '?')[1]
  for _, k in pairs(util.split(m, '/')) do
    if _ ~= 1 then
      r = r .. '/' .. k
    end
  end
  return r
end

--
-- Entry point
--
function api(req, ...)

  local method_name = get_method_name(req)
  local requested_methods = methods[req.method][method_name]
  if req.method == 'GET' then
    return requested_methods(core, req.args)
  elseif req.method == 'POST' then
    return requested_methods(core, ...)
  end

  error('Not allowed!')
end


text:
Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound',
	waitOn: function () {
		if (Meteor.user()) {

			var userIds = _.map(Meteor.user().profile.friends, function (f) {
				return f._id;
			});

			var subscriptions = _.map(userIds, function(fId) {
				return Meteor.subscribe('recentChats', fId);
			});

			subscriptions.push(Meteor.subscribe('friends', userIds));

			return subscriptions;
		}
	}
});

Router.route('/', function() {
	if (Meteor.user()) {
		this.redirect('contacts');
	} else {
		this.render('welcome');
	}
}, {name: 'home'});

Router.route('/contacts', function() {
	this.render('myContacts');
});

Router.route('/account', function() {
	this.render('myAccount');
});

Router.route('/changepwd', function() {
	this.render('changePwd');
});

Router.route('/change-avatar', function() {
	this.render('changeAvatar');
});

Router.route('/send-file/:friendId', function() {
	this.render('sendFile');
});

Router.route('/logout', function(){
	if (Meteor.user()) {
		this.render('loading');
	} else {
		this.render('welcome');
	}
});

Router.route('/recent-chats', {
	name: 'recentChats',
	template: 'recentChats',
	data: function() {
		if (Meteor.user()) {
			var friends = _.map(Meteor.user().profile.friends, function (f) {
				return f._id;
			});

			var recentChats = [];

			for (var i = 0; i < friends.length; i++) {
				var room = createRoom(Meteor.userId(), friends[i]);
				var message = Messages.findOne({room: room}, {sort: {time: -1}});

				if (message)
					recentChats.push({room: room, message:message});
			}

			//newest first
			recentChats = _.sortBy(recentChats, function(chat){
				return -1 * chat.message.time;
			});

			return {recentChats: recentChats};
		}
	},

	action: function() {
		this.render('recentChats');
	}
});

Router.route('/profile/:username',{
	name: 'profileView',
	template: 'profileView',

	data: function() {
		var username = this.params.username;
		return {user: Meteor.users.findOne({username: username})};
	},

	action: function() {
		if (this.data().user) {
			this.render('profileView');
		} else {
			this.redirect('home');
		}
	}
});

Router.route('/chat/:friend/:limit?', {
	name: 'chat',
	controller: 'ChatController',
	template: 'chat'
});

ChatController = RouteController.extend({
	template: 'chat',
	increment: 15,
	chatLimit: function() {
		return parseInt(this.params.limit) || this.increment;
	},
	findOptions: function() {
		return {sort: {time: 1}};
	},
	room: function() {
		return createRoom(Meteor.userId(), this.params.friend);
	},
	subscriptions: function() {
		this.chatSub = Meteor.subscribe('chat', this.params.friend, this.chatLimit());
	},
	messages: function() {
		return Messages.find({room: this.room()}, this.findOptions());
	},
	data: function() {
		var hasMore = this.messages().count() === this.chatLimit();
		var olderChats = this.route.path({friend: this.params.friend, limit: this.chatLimit() + this.increment});
		return {
			room: this.room(),
			messages: this.messages(),
			ready: this.chatSub.ready(),
			olderChats: hasMore ? olderChats : null
		};
	}
});

Router.route('/radius', function(){
	this.render('radius');
});

var requireLogin = function() {
	if (!Meteor.user()) {
		if (Meteor.loggingIn()) {
			this.render('loading');
		} else {
			this.render('welcome');
		}
	} else {
		this.next();
	}
};

Router.onBeforeAction(requireLogin, {except: ['account']});


text:
title: The curse of dimensionality
tags: ["R", "python", "machine learning", "programming"]
comments: true
---

## Introduction

Based on Peter Norvigs's MSRI talk
[What to demand from a Scientific Computing Language](http://www.msri.org/summer_schools/556/schedules/4197)
(22:50): 'if you have high dimensional data, then almost all the data
are outliers'. He showed a very elegant piece of python code to
illustrate it; below is an R implementation.

<!--more-->

## Implementation

{% gist lgatto/6479628cfbce942b5def curse-of-dimensionality.py %}

The simulation generates `N` points in hypercubes of `d` dimensions
and counts how many of those points are outliers, defined as being in
the 1% outer shell of the space. In 1 dimension, we have 1% of the
uniformely distributed points that are outliers. In 50 dimension,
there are already 60% of the points that are outliers; in 100
dimensions, almost 90% of the points are outliers.

{% gist lgatto/6479628cfbce942b5def curse-of-dimensionality.R %}

## Result

![Curse of dimensionality](/images/curse-of-dimensionality.png)


text:
package io.flic.lib;

/**
 * FlicButtonCallback
 *
 * Callbacks for button updates. You should extend this class and implement the callbacks you want.
 */
public class FlicButtonCallback {
	/**
	 * Called when the Bluetooth connection has just been started.
	 * It's not ready for use yet however - {@link FlicButtonCallback#onConnectionCompleted(FlicButton)} will be called when ready.
	 *
	 * @param button The button
	 */
	public void onConnectionStarted(FlicButton button) {}

	/**
	 * Called if there was a problem establishing a Bluetooth connection to the button. Happens very rarely.
	 *
	 * @param button The button
	 * @param status A Bluetooth GATT status.
	 */
	public void onConnectionFailed(FlicButton button, int status) {}

	/**
	 * Called when the Bluetooth connection was disconnected, for example if the button becomes out of range or the user manually disconnecting this button in the Flic Application.
	 *
	 * @param button The button
	 */
	public void onDisconnect(FlicButton button) {}

	/**
	 * Called when the connection to the button has been established and is ready to use.
	 *
	 * @param button The button
	 */
	public void onConnectionCompleted(FlicButton button) {}

	/**
	 * Called as a result of {@link FlicButton#readRemoteRSSI()}.
	 *
	 * @param button The button
	 * @param rssi RSSI value for the remote device
	 * @param status 0 if the RSSI was read successfully
	 */
	public void onReadRemoteRSSI(FlicButton button, int rssi, int status) {}

	/**
	 * Called when the button was pressed or released.
	 *
	 * @param button The button
	 * @param wasQueued If the event was locally queued in the button because it was disconnected. After the connection is completed, the event will be sent with this parameter set to true.
	 * @param timeDiff If the event was queued, the timeDiff will be the number of seconds since the event happened.
	 * @param isUp True if up, else false
	 * @param isDown True if down, else false
	 */
	public void onButtonUpOrDown(FlicButton button, boolean wasQueued, int timeDiff, boolean isUp, boolean isDown) {}

	/**
	 * Used for the scenario where you want to listen on button click and hold.
	 *
	 * @param button The button
	 * @param wasQueued If the event was locally queued in the button because it was disconnected. After the connection is completed, the event will be sent with this parameter set to true.
	 * @param timeDiff If the event was queued, the timeDiff will be the number of seconds since the event happened.
	 * @param isClick True if click, else false
	 * @param isHold True if hold, else false
	 */
	public void onButtonClickOrHold(FlicButton button, boolean wasQueued, int timeDiff, boolean isClick, boolean isHold) {}

	/**
	 * Used for the scenario where you want to listen on single click and double click.
	 * Single clicks might be delayed for up to 0.5 seconds because we can't be sure if it was rather a double click or not until then.
	 *
	 * @param button The button
	 * @param wasQueued If the event was locally queued in the button because it was disconnected. After the connection is completed, the event will be sent with this parameter set to true.
	 * @param timeDiff If the event was queued, the timeDiff will be the number of seconds since the event happened.
	 * @param isSingleClick True if single click, else false
	 * @param isDoubleClick True if double click, else false
	 */
	public void onButtonSingleOrDoubleClick(FlicButton button, boolean wasQueued, int timeDiff, boolean isSingleClick, boolean isDoubleClick) {}

	/**
	 * Used for the scenario where you want to listen on single click, double click and hold.
	 * Single clicks might be delayed for up to 0.5 seconds because we can't be sure if it was rather a double click or not until then.
	 *
	 * @param button The button
	 * @param wasQueued If the event was locally queued in the button because it was disconnected. After the connection is completed, the event will be sent with this parameter set to true.
	 * @param timeDiff If the event was queued, the timeDiff will be the number of seconds since the event happened.
	 * @param isSingleClick True if single click, else false
	 * @param isDoubleClick True if double click, else false
	 * @param isHold True if hold, else false
	 */
	public void onButtonSingleOrDoubleClickOrHold(FlicButton button, boolean wasQueued, int timeDiff, boolean isSingleClick, boolean isDoubleClick, boolean isHold) {}

	/**
	 * Called when the button was removed in the Flic App, or when the user disconnected this app from the button in the Flic App (if so the button can be grabbed again as usual).
	 * This object cannot be used any more once this method has returned.
	 *
	 * @param button The button
	 */
	public void onButtonRemoved(FlicButton button) {}
}


text:
<?php

namespace Abc\Bundle\JobBundle\Annotation;

/**
 * @Annotation
 * @Target({"METHOD"})
 * @author Hannes Schulz <hannes.schulz@aboutcoders.com>
 */
class ReturnType
{
    /**
     * @Required
     * @var string
     */
    public $type;

    /**
     * @var array
     */
    public $options = array();
}


text:
from django.db import connection
from django.db.backends.util import truncate_name
from django.db.models.fields import Field # Django base Field class
from django.contrib.gis.db.backend.util import gqn
from django.contrib.gis.db.backend.oracle.query import TRANSFORM

# Quotename & geographic quotename, respectively.
qn = connection.ops.quote_name

class OracleSpatialField(Field):
    """
    The backend-specific geographic field for Oracle Spatial.
    """

    empty_strings_allowed = False

    def __init__(self, extent=(-180.0, -90.0, 180.0, 90.0), tolerance=0.05, **kwargs):
        """
        Oracle Spatial backend needs to have the extent -- for projected coordinate
        systems _you must define the extent manually_, since the coordinates are
        for geodetic systems.  The `tolerance` keyword specifies the tolerance
        for error (in meters), and defaults to 0.05 (5 centimeters).
        """
        # Oracle Spatial specific keyword arguments.
        self._extent = extent
        self._tolerance = tolerance
        # Calling the Django field initialization.
        super(OracleSpatialField, self).__init__(**kwargs)

    def _add_geom(self, style, db_table):
        """
        Adds this geometry column into the Oracle USER_SDO_GEOM_METADATA
        table.
        """

        # Checking the dimensions.
        # TODO: Add support for 3D geometries.
        if self._dim != 2:
            raise Exception('3D geometries not yet supported on Oracle Spatial backend.')

        # Constructing the SQL that will be used to insert information about
        # the geometry column into the USER_GSDO_GEOM_METADATA table.
        meta_sql = style.SQL_KEYWORD('INSERT INTO ') + \
                   style.SQL_TABLE('USER_SDO_GEOM_METADATA') + \
                   ' (%s, %s, %s, %s)\n  ' % tuple(map(qn, ['TABLE_NAME', 'COLUMN_NAME', 'DIMINFO', 'SRID'])) + \
                   style.SQL_KEYWORD(' VALUES ') + '(\n    ' + \
                   style.SQL_TABLE(gqn(db_table)) + ',\n    ' + \
                   style.SQL_FIELD(gqn(self.column)) + ',\n    ' + \
                   style.SQL_KEYWORD("MDSYS.SDO_DIM_ARRAY") + '(\n      ' + \
                   style.SQL_KEYWORD("MDSYS.SDO_DIM_ELEMENT") + \
                   ("('LONG', %s, %s, %s),\n      " % (self._extent[0], self._extent[2], self._tolerance)) + \
                   style.SQL_KEYWORD("MDSYS.SDO_DIM_ELEMENT") + \
                   ("('LAT', %s, %s, %s)\n    ),\n" % (self._extent[1], self._extent[3], self._tolerance)) + \
                   '    %s\n  );' % self._srid
        return meta_sql

    def _geom_index(self, style, db_table):
        "Creates an Oracle Geometry index (R-tree) for this geometry field."

        # Getting the index name, Oracle doesn't allow object
        # names > 30 characters.
        idx_name = truncate_name('%s_%s_id' % (db_table, self.column), 30)

        sql = style.SQL_KEYWORD('CREATE INDEX ') + \
              style.SQL_TABLE(qn(idx_name)) + \
              style.SQL_KEYWORD(' ON ') + \
              style.SQL_TABLE(qn(db_table)) + '(' + \
              style.SQL_FIELD(qn(self.column)) + ') ' + \
              style.SQL_KEYWORD('INDEXTYPE IS ') + \
              style.SQL_TABLE('MDSYS.SPATIAL_INDEX') + ';'
        return sql

    def post_create_sql(self, style, db_table):
        """
        Returns SQL that will be executed after the model has been
        created.
        """
        # Getting the meta geometry information.
        post_sql = self._add_geom(style, db_table)

        # Getting the geometric index for this Geometry column.
        if self._index:
            return (post_sql, self._geom_index(style, db_table))
        else:
            return (post_sql,)

    def db_type(self):
        "The Oracle geometric data type is MDSYS.SDO_GEOMETRY."
        return 'MDSYS.SDO_GEOMETRY'

    def get_placeholder(self, value):
        """
        Provides a proper substitution value for Geometries that are not in the
        SRID of the field.  Specifically, this routine will substitute in the
        SDO_CS.TRANSFORM() function call.
        """
        if value is None:
            return '%s'
        elif value.srid != self._srid:
            # Adding Transform() to the SQL placeholder.
            return '%s(SDO_GEOMETRY(%%s, %s), %s)' % (TRANSFORM, value.srid, self._srid)
        else:
            return 'SDO_GEOMETRY(%%s, %s)' % self._srid


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

<document xmlns="http://maven.apache.org/XDOC/2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">

  <properties>
    <title>Talks and Screencasts</title>
    <author email="roland@jolokia.org">Roland Huss</author>
  </properties>

        The slides to my talk for the small but very fine JayDay 2013 are
        online.
        These are "implemented" in JavaScript including live demos, where the JavaScript can be directly inserted
        in the browser (tested with Chrome & Firefox). For the sample code, simply push the blue buttons at the
        bottom of a demo slide.

        Here's my talk from Devoxx 2011 which is now freely
        available on Parleys. Well, as explained here I was quite nervous on my first Devoxx
        talk, so please concentrate on the facts and fade out the speaker ;-)

        <object width="480" height="780"><param name="movie" value="https://www.parleys.com/dist/share/parleysshare.swf"></param><param name="allowFullScreen" value="true"></param><param name="wmode" value="direct"></param><param name="bgcolor" value="#222222"></param><param name="flashVars" value="sv=true&pageId=2864" ></param><embed src="http://www.parleys.com/dist/share/parleysshare.swf" type="application/x-shockwave-flash" flashVars="sv=true&pageId=2864" allowfullscreen="true" bgcolor="#222222" width="480" height="780"></embed></object>

The slides with included videos are also available at Slideshare:

        This talk
        from the Open Source Monitoring Conference
        was given 2011 in Nuremberg.
        It focuses on the integration of
        Jolokia within Nagios and was given in German. I was the
        'Java guy' this year. It was my third time at OSMC and it
        was as always a big pleasure to meet the Nagios folks and
        catering was phantastic, too ;-)

        This screencast demos the cousin of j4psh, osgish an Perl bases OSGi shell which uses Jolokia and Aries for
        managing OSGi container. It works well, but is still yet some sort of prototype. The screencast is cool nevertheless ;-)

Osgish - A OSGi Shell from Roland Huss on Vimeo.

</document>


text:
using System;
using System.Linq.Expressions;
using Benchmark.DataSources;
using Benchmark.Models;

namespace Benchmark.Tests
{
    public class TakeTopTest<T, TResult> : ITest<T>
    {
        public string Name { get; }
        public int Count { get; }
        public Func<T, TResult> SelectorFunc { get; }
        public Expression<Func<T, TResult>> SelectorExpr { get; }

        public int TestCount => 1;

        public TakeTopTest(string name, Expression<Func<T, TResult>> selector, int count)
        {
            Name = $"TakeTop({name})";
            Count = count;
            SelectorExpr = selector;
            SelectorFunc = selector.Compile();
        }

        public void Execute(IDataSource<T> source)
            => source.TakeTop(SelectorFunc, SelectorExpr, Count);
        public object ExecuteResult(IDataSource<T> source)
            => source.TakeTop(SelectorFunc, SelectorExpr, Count);
    }
}


text:
package com.github.gwtd3.demo.client.pageobjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.Color;

public class DemoDragMultiple extends AbstractDemoPage<DemoDragMultiple> {

	protected DemoDragMultiple(final WebDriver driver, final DemoApplication parent) {
		super(parent);
	}

	public static class Circle extends ElementPageObject<DemoDragMultiple> {

		public Circle(final DemoDragMultiple parent, final WebElement element) {
			super(parent, element);
		}

		/**
		 * @return the cx element of any
		 */
		public double cx() {
			return Double.parseDouble(element.getAttribute("cx"));
		}

		public double cy() {
			return Double.parseDouble(element.getAttribute("cy"));
		}

		public Color fillColor() {
			return getAttributeAsColor("fill");
		}
	}

	public Circle getCircle(final int i) {
		// generate something like circle:first-child + circle + circle
		return new Circle(this, findAll(By.tagName("circle")).get(i));
	}

}


text:
import datetime
from sqlalchemy import Column, Integer, String, DateTime, Index
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine

Base = declarative_base()

class Comment(Base):
    __tablename__ = 'comment'
    commentid = Column(Integer, primary_key=True)
    id = Column(String(100), nullable=False)
    nickname = Column(String(20), default="")
    url = Column(String(100), default="")
    content = Column(String(250), nullable=False)
    created_date = Column(DateTime, default=datetime.datetime.utcnow)

Index('index_comment_id', Comment.id)


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.test.internal.engine.groups.validationordergenerator;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author Emmanuel Bernard
 */
@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = ZipCodeCoherenceValidator.class)
public @interface ZipCodeCoherenceChecker {
	String message() default "{validator.zipCodeCoherenceChecker}";

	Class<?>[] groups() default { };
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-figures/richards-franklin-snyder-1849-1934" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/richards-franklin-snyder-1849-1934</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Richards, Franklin Snyder 1849-1934</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/richards-franklin-snyder-1849-1934</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/richards-franklin-snyder-1849-1934</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "C:/Program Files (x86)/Assimp")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "Release")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()

if("${CMAKE_INSTALL_COMPONENT}" STREQUAL "assimp-bin" OR NOT CMAKE_INSTALL_COMPONENT)
  if("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Dd][Ee][Bb][Uu][Gg])$")
    file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE EXECUTABLE FILES "E:/Projects/fispToos/assimp/Build/tools/assimp_cmd/Debug/assimp.exe")
  elseif("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$")
    file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE EXECUTABLE FILES "E:/Projects/fispToos/assimp/Build/tools/assimp_cmd/Release/assimp.exe")
  elseif("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Mm][Ii][Nn][Ss][Ii][Zz][Ee][Rr][Ee][Ll])$")
    file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE EXECUTABLE FILES "E:/Projects/fispToos/assimp/Build/tools/assimp_cmd/MinSizeRel/assimp.exe")
  elseif("${CMAKE_INSTALL_CONFIG_NAME}" MATCHES "^([Rr][Ee][Ll][Ww][Ii][Tt][Hh][Dd][Ee][Bb][Ii][Nn][Ff][Oo])$")
    file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/bin" TYPE EXECUTABLE FILES "E:/Projects/fispToos/assimp/Build/tools/assimp_cmd/RelWithDebInfo/assimp.exe")
  endif()
endif()


text:
"""
This is the default range matcher.
"""

import logging

HAS_RANGE = False
try:
    import seco.range

    HAS_RANGE = True
except ImportError:
    pass

log = logging.getLogger(__name__)

def match(tgt, opts=None, minion_id=None):
    """
    Matches based on range cluster
    """
    if not opts:
        opts = __opts__
    if HAS_RANGE:
        range_ = seco.range.Range(opts["range_server"])
        try:
            return opts["grains"]["fqdn"] in range_.expand(tgt)
        except seco.range.RangeException as exc:
            log.debug("Range exception in compound match: %s", exc)
            return False
    return False