text:
package com.facebook.buck.cxx;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.MacroException;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.MetadataProvidingDescription;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;

import java.nio.file.Path;

public class CxxTestDescription implements
    Description<CxxTestDescription.Arg>,
    Flavored,
    ImplicitDepsInferringDescription<CxxTestDescription.Arg>,
    MetadataProvidingDescription<CxxTestDescription.Arg> {

  private static final BuildRuleType TYPE = BuildRuleType.of("cxx_test");
  private static final CxxTestType DEFAULT_TEST_TYPE = CxxTestType.GTEST;

  private final CxxBuckConfig cxxBuckConfig;
  private final CxxPlatform defaultCxxPlatform;
  private final FlavorDomain<CxxPlatform> cxxPlatforms;
  private final Optional<Long> defaultTestRuleTimeoutMs;

  public CxxTestDescription(
      CxxBuckConfig cxxBuckConfig,
      CxxPlatform defaultCxxPlatform,
      FlavorDomain<CxxPlatform> cxxPlatforms,
      Optional<Long> defaultTestRuleTimeoutMs) {
    this.cxxBuckConfig = cxxBuckConfig;
    this.defaultCxxPlatform = defaultCxxPlatform;
    this.cxxPlatforms = cxxPlatforms;
    this.defaultTestRuleTimeoutMs = defaultTestRuleTimeoutMs;
  }

  @Override
  public BuildRuleType getBuildRuleType() {
    return TYPE;
  }

  @Override
  public Arg createUnpopulatedConstructorArg() {
    return new Arg();
  }

  @Override
  public <A extends Arg> BuildRule createBuildRule(
      TargetGraph targetGraph,
      BuildRuleParams inputParams,
      final BuildRuleResolver resolver,
      final A args) throws NoSuchBuildTargetException {
    Optional<StripStyle> flavoredStripStyle =
        StripStyle.FLAVOR_DOMAIN.getValue(inputParams.getBuildTarget());
    final BuildRuleParams params =
        CxxStrip.removeStripStyleFlavorInParams(inputParams, flavoredStripStyle);

    Optional<CxxPlatform> platform = cxxPlatforms.getValue(params.getBuildTarget());
    CxxPlatform cxxPlatform = platform.or(defaultCxxPlatform);
    SourcePathResolver pathResolver = new SourcePathResolver(resolver);

    if (params.getBuildTarget().getFlavors()
          .contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
      return CxxDescriptionEnhancer.createCompilationDatabase(
          params,
          resolver,
          pathResolver,
          cxxBuckConfig,
          cxxPlatform,
          args);
    }

    if (params.getBuildTarget().getFlavors()
          .contains(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)) {
      return CxxDescriptionEnhancer.createUberCompilationDatabase(
          platform.isPresent() ?
              params :
              params.withFlavor(cxxPlatform.getFlavor()),
          resolver
      );
    }

    // Generate the link rule that builds the test binary.
    final CxxLinkAndCompileRules cxxLinkAndCompileRules =
        CxxDescriptionEnhancer.createBuildRulesForCxxBinaryDescriptionArg(
            params,
            resolver,
            cxxBuckConfig,
            cxxPlatform,
            args,
            flavoredStripStyle);

    // Construct the actual build params we'll use, notably with an added dependency on the
    // CxxLink rule above which builds the test binary.
    BuildRuleParams testParams =
        params.appendExtraDeps(cxxLinkAndCompileRules.executable.getDeps(pathResolver));
    testParams = CxxStrip.restoreStripStyleFlavorInParams(testParams, flavoredStripStyle);

    // Supplier which expands macros in the passed in test environment.
    Supplier<ImmutableMap<String, String>> testEnv =
        new Supplier<ImmutableMap<String, String>>() {
          @Override
          public ImmutableMap<String, String> get() {
            return ImmutableMap.copyOf(
                Maps.transformValues(
                    args.env.or(ImmutableMap.<String, String>of()),
                    CxxDescriptionEnhancer.MACRO_HANDLER.getExpander(
                        params.getBuildTarget(),
                        params.getCellRoots(),
                        resolver)));
          }
        };

    // Supplier which expands macros in the passed in test arguments.
    Supplier<ImmutableList<String>> testArgs =
        new Supplier<ImmutableList<String>>() {
          @Override
          public ImmutableList<String> get() {
            return FluentIterable.from(args.args.or(ImmutableList.<String>of()))
                .transform(
                    CxxDescriptionEnhancer.MACRO_HANDLER.getExpander(
                        params.getBuildTarget(),
                        params.getCellRoots(),
                        resolver))
                .toList();
          }
        };

    Supplier<ImmutableSortedSet<BuildRule>> additionalDeps =
        new Supplier<ImmutableSortedSet<BuildRule>>() {
          @Override
          public ImmutableSortedSet<BuildRule> get() {
            ImmutableSortedSet.Builder<BuildRule> deps = ImmutableSortedSet.naturalOrder();

            // It's not uncommon for users to add dependencies onto other binaries that they run
            // during the test, so make sure to add them as runtime deps.
            deps.addAll(
                Sets.difference(
                    params.getDeps(),
                    cxxLinkAndCompileRules.getBinaryRule().getDeps()));

            // Add any build-time from any macros embedded in the `env` or `args` parameter.
            for (String part :
                Iterables.concat(
                    args.args.or(ImmutableList.<String>of()),
                    args.env.or(ImmutableMap.<String, String>of()).values())) {
              try {
                deps.addAll(
                    CxxDescriptionEnhancer.MACRO_HANDLER.extractBuildTimeDeps(
                        params.getBuildTarget(),
                        params.getCellRoots(),
                        resolver,
                        part));
              } catch (MacroException e) {
                throw new HumanReadableException(
                    e,
                    "%s: %s",
                    params.getBuildTarget(),
                    e.getMessage());
              }
            }

            return deps.build();
          }
        };

    CxxTest test;

    CxxTestType type = args.framework.or(getDefaultTestType());
    switch (type) {
      case GTEST: {
        test = new CxxGtestTest(
            testParams,
            pathResolver,
            cxxLinkAndCompileRules.getBinaryRule(),
            cxxLinkAndCompileRules.executable,
            testEnv,
            testArgs,
            FluentIterable.from(args.resources.or(ImmutableSortedSet.<Path>of()))
                .transform(SourcePaths.toSourcePath(params.getProjectFilesystem()))
                .toSortedSet(Ordering.natural()),
            additionalDeps,
            args.labels.get(),
            args.contacts.get(),
            args.runTestSeparately.or(false),
            args.testRuleTimeoutMs.or(defaultTestRuleTimeoutMs),
            cxxBuckConfig.getMaximumTestOutputSize());
        break;
      }
      case BOOST: {
        test = new CxxBoostTest(
            testParams,
            pathResolver,
            cxxLinkAndCompileRules.getBinaryRule(),
            cxxLinkAndCompileRules.executable,
            testEnv,
            testArgs,
            FluentIterable.from(args.resources.or(ImmutableSortedSet.<Path>of()))
                .transform(SourcePaths.toSourcePath(params.getProjectFilesystem()))
                .toSortedSet(Ordering.natural()),
            additionalDeps,
            args.labels.get(),
            args.contacts.get(),
            args.runTestSeparately.or(false),
            args.testRuleTimeoutMs.or(defaultTestRuleTimeoutMs));
        break;
      }
      default: {
        Preconditions.checkState(false, "Unhandled C++ test type: %s", type);
        throw new RuntimeException();
      }
    }

    return test;
  }

  @Override
  public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellPathResolver cellRoots,
      Arg constructorArg) {

    ImmutableSet.Builder<BuildTarget> deps = ImmutableSet.builder();

    // Get any parse time deps from the C/C++ platforms.
    deps.addAll(
        CxxPlatforms.getParseTimeDeps(
            cxxPlatforms
                .getValue(buildTarget.getFlavors())
                .or(defaultCxxPlatform)));

    // Extract parse time deps from flags, args, and environment parameters.
    Iterable<Iterable<String>> macroStrings =
        ImmutableList.<Iterable<String>>builder()
            .add(constructorArg.linkerFlags.get())
            .addAll(constructorArg.platformLinkerFlags.get().getValues())
            .add(constructorArg.args.get())
            .add(constructorArg.env.get().values())
            .build();
    for (String macroString : Iterables.concat(macroStrings)) {
      try {
        deps.addAll(
            CxxDescriptionEnhancer.MACRO_HANDLER.extractParseTimeDeps(
                buildTarget,
                cellRoots,
                macroString));
      } catch (MacroException e) {
        throw new HumanReadableException(e, "%s: %s", buildTarget, e.getMessage());
      }
    }

    CxxTestType type = constructorArg.framework.or(getDefaultTestType());
    switch (type) {
      case GTEST: {
        deps.add(cxxBuckConfig.getGtestDep());
        boolean useDefaultTestMain = constructorArg.useDefaultTestMain.or(true);
        if (useDefaultTestMain) {
          deps.add(cxxBuckConfig.getGtestDefaultTestMainDep());
        }
        break;
      }
      case BOOST: {
        deps.add(cxxBuckConfig.getBoostTestDep());
        break;
      }
      default: {
        break;
      }
    }

    return deps.build();
  }

  public CxxTestType getDefaultTestType() {
    return DEFAULT_TEST_TYPE;
  }

  @Override
  public boolean hasFlavors(ImmutableSet<Flavor> flavors) {

    if (flavors.isEmpty()) {
      return true;
    }

    if (flavors.contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
      return true;
    }

    if (flavors.contains(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)) {
      return true;
    }

    if (StripStyle.FLAVOR_DOMAIN.containsAnyOf(flavors)) {
      return true;
    }

    for (Flavor flavor : cxxPlatforms.getFlavors()) {
      if (flavors.equals(ImmutableSet.of(flavor))) {
        return true;
      }
    }

    return false;
  }

  @Override
  public <A extends Arg, U> Optional<U> createMetadata(
      BuildTarget buildTarget,
      BuildRuleResolver resolver,
      A args,
      final Class<U> metadataClass) throws NoSuchBuildTargetException {
    if (!metadataClass.isAssignableFrom(CxxCompilationDatabaseDependencies.class) ||
        !buildTarget.getFlavors().contains(CxxCompilationDatabase.COMPILATION_DATABASE)) {
      return Optional.absent();
    }
    return CxxDescriptionEnhancer
        .createCompilationDatabaseDependencies(buildTarget, cxxPlatforms, resolver, args)
        .transform(
            new Function<CxxCompilationDatabaseDependencies, U>() {
              @Override
              public U apply(CxxCompilationDatabaseDependencies input) {
                return metadataClass.cast(input);
              }
            }
        );
  }

  @SuppressFieldNotInitialized
  public class Arg extends CxxBinaryDescription.Arg {
    public Optional<ImmutableSet<String>> contacts;
    public Optional<ImmutableSet<Label>> labels;
    public Optional<CxxTestType> framework;
    public Optional<ImmutableMap<String, String>> env;
    public Optional<ImmutableList<String>> args;
    public Optional<Boolean> runTestSeparately;
    public Optional<Boolean> useDefaultTestMain;
    public Optional<Long> testRuleTimeoutMs;
    public Optional<ImmutableSortedSet<Path>> resources;
  }

}


text:
#ifndef SIM_MAIN_H
#define SIM_MAIN_H

/* This simulator doesn't cache the Current Instruction Address */
/* #define SIM_ENGINE_HALT_HOOK(SD, LAST_CPU, CIA) */
/* #define SIM_ENGINE_RESUME_HOOK(SD, LAST_CPU, CIA) */

#define SIM_HAVE_BIENDIAN

/* hobble some common features for moment */
#define WITH_WATCHPOINTS 1
#define WITH_MODULO_MEMORY 1

#define SIM_CORE_SIGNAL(SD,CPU,CIA,MAP,NR_BYTES,ADDR,TRANSFER,ERROR) \
mips_core_signal ((SD), (CPU), (CIA), (MAP), (NR_BYTES), (ADDR), (TRANSFER), (ERROR))

#include "sim-basics.h"

typedef address_word sim_cia;

#include "sim-base.h"
#include "bfd.h"

/* Deprecated macros and types for manipulating 64bit values.  Use
   ../common/sim-bits.h and ../common/sim-endian.h macros instead. */

typedef signed64 word64;
typedef unsigned64 uword64;

#define WORD64LO(t)     (unsigned int)((t)&0xFFFFFFFF)
#define WORD64HI(t)     (unsigned int)(((uword64)(t))>>32)
#define SET64LO(t)      (((uword64)(t))&0xFFFFFFFF)
#define SET64HI(t)	(((uword64)(t))<<32)
#define WORD64(h,l)     ((word64)((SET64HI(h)|SET64LO(l))))
#define UWORD64(h,l)     (SET64HI(h)|SET64LO(l))

/* Check if a value will fit within a halfword: */
#define NOTHALFWORDVALUE(v) ((((((uword64)(v)>>16) == 0) && !((v) & ((unsigned)1 << 15))) || (((((uword64)(v)>>32) == 0xFFFFFFFF) && ((((uword64)(v)>>16) & 0xFFFF) == 0xFFFF)) && ((v) & ((unsigned)1 << 15)))) ? (1 == 0) : (1 == 1))

/* Floating-point operations: */

#include "sim-fpu.h"
#include "cp1.h"

/* FPU registers must be one of the following types. All other values
   are reserved (and undefined). */
typedef enum {
 fmt_single  = 0,
 fmt_double  = 1,
 fmt_word    = 4,
 fmt_long    = 5,
 fmt_ps      = 6,
 /* The following are well outside the normal acceptable format
    range, and are used in the register status vector. */
 fmt_unknown       = 0x10000000,
 fmt_uninterpreted = 0x20000000,
 fmt_uninterpreted_32 = 0x40000000,
 fmt_uninterpreted_64 = 0x80000000U,
} FP_formats;

/* For paired word (pw) operations, the opcode representation is fmt_word,
   but register transfers (StoreFPR, ValueFPR, etc.) are done as fmt_long.  */
#define fmt_pw fmt_long

/* This should be the COC1 value at the start of the preceding
   instruction: */
#define PREVCOC1() ((STATE & simPCOC1) ? 1 : 0)

#ifdef TARGET_ENABLE_FR
/* FIXME: this should be enabled for all targets, but needs testing first. */
#define SizeFGR() (((WITH_TARGET_FLOATING_POINT_BITSIZE) == 64) \
   ? ((SR & status_FR) ? 64 : 32) \
   : (WITH_TARGET_FLOATING_POINT_BITSIZE))
#else
#define SizeFGR() (WITH_TARGET_FLOATING_POINT_BITSIZE)
#endif

/* HI/LO register accesses */

/* For some MIPS targets, the HI/LO registers have certain timing
   restrictions in that, for instance, a read of a HI register must be
   separated by at least three instructions from a preceeding read.

   The struct below is used to record the last access by each of A MT,
   MF or other OP instruction to a HI/LO register.  See mips.igen for
   more details. */

typedef struct _hilo_access {
  signed64 timestamp;
  address_word cia;
} hilo_access;

typedef struct _hilo_history {
  hilo_access mt;
  hilo_access mf;
  hilo_access op;
} hilo_history;

/* Integer ALU operations: */

#include "sim-alu.h"

#define ALU32_END(ANS) \
  if (ALU32_HAD_OVERFLOW) \
    SignalExceptionIntegerOverflow (); \
  (ANS) = (signed32) ALU32_OVERFLOW_RESULT

#define ALU64_END(ANS) \
  if (ALU64_HAD_OVERFLOW) \
    SignalExceptionIntegerOverflow (); \
  (ANS) = ALU64_OVERFLOW_RESULT;

/* The following is probably not used for MIPS IV onwards: */
/* Slots for delayed register updates. For the moment we just have a
   fixed number of slots (rather than a more generic, dynamic
   system). This keeps the simulator fast. However, we only allow
   for the register update to be delayed for a single instruction
   cycle. */
#define PSLOTS (8) /* Maximum number of instruction cycles */

typedef struct _pending_write_queue {
  int in;
  int out;
  int total;
  int slot_delay[PSLOTS];
  int slot_size[PSLOTS];
  int slot_bit[PSLOTS];
  void *slot_dest[PSLOTS];
  unsigned64 slot_value[PSLOTS];
} pending_write_queue;

#ifndef PENDING_TRACE
#define PENDING_TRACE 0
#endif
#define PENDING_IN ((CPU)->pending.in)
#define PENDING_OUT ((CPU)->pending.out)
#define PENDING_TOTAL ((CPU)->pending.total)
#define PENDING_SLOT_SIZE ((CPU)->pending.slot_size)
#define PENDING_SLOT_BIT ((CPU)->pending.slot_bit)
#define PENDING_SLOT_DELAY ((CPU)->pending.slot_delay)
#define PENDING_SLOT_DEST ((CPU)->pending.slot_dest)
#define PENDING_SLOT_VALUE ((CPU)->pending.slot_value)

/* Invalidate the pending write queue, all pending writes are
   discarded. */

#define PENDING_INVALIDATE() \
memset (&(CPU)->pending, 0, sizeof ((CPU)->pending))

/* Schedule a write to DEST for N cycles time.  For 64 bit
   destinations, schedule two writes.  For floating point registers,
   the caller should schedule a write to both the dest register and
   the FPR_STATE register.  When BIT is non-negative, only BIT of DEST
   is updated. */

#define PENDING_SCHED(DEST,VAL,DELAY,BIT)				\
  do {									\
    if (PENDING_SLOT_DEST[PENDING_IN] != NULL)				\
      sim_engine_abort (SD, CPU, cia,					\
		        "PENDING_SCHED - buffer overflow\n");		\
    if (PENDING_TRACE)							\
      sim_io_eprintf (SD, "PENDING_SCHED - 0x%lx - dest 0x%lx, val 0x%lx, bit %d, size %d, pending_in %d, pending_out %d, pending_total %d\n",			\
		      (unsigned long) cia, (unsigned long) &(DEST),	\
		      (unsigned long) (VAL), (BIT), (int) sizeof (DEST),\
		      PENDING_IN, PENDING_OUT, PENDING_TOTAL);		\
    PENDING_SLOT_DELAY[PENDING_IN] = (DELAY) + 1;			\
    PENDING_SLOT_DEST[PENDING_IN] = &(DEST);				\
    PENDING_SLOT_VALUE[PENDING_IN] = (VAL);				\
    PENDING_SLOT_SIZE[PENDING_IN] = sizeof (DEST);			\
    PENDING_SLOT_BIT[PENDING_IN] = (BIT);				\
    PENDING_IN = (PENDING_IN + 1) % PSLOTS;                             \
    PENDING_TOTAL += 1;			                                \
  } while (0)

#define PENDING_WRITE(DEST,VAL,DELAY) PENDING_SCHED(DEST,VAL,DELAY,-1)
#define PENDING_BIT(DEST,VAL,DELAY,BIT) PENDING_SCHED(DEST,VAL,DELAY,BIT)

#define PENDING_TICK() pending_tick (SD, CPU, cia)

#define PENDING_FLUSH() abort () /* think about this one */
#define PENDING_FP() abort () /* think about this one */

/* For backward compatibility */
#define PENDING_FILL(R,VAL) 						\
do {									\
  if ((R) >= FGR_BASE && (R) < FGR_BASE + NR_FGR)			\
    {									\
      PENDING_SCHED(FGR[(R) - FGR_BASE], VAL, 1, -1);			\
      PENDING_SCHED(FPR_STATE[(R) - FGR_BASE], fmt_uninterpreted, 1, -1); \
    }									\
  else									\
    PENDING_SCHED(GPR[(R)], VAL, 1, -1);				\
} while (0)

enum float_operation
  {
    FLOP_ADD,    FLOP_SUB,    FLOP_MUL,    FLOP_MADD,
    FLOP_MSUB,   FLOP_MAX=10, FLOP_MIN,    FLOP_ABS,
    FLOP_ITOF0=14, FLOP_FTOI0=18, FLOP_NEG=23
  };

/* The internal representation of an MDMX accumulator.
   Note that 24 and 48 bit accumulator elements are represented in
   32 or 64 bits.  Since the accumulators are 2's complement with
   overflow suppressed, high-order bits can be ignored in most contexts.  */

typedef signed32 signed24;
typedef signed64 signed48;

typedef union {
  signed24  ob[8];
  signed48  qh[4];
} MDMX_accumulator;

/* Conventional system arguments.  */
#define SIM_STATE  sim_cpu *cpu, address_word cia
#define SIM_ARGS   CPU, cia

struct _sim_cpu {

  /* The following are internal simulator state variables: */
#define CIA_GET(CPU) ((CPU)->registers[PCIDX] + 0)
#define CIA_SET(CPU,CIA) ((CPU)->registers[PCIDX] = (CIA))
  address_word dspc;  /* delay-slot PC */
#define DSPC ((CPU)->dspc)

#define DELAY_SLOT(TARGET) NIA = delayslot32 (SD_, (TARGET))
#define NULLIFY_NEXT_INSTRUCTION() NIA = nullify_next_insn32 (SD_)

  /* State of the simulator */
  unsigned int state;
  unsigned int dsstate;
#define STATE ((CPU)->state)
#define DSSTATE ((CPU)->dsstate)

/* Flags in the "state" variable: */
#define simHALTEX       (1 << 2)  /* 0 = run; 1 = halt on exception */
#define simHALTIN       (1 << 3)  /* 0 = run; 1 = halt on interrupt */
#define simTRACE        (1 << 8)  /* 0 = do nothing; 1 = trace address activity */
#define simPCOC0        (1 << 17) /* COC[1] from current */
#define simPCOC1        (1 << 18) /* COC[1] from previous */
#define simDELAYSLOT    (1 << 24) /* 0 = do nothing; 1 = delay slot entry exists */
#define simSKIPNEXT     (1 << 25) /* 0 = do nothing; 1 = skip instruction */
#define simSIGINT	(1 << 28)  /* 0 = do nothing; 1 = SIGINT has occured */
#define simJALDELAYSLOT	(1 << 29) /* 1 = in jal delay slot */

#ifndef ENGINE_ISSUE_PREFIX_HOOK
#define ENGINE_ISSUE_PREFIX_HOOK() \
  { \
    /* Perform any pending writes */ \
    PENDING_TICK(); \
    /* Set previous flag, depending on current: */ \
    if (STATE & simPCOC0) \
     STATE |= simPCOC1; \
    else \
     STATE &= ~simPCOC1; \
    /* and update the current value: */ \
    if (GETFCC(0)) \
     STATE |= simPCOC0; \
    else \
     STATE &= ~simPCOC0; \
  }
#endif /* ENGINE_ISSUE_PREFIX_HOOK */

/* This is nasty, since we have to rely on matching the register
   numbers used by GDB. Unfortunately, depending on the MIPS target
   GDB uses different register numbers. We cannot just include the
   relevant "gdb/tm.h" link, since GDB may not be configured before
   the sim world, and also the GDB header file requires too much other
   state. */

#ifndef TM_MIPS_H
#define LAST_EMBED_REGNUM (96)
#define NUM_REGS (LAST_EMBED_REGNUM + 1)

#define FP0_REGNUM 38           /* Floating point register 0 (single float) */
#define FCRCS_REGNUM 70         /* FP control/status */
#define FCRIR_REGNUM 71         /* FP implementation/revision */
#endif

/* To keep this default simulator simple, and fast, we use a direct
   vector of registers. The internal simulator engine then uses
   manifests to access the correct slot. */

  unsigned_word registers[LAST_EMBED_REGNUM + 1];

  int register_widths[NUM_REGS];
#define REGISTERS       ((CPU)->registers)

#define GPR     (&REGISTERS[0])
#define GPR_SET(N,VAL) (REGISTERS[(N)] = (VAL))

#define LO      (REGISTERS[33])
#define HI      (REGISTERS[34])
#define PCIDX	37
#define PC      (REGISTERS[PCIDX])
#define CAUSE   (REGISTERS[36])
#define SRIDX   (32)
#define SR      (REGISTERS[SRIDX])      /* CPU status register */
#define FCR0IDX  (71)
#define FCR0    (REGISTERS[FCR0IDX])    /* really a 32bit register */
#define FCR31IDX (70)
#define FCR31   (REGISTERS[FCR31IDX])   /* really a 32bit register */
#define FCSR    (FCR31)
#define Debug	(REGISTERS[86])
#define DEPC	(REGISTERS[87])
#define EPC	(REGISTERS[88])
#define ACX	(REGISTERS[89])

#define AC0LOIDX	(33)	/* Must be the same register as LO */
#define AC0HIIDX	(34)	/* Must be the same register as HI */
#define AC1LOIDX	(90)
#define AC1HIIDX	(91)
#define AC2LOIDX	(92)
#define AC2HIIDX	(93)
#define AC3LOIDX	(94)
#define AC3HIIDX	(95)

#define DSPLO(N)	(REGISTERS[DSPLO_REGNUM[N]])
#define DSPHI(N)	(REGISTERS[DSPHI_REGNUM[N]])

#define DSPCRIDX	(96)	/* DSP control register */
#define DSPCR		(REGISTERS[DSPCRIDX])

#define DSPCR_POS_SHIFT		(0)
#define DSPCR_POS_MASK		(0x3f)
#define DSPCR_POS_SMASK		(DSPCR_POS_MASK << DSPCR_POS_SHIFT)

#define DSPCR_SCOUNT_SHIFT	(7)
#define DSPCR_SCOUNT_MASK	(0x3f)
#define DSPCR_SCOUNT_SMASK	(DSPCR_SCOUNT_MASK << DSPCR_SCOUNT_SHIFT)

#define DSPCR_CARRY_SHIFT	(13)
#define DSPCR_CARRY_MASK	(1)
#define DSPCR_CARRY_SMASK	(DSPCR_CARRY_MASK << DSPCR_CARRY_SHIFT)
#define DSPCR_CARRY		(1 << DSPCR_CARRY_SHIFT)

#define DSPCR_EFI_SHIFT		(14)
#define DSPCR_EFI_MASK		(1)
#define DSPCR_EFI_SMASK		(DSPCR_EFI_MASK << DSPCR_EFI_SHIFT)
#define DSPCR_EFI		(1 << DSPCR_EFI_MASK)

#define DSPCR_OUFLAG_SHIFT	(16)
#define DSPCR_OUFLAG_MASK	(0xff)
#define DSPCR_OUFLAG_SMASK	(DSPCR_OUFLAG_MASK << DSPCR_OUFLAG_SHIFT)
#define DSPCR_OUFLAG4		(1 << (DSPCR_OUFLAG_SHIFT + 4))
#define DSPCR_OUFLAG5		(1 << (DSPCR_OUFLAG_SHIFT + 5))
#define DSPCR_OUFLAG6		(1 << (DSPCR_OUFLAG_SHIFT + 6))
#define DSPCR_OUFLAG7		(1 << (DSPCR_OUFLAG_SHIFT + 7))

#define DSPCR_CCOND_SHIFT	(24)
#define DSPCR_CCOND_MASK	(0xf)
#define DSPCR_CCOND_SMASK	(DSPCR_CCOND_MASK << DSPCR_CCOND_SHIFT)

  /* All internal state modified by signal_exception() that may need to be
     rolled back for passing moment-of-exception image back to gdb. */
  unsigned_word exc_trigger_registers[LAST_EMBED_REGNUM + 1];
  unsigned_word exc_suspend_registers[LAST_EMBED_REGNUM + 1];
  int exc_suspended;

#define SIM_CPU_EXCEPTION_TRIGGER(SD,CPU,CIA) mips_cpu_exception_trigger(SD,CPU,CIA)
#define SIM_CPU_EXCEPTION_SUSPEND(SD,CPU,EXC) mips_cpu_exception_suspend(SD,CPU,EXC)
#define SIM_CPU_EXCEPTION_RESUME(SD,CPU,EXC) mips_cpu_exception_resume(SD,CPU,EXC)

  unsigned_word c0_config_reg;
#define C0_CONFIG ((CPU)->c0_config_reg)

/* The following are pseudonyms for standard registers */
#define ZERO    (REGISTERS[0])
#define V0      (REGISTERS[2])
#define A0      (REGISTERS[4])
#define A1      (REGISTERS[5])
#define A2      (REGISTERS[6])
#define A3      (REGISTERS[7])
#define T8IDX   24
#define T8	(REGISTERS[T8IDX])
#define SPIDX   29
#define SP      (REGISTERS[SPIDX])
#define RAIDX   31
#define RA      (REGISTERS[RAIDX])

  /* While space is allocated in the main registers arrray for some of
     the COP0 registers, that space isn't sufficient.  Unknown COP0
     registers overflow into the array below */

#define NR_COP0_GPR	32
  unsigned_word cop0_gpr[NR_COP0_GPR];
#define COP0_GPR	((CPU)->cop0_gpr)
#define COP0_BADVADDR	(COP0_GPR[8])

  /* While space is allocated for the floating point registers in the
     main registers array, they are stored separatly.  This is because
     their size may not necessarily match the size of either the
     general-purpose or system specific registers.  */
#define NR_FGR    (32)
#define FGR_BASE  FP0_REGNUM
  fp_word fgr[NR_FGR];
#define FGR       ((CPU)->fgr)

  /* Keep the current format state for each register: */
  FP_formats fpr_state[32];
#define FPR_STATE ((CPU)->fpr_state)

  pending_write_queue pending;

  /* The MDMX accumulator (used only for MDMX ASE).  */
  MDMX_accumulator acc;
#define ACC             ((CPU)->acc)

  /* LLBIT = Load-Linked bit. A bit of "virtual" state used by atomic
     read-write instructions. It is set when a linked load occurs. It
     is tested and cleared by the conditional store. It is cleared
     (during other CPU operations) when a store to the location would
     no longer be atomic. In particular, it is cleared by exception
     return instructions. */
  int llbit;
#define LLBIT ((CPU)->llbit)

/* The HIHISTORY and LOHISTORY timestamps are used to ensure that
   corruptions caused by using the HI or LO register too close to a
   following operation is spotted. See mips.igen for more details. */

  hilo_history hi_history;
#define HIHISTORY (&(CPU)->hi_history)
  hilo_history lo_history;
#define LOHISTORY (&(CPU)->lo_history)

  sim_cpu_base base;
};

/* MIPS specific simulator watch config */

void watch_options_install (SIM_DESC sd);

struct swatch {
  sim_event *pc;
  sim_event *clock;
  sim_event *cycles;
};

/* FIXME: At present much of the simulator is still static */
struct sim_state {

  struct swatch watch;

  sim_cpu cpu[MAX_NR_PROCESSORS];
#if (WITH_SMP)
#define STATE_CPU(sd,n) (&(sd)->cpu[n])
#else
#define STATE_CPU(sd,n) (&(sd)->cpu[0])
#endif

  sim_state_base base;
};

/* Status information: */

/* TODO : these should be the bitmasks for these bits within the
   status register. At the moment the following are VR4300
   bit-positions: */
#define status_KSU_mask  (0x18)         /* mask for KSU bits */
#define status_KSU_shift (3)            /* shift for field */
#define ksu_kernel       (0x0)
#define ksu_supervisor   (0x1)
#define ksu_user         (0x2)
#define ksu_unknown      (0x3)

#define SR_KSU		 ((SR & status_KSU_mask) >> status_KSU_shift)

#define status_IE	 (1 <<  0)      /* Interrupt enable */
#define status_EIE	 (1 << 16)      /* Enable Interrupt Enable */
#define status_EXL	 (1 <<  1)	/* Exception level */
#define status_RE        (1 << 25)      /* Reverse Endian in user mode */
#define status_FR        (1 << 26)      /* enables MIPS III additional FP registers */
#define status_SR        (1 << 20)      /* soft reset or NMI */
#define status_BEV       (1 << 22)      /* Location of general exception vectors */
#define status_TS        (1 << 21)      /* TLB shutdown has occurred */
#define status_ERL       (1 <<  2)      /* Error level */
#define status_IM7       (1 << 15)      /* Timer Interrupt Mask */
#define status_RP        (1 << 27)      /* Reduced Power mode */

/* Specializations for TX39 family */
#define status_IEc       (1 << 0)       /* Interrupt enable (current) */
#define status_KUc       (1 << 1)       /* Kernel/User mode */
#define status_IEp       (1 << 2)       /* Interrupt enable (previous) */
#define status_KUp       (1 << 3)       /* Kernel/User mode */
#define status_IEo       (1 << 4)       /* Interrupt enable (old) */
#define status_KUo       (1 << 5)       /* Kernel/User mode */
#define status_IM_mask   (0xff)         /* Interrupt mask */
#define status_IM_shift  (8)
#define status_NMI       (1 << 20)      /* NMI */
#define status_NMI       (1 << 20)      /* NMI */

/* Status bits used by MIPS32/MIPS64.  */
#define status_UX        (1 <<  5)      /* 64-bit user addrs */
#define status_SX        (1 <<  6)      /* 64-bit supervisor addrs */
#define status_KX        (1 <<  7)      /* 64-bit kernel addrs */
#define status_TS        (1 << 21)      /* TLB shutdown has occurred */
#define status_PX        (1 << 23)      /* Enable 64 bit operations */
#define status_MX        (1 << 24)      /* Enable MDMX resources */
#define status_CU0       (1 << 28)      /* Coprocessor 0 usable */
#define status_CU1       (1 << 29)      /* Coprocessor 1 usable */
#define status_CU2       (1 << 30)      /* Coprocessor 2 usable */
#define status_CU3       (1 << 31)      /* Coprocessor 3 usable */
/* Bits reserved for implementations:  */
#define status_SBX       (1 << 16)      /* Enable SiByte SB-1 extensions.  */

#define cause_BD ((unsigned)1 << 31)    /* L1 Exception in branch delay slot */
#define cause_BD2         (1 << 30)     /* L2 Exception in branch delay slot */
#define cause_CE_mask     0x30000000	/* Coprocessor exception */
#define cause_CE_shift    28
#define cause_EXC2_mask   0x00070000
#define cause_EXC2_shift  16
#define cause_IP7 	  (1 << 15)	/* Interrupt pending */
#define cause_SIOP        (1 << 12)     /* SIO pending */
#define cause_IP3 	  (1 << 11)	/* Int 0 pending */
#define cause_IP2 	  (1 << 10)	/* Int 1 pending */

#define cause_EXC_mask  (0x1c)          /* Exception code */
#define cause_EXC_shift (2)

#define cause_SW0       (1 << 8)        /* Software interrupt 0 */
#define cause_SW1       (1 << 9)        /* Software interrupt 1 */
#define cause_IP_mask   (0x3f)          /* Interrupt pending field */
#define cause_IP_shift  (10)

#define cause_set_EXC(x)  CAUSE = (CAUSE & ~cause_EXC_mask)  | ((x << cause_EXC_shift)  & cause_EXC_mask)
#define cause_set_EXC2(x) CAUSE = (CAUSE & ~cause_EXC2_mask) | ((x << cause_EXC2_shift) & cause_EXC2_mask)

/* NOTE: We keep the following status flags as bit values (1 for true,
   0 for false). This allows them to be used in binary boolean
   operations without worrying about what exactly the non-zero true
   value is. */

/* UserMode */
#ifdef SUBTARGET_R3900
#define UserMode        ((SR & status_KUc) ? 1 : 0)
#else
#define UserMode	((((SR & status_KSU_mask) >> status_KSU_shift) == ksu_user) ? 1 : 0)
#endif /* SUBTARGET_R3900 */

/* BigEndianMem */
/* Hardware configuration. Affects endianness of LoadMemory and
   StoreMemory and the endianness of Kernel and Supervisor mode
   execution. The value is 0 for little-endian; 1 for big-endian. */
#define BigEndianMem    (CURRENT_TARGET_BYTE_ORDER == BIG_ENDIAN)
/*(state & simBE) ? 1 : 0)*/

/* ReverseEndian */
/* This mode is selected if in User mode with the RE bit being set in
   SR (Status Register). It reverses the endianness of load and store
   instructions. */
#define ReverseEndian   (((SR & status_RE) && UserMode) ? 1 : 0)

/* BigEndianCPU */
/* The endianness for load and store instructions (0=little;1=big). In
   User mode this endianness may be switched by setting the state_RE
   bit in the SR register. Thus, BigEndianCPU may be computed as
   (BigEndianMem EOR ReverseEndian). */
#define BigEndianCPU    (BigEndianMem ^ ReverseEndian) /* Already bits */

/* Exceptions: */

/* NOTE: These numbers depend on the processor architecture being
   simulated: */
enum ExceptionCause {
  Interrupt               = 0,
  TLBModification         = 1,
  TLBLoad                 = 2,
  TLBStore                = 3,
  AddressLoad             = 4,
  AddressStore            = 5,
  InstructionFetch        = 6,
  DataReference           = 7,
  SystemCall              = 8,
  BreakPoint              = 9,
  ReservedInstruction     = 10,
  CoProcessorUnusable     = 11,
  IntegerOverflow         = 12,    /* Arithmetic overflow (IDT monitor raises SIGFPE) */
  Trap                    = 13,
  FPE                     = 15,
  DebugBreakPoint         = 16,    /* Impl. dep. in MIPS32/MIPS64.  */
  MDMX                    = 22,
  Watch                   = 23,
  MCheck                  = 24,
  CacheErr                = 30,
  NMIReset                = 31,    /* Reserved in MIPS32/MIPS64.  */

/* The following exception code is actually private to the simulator
   world. It is *NOT* a processor feature, and is used to signal
   run-time errors in the simulator. */
  SimulatorFault      	  = 0xFFFFFFFF
};

#define TLB_REFILL  (0)
#define TLB_INVALID (1)

/* The following break instructions are reserved for use by the
   simulator.  The first is used to halt the simulation.  The second
   is used by gdb for break-points.  NOTE: Care must be taken, since
   this value may be used in later revisions of the MIPS ISA. */
#define HALT_INSTRUCTION_MASK   (0x03FFFFC0)

#define HALT_INSTRUCTION        (0x03ff000d)
#define HALT_INSTRUCTION2       (0x0000ffcd)

#define BREAKPOINT_INSTRUCTION  (0x0005000d)
#define BREAKPOINT_INSTRUCTION2 (0x0000014d)

void interrupt_event (SIM_DESC sd, void *data);

void signal_exception (SIM_DESC sd, sim_cpu *cpu, address_word cia, int exception, ...);
#define SignalException(exc,instruction)     signal_exception (SD, CPU, cia, (exc), (instruction))
#define SignalExceptionInterrupt(level)      signal_exception (SD, CPU, cia, Interrupt, level)
#define SignalExceptionInstructionFetch()    signal_exception (SD, CPU, cia, InstructionFetch)
#define SignalExceptionAddressStore()        signal_exception (SD, CPU, cia, AddressStore)
#define SignalExceptionAddressLoad()         signal_exception (SD, CPU, cia, AddressLoad)
#define SignalExceptionDataReference()       signal_exception (SD, CPU, cia, DataReference)
#define SignalExceptionSimulatorFault(buf)   signal_exception (SD, CPU, cia, SimulatorFault, buf)
#define SignalExceptionFPE()                 signal_exception (SD, CPU, cia, FPE)
#define SignalExceptionIntegerOverflow()     signal_exception (SD, CPU, cia, IntegerOverflow)
#define SignalExceptionCoProcessorUnusable(cop) signal_exception (SD, CPU, cia, CoProcessorUnusable)
#define SignalExceptionNMIReset()            signal_exception (SD, CPU, cia, NMIReset)
#define SignalExceptionTLBRefillStore()      signal_exception (SD, CPU, cia, TLBStore, TLB_REFILL)
#define SignalExceptionTLBRefillLoad()       signal_exception (SD, CPU, cia, TLBLoad, TLB_REFILL)
#define SignalExceptionTLBInvalidStore()     signal_exception (SD, CPU, cia, TLBStore, TLB_INVALID)
#define SignalExceptionTLBInvalidLoad()      signal_exception (SD, CPU, cia, TLBLoad, TLB_INVALID)
#define SignalExceptionTLBModification()     signal_exception (SD, CPU, cia, TLBModification)
#define SignalExceptionMDMX()                signal_exception (SD, CPU, cia, MDMX)
#define SignalExceptionWatch()               signal_exception (SD, CPU, cia, Watch)
#define SignalExceptionMCheck()              signal_exception (SD, CPU, cia, MCheck)
#define SignalExceptionCacheErr()            signal_exception (SD, CPU, cia, CacheErr)

/* Co-processor accesses */

/* XXX FIXME: For now, assume that FPU (cp1) is always usable.  */
#define COP_Usable(coproc_num)		(coproc_num == 1)

void cop_lw  (SIM_DESC sd, sim_cpu *cpu, address_word cia, int coproc_num, int coproc_reg, unsigned int memword);
void cop_ld  (SIM_DESC sd, sim_cpu *cpu, address_word cia, int coproc_num, int coproc_reg, uword64 memword);
unsigned int cop_sw (SIM_DESC sd, sim_cpu *cpu, address_word cia, int coproc_num, int coproc_reg);
uword64 cop_sd (SIM_DESC sd, sim_cpu *cpu, address_word cia, int coproc_num, int coproc_reg);

#define COP_LW(coproc_num,coproc_reg,memword) \
cop_lw (SD, CPU, cia, coproc_num, coproc_reg, memword)
#define COP_LD(coproc_num,coproc_reg,memword) \
cop_ld (SD, CPU, cia, coproc_num, coproc_reg, memword)
#define COP_SW(coproc_num,coproc_reg) \
cop_sw (SD, CPU, cia, coproc_num, coproc_reg)
#define COP_SD(coproc_num,coproc_reg) \
cop_sd (SD, CPU, cia, coproc_num, coproc_reg)

void decode_coproc (SIM_DESC sd, sim_cpu *cpu, address_word cia, unsigned int instruction);
#define DecodeCoproc(instruction) \
decode_coproc (SD, CPU, cia, (instruction))

int sim_monitor (SIM_DESC sd, sim_cpu *cpu, address_word cia, unsigned int arg);

/* FPR access.  */
unsigned64 value_fpr (SIM_STATE, int fpr, FP_formats);
#define ValueFPR(FPR,FMT) value_fpr (SIM_ARGS, (FPR), (FMT))
void store_fpr (SIM_STATE, int fpr, FP_formats fmt, unsigned64 value);
#define StoreFPR(FPR,FMT,VALUE) store_fpr (SIM_ARGS, (FPR), (FMT), (VALUE))
unsigned64 ps_lower (SIM_STATE, unsigned64 op);
#define PSLower(op) ps_lower (SIM_ARGS, op)
unsigned64 ps_upper (SIM_STATE, unsigned64 op);
#define PSUpper(op) ps_upper (SIM_ARGS, op)
unsigned64 pack_ps (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats from);
#define PackPS(op1,op2) pack_ps (SIM_ARGS, op1, op2, fmt_single)

/* FCR access.  */
unsigned_word value_fcr (SIM_STATE, int fcr);
#define ValueFCR(FCR) value_fcr (SIM_ARGS, (FCR))
void store_fcr (SIM_STATE, int fcr, unsigned_word value);
#define StoreFCR(FCR,VALUE) store_fcr (SIM_ARGS, (FCR), (VALUE))
void test_fcsr (SIM_STATE);
#define TestFCSR() test_fcsr (SIM_ARGS)

/* FPU operations.  */
void fp_cmp (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt, int abs, int cond, int cc);
#define Compare(op1,op2,fmt,cond,cc) fp_cmp(SIM_ARGS, op1, op2, fmt, 0, cond, cc)
unsigned64 fp_abs (SIM_STATE, unsigned64 op, FP_formats fmt);
#define AbsoluteValue(op,fmt) fp_abs(SIM_ARGS, op, fmt)
unsigned64 fp_neg (SIM_STATE, unsigned64 op, FP_formats fmt);
#define Negate(op,fmt) fp_neg(SIM_ARGS, op, fmt)
unsigned64 fp_add (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define Add(op1,op2,fmt) fp_add(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_sub (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define Sub(op1,op2,fmt) fp_sub(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_mul (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define Multiply(op1,op2,fmt) fp_mul(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_div (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define Divide(op1,op2,fmt) fp_div(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_recip (SIM_STATE, unsigned64 op, FP_formats fmt);
#define Recip(op,fmt) fp_recip(SIM_ARGS, op, fmt)
unsigned64 fp_sqrt (SIM_STATE, unsigned64 op, FP_formats fmt);
#define SquareRoot(op,fmt) fp_sqrt(SIM_ARGS, op, fmt)
unsigned64 fp_rsqrt (SIM_STATE, unsigned64 op, FP_formats fmt);
#define RSquareRoot(op,fmt) fp_rsqrt(SIM_ARGS, op, fmt)
unsigned64 fp_madd (SIM_STATE, unsigned64 op1, unsigned64 op2,
		    unsigned64 op3, FP_formats fmt);
#define MultiplyAdd(op1,op2,op3,fmt) fp_madd(SIM_ARGS, op1, op2, op3, fmt)
unsigned64 fp_msub (SIM_STATE, unsigned64 op1, unsigned64 op2,
		    unsigned64 op3, FP_formats fmt);
#define MultiplySub(op1,op2,op3,fmt) fp_msub(SIM_ARGS, op1, op2, op3, fmt)
unsigned64 fp_nmadd (SIM_STATE, unsigned64 op1, unsigned64 op2,
		     unsigned64 op3, FP_formats fmt);
#define NegMultiplyAdd(op1,op2,op3,fmt) fp_nmadd(SIM_ARGS, op1, op2, op3, fmt)
unsigned64 fp_nmsub (SIM_STATE, unsigned64 op1, unsigned64 op2,
		     unsigned64 op3, FP_formats fmt);
#define NegMultiplySub(op1,op2,op3,fmt) fp_nmsub(SIM_ARGS, op1, op2, op3, fmt)
unsigned64 convert (SIM_STATE, int rm, unsigned64 op, FP_formats from, FP_formats to);
#define Convert(rm,op,from,to) convert (SIM_ARGS, rm, op, from, to)
unsigned64 convert_ps (SIM_STATE, int rm, unsigned64 op, FP_formats from,
		       FP_formats to);
#define ConvertPS(rm,op,from,to) convert_ps (SIM_ARGS, rm, op, from, to)

/* MIPS-3D ASE operations.  */
#define CompareAbs(op1,op2,fmt,cond,cc) \
fp_cmp(SIM_ARGS, op1, op2, fmt, 1, cond, cc)
unsigned64 fp_add_r (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define AddR(op1,op2,fmt) fp_add_r(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_mul_r (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define MultiplyR(op1,op2,fmt) fp_mul_r(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_recip1 (SIM_STATE, unsigned64 op, FP_formats fmt);
#define Recip1(op,fmt) fp_recip1(SIM_ARGS, op, fmt)
unsigned64 fp_recip2 (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define Recip2(op1,op2,fmt) fp_recip2(SIM_ARGS, op1, op2, fmt)
unsigned64 fp_rsqrt1 (SIM_STATE, unsigned64 op, FP_formats fmt);
#define RSquareRoot1(op,fmt) fp_rsqrt1(SIM_ARGS, op, fmt)
unsigned64 fp_rsqrt2 (SIM_STATE, unsigned64 op1, unsigned64 op2, FP_formats fmt);
#define RSquareRoot2(op1,op2,fmt) fp_rsqrt2(SIM_ARGS, op1, op2, fmt)

/* MDMX access.  */

typedef unsigned int MX_fmtsel;   /* MDMX format select field (5 bits).  */
#define ob_fmtsel(sel) (((sel)<<1)|0x0)
#define qh_fmtsel(sel) (((sel)<<2)|0x1)

#define fmt_mdmx fmt_uninterpreted

#define MX_VECT_AND  (0)
#define MX_VECT_NOR  (1)
#define MX_VECT_OR   (2)
#define MX_VECT_XOR  (3)
#define MX_VECT_SLL  (4)
#define MX_VECT_SRL  (5)
#define MX_VECT_ADD  (6)
#define MX_VECT_SUB  (7)
#define MX_VECT_MIN  (8)
#define MX_VECT_MAX  (9)
#define MX_VECT_MUL  (10)
#define MX_VECT_MSGN (11)
#define MX_VECT_SRA  (12)
#define MX_VECT_ABSD (13)		/* SB-1 only.  */
#define MX_VECT_AVG  (14)		/* SB-1 only.  */

unsigned64 mdmx_cpr_op (SIM_STATE, int op, unsigned64 op1, int vt, MX_fmtsel fmtsel);
#define MX_Add(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_ADD, op1, vt, fmtsel)
#define MX_And(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_AND, op1, vt, fmtsel)
#define MX_Max(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_MAX, op1, vt, fmtsel)
#define MX_Min(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_MIN, op1, vt, fmtsel)
#define MX_Msgn(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_MSGN, op1, vt, fmtsel)
#define MX_Mul(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_MUL, op1, vt, fmtsel)
#define MX_Nor(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_NOR, op1, vt, fmtsel)
#define MX_Or(op1,vt,fmtsel)  mdmx_cpr_op(SIM_ARGS, MX_VECT_OR,  op1, vt, fmtsel)
#define MX_ShiftLeftLogical(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_SLL, op1, vt, fmtsel)
#define MX_ShiftRightArith(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_SRA, op1, vt, fmtsel)
#define MX_ShiftRightLogical(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_SRL, op1, vt, fmtsel)
#define MX_Sub(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_SUB, op1, vt, fmtsel)
#define MX_Xor(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_XOR, op1, vt, fmtsel)
#define MX_AbsDiff(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_ABSD, op1, vt, fmtsel)
#define MX_Avg(op1,vt,fmtsel) mdmx_cpr_op(SIM_ARGS, MX_VECT_AVG, op1, vt, fmtsel)

#define MX_C_EQ  0x1
#define MX_C_LT  0x4

void mdmx_cc_op (SIM_STATE, int cond, unsigned64 op1, int vt, MX_fmtsel fmtsel);
#define MX_Comp(op1,cond,vt,fmtsel) mdmx_cc_op(SIM_ARGS, cond, op1, vt, fmtsel)

unsigned64 mdmx_pick_op (SIM_STATE, int tf, unsigned64 op1, int vt, MX_fmtsel fmtsel);
#define MX_Pick(tf,op1,vt,fmtsel) mdmx_pick_op(SIM_ARGS, tf, op1, vt, fmtsel)

#define MX_VECT_ADDA  (0)
#define MX_VECT_ADDL  (1)
#define MX_VECT_MULA  (2)
#define MX_VECT_MULL  (3)
#define MX_VECT_MULS  (4)
#define MX_VECT_MULSL (5)
#define MX_VECT_SUBA  (6)
#define MX_VECT_SUBL  (7)
#define MX_VECT_ABSDA (8)		/* SB-1 only.  */

void mdmx_acc_op (SIM_STATE, int op, unsigned64 op1, int vt, MX_fmtsel fmtsel);
#define MX_AddA(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_ADDA, op1, vt, fmtsel)
#define MX_AddL(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_ADDL, op1, vt, fmtsel)
#define MX_MulA(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_MULA, op1, vt, fmtsel)
#define MX_MulL(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_MULL, op1, vt, fmtsel)
#define MX_MulS(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_MULS, op1, vt, fmtsel)
#define MX_MulSL(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_MULSL, op1, vt, fmtsel)
#define MX_SubA(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_SUBA, op1, vt, fmtsel)
#define MX_SubL(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_SUBL, op1, vt, fmtsel)
#define MX_AbsDiffC(op1,vt,fmtsel) mdmx_acc_op(SIM_ARGS, MX_VECT_ABSDA, op1, vt, fmtsel)

#define MX_FMT_OB   (0)
#define MX_FMT_QH   (1)

/* The following codes chosen to indicate the units of shift.  */
#define MX_RAC_L    (0)
#define MX_RAC_M    (1)
#define MX_RAC_H    (2)

unsigned64 mdmx_rac_op (SIM_STATE, int, int);
#define MX_RAC(op,fmt) mdmx_rac_op(SIM_ARGS, op, fmt)

void mdmx_wacl (SIM_STATE, int, unsigned64, unsigned64);
#define MX_WACL(fmt,vs,vt) mdmx_wacl(SIM_ARGS, fmt, vs, vt)
void mdmx_wach (SIM_STATE, int, unsigned64);
#define MX_WACH(fmt,vs) mdmx_wach(SIM_ARGS, fmt, vs)

#define MX_RND_AS   (0)
#define MX_RND_AU   (1)
#define MX_RND_ES   (2)
#define MX_RND_EU   (3)
#define MX_RND_ZS   (4)
#define MX_RND_ZU   (5)

unsigned64 mdmx_round_op (SIM_STATE, int, int, MX_fmtsel);
#define MX_RNAS(vt,fmt) mdmx_round_op(SIM_ARGS, MX_RND_AS, vt, fmt)
#define MX_RNAU(vt,fmt) mdmx_round_op(SIM_ARGS, MX_RND_AU, vt, fmt)
#define MX_RNES(vt,fmt) mdmx_round_op(SIM_ARGS, MX_RND_ES, vt, fmt)
#define MX_RNEU(vt,fmt) mdmx_round_op(SIM_ARGS, MX_RND_EU, vt, fmt)
#define MX_RZS(vt,fmt)  mdmx_round_op(SIM_ARGS, MX_RND_ZS, vt, fmt)
#define MX_RZU(vt,fmt)  mdmx_round_op(SIM_ARGS, MX_RND_ZU, vt, fmt)

unsigned64 mdmx_shuffle (SIM_STATE, int, unsigned64, unsigned64);
#define MX_SHFL(shop,op1,op2) mdmx_shuffle(SIM_ARGS, shop, op1, op2)

/* Memory accesses */

/* The following are generic to all versions of the MIPS architecture
   to date: */

/* Memory Access Types (for CCA): */
#define Uncached                (0)
#define CachedNoncoherent       (1)
#define CachedCoherent          (2)
#define Cached                  (3)

#define isINSTRUCTION   (1 == 0) /* FALSE */
#define isDATA          (1 == 1) /* TRUE */
#define isLOAD          (1 == 0) /* FALSE */
#define isSTORE         (1 == 1) /* TRUE */
#define isREAL          (1 == 0) /* FALSE */
#define isRAW           (1 == 1) /* TRUE */
/* The parameter HOST (isTARGET / isHOST) is ignored */
#define isTARGET        (1 == 0) /* FALSE */
/* #define isHOST          (1 == 1) TRUE */

/* The "AccessLength" specifications for Loads and Stores. NOTE: This
   is the number of bytes minus 1. */
#define AccessLength_BYTE       (0)
#define AccessLength_HALFWORD   (1)
#define AccessLength_TRIPLEBYTE (2)
#define AccessLength_WORD       (3)
#define AccessLength_QUINTIBYTE (4)
#define AccessLength_SEXTIBYTE  (5)
#define AccessLength_SEPTIBYTE  (6)
#define AccessLength_DOUBLEWORD (7)
#define AccessLength_QUADWORD   (15)

#define LOADDRMASK (WITH_TARGET_WORD_BITSIZE == 64 \
		    ? AccessLength_DOUBLEWORD /*7*/ \
		    : AccessLength_WORD /*3*/)
#define PSIZE (WITH_TARGET_ADDRESS_BITSIZE)

INLINE_SIM_MAIN (int) address_translation (SIM_DESC sd, sim_cpu *, address_word cia, address_word vAddr, int IorD, int LorS, address_word *pAddr, int *CCA, int raw);
#define AddressTranslation(vAddr,IorD,LorS,pAddr,CCA,host,raw) \
address_translation (SD, CPU, cia, vAddr, IorD, LorS, pAddr, CCA, raw)

INLINE_SIM_MAIN (void) load_memory (SIM_DESC sd, sim_cpu *cpu, address_word cia, uword64* memvalp, uword64* memval1p, int CCA, unsigned int AccessLength, address_word pAddr, address_word vAddr, int IorD);
#define LoadMemory(memvalp,memval1p,CCA,AccessLength,pAddr,vAddr,IorD,raw) \
load_memory (SD, CPU, cia, memvalp, memval1p, CCA, AccessLength, pAddr, vAddr, IorD)

INLINE_SIM_MAIN (void) store_memory (SIM_DESC sd, sim_cpu *cpu, address_word cia, int CCA, unsigned int AccessLength, uword64 MemElem, uword64 MemElem1, address_word pAddr, address_word vAddr);
#define StoreMemory(CCA,AccessLength,MemElem,MemElem1,pAddr,vAddr,raw) \
store_memory (SD, CPU, cia, CCA, AccessLength, MemElem, MemElem1, pAddr, vAddr)

INLINE_SIM_MAIN (void) cache_op (SIM_DESC sd, sim_cpu *cpu, address_word cia, int op, address_word pAddr, address_word vAddr, unsigned int instruction);
#define CacheOp(op,pAddr,vAddr,instruction) \
cache_op (SD, CPU, cia, op, pAddr, vAddr, instruction)

INLINE_SIM_MAIN (void) sync_operation (SIM_DESC sd, sim_cpu *cpu, address_word cia, int stype);
#define SyncOperation(stype) \
sync_operation (SD, CPU, cia, (stype))

INLINE_SIM_MAIN (void) prefetch (SIM_DESC sd, sim_cpu *cpu, address_word cia, int CCA, address_word pAddr, address_word vAddr, int DATA, int hint);
#define Prefetch(CCA,pAddr,vAddr,DATA,hint) \
prefetch (SD, CPU, cia, CCA, pAddr, vAddr, DATA, hint)

void unpredictable_action (sim_cpu *cpu, address_word cia);
#define NotWordValue(val)	not_word_value (SD_, (val))
#define Unpredictable()		unpredictable (SD_)
#define UnpredictableResult()	/* For now, do nothing.  */

INLINE_SIM_MAIN (unsigned32) ifetch32 (SIM_DESC sd, sim_cpu *cpu, address_word cia, address_word vaddr);
#define IMEM32(CIA) ifetch32 (SD, CPU, (CIA), (CIA))
INLINE_SIM_MAIN (unsigned16) ifetch16 (SIM_DESC sd, sim_cpu *cpu, address_word cia, address_word vaddr);
#define IMEM16(CIA) ifetch16 (SD, CPU, (CIA), ((CIA) & ~1))
#define IMEM16_IMMED(CIA,NR) ifetch16 (SD, CPU, (CIA), ((CIA) & ~1) + 2 * (NR))

void dotrace (SIM_DESC sd, sim_cpu *cpu, FILE *tracefh, int type, SIM_ADDR address, int width, char *comment, ...);
extern FILE *tracefh;

extern int DSPLO_REGNUM[4];
extern int DSPHI_REGNUM[4];

INLINE_SIM_MAIN (void) pending_tick (SIM_DESC sd, sim_cpu *cpu, address_word cia);
extern SIM_CORE_SIGNAL_FN mips_core_signal;

char* pr_addr (SIM_ADDR addr);
char* pr_uword64 (uword64 addr);

#define GPR_CLEAR(N) do { GPR_SET((N),0); } while (0)

void mips_cpu_exception_trigger(SIM_DESC sd, sim_cpu* cpu, address_word pc);
void mips_cpu_exception_suspend(SIM_DESC sd, sim_cpu* cpu, int exception);
void mips_cpu_exception_resume(SIM_DESC sd, sim_cpu* cpu, int exception);

#ifdef MIPS_MACH_MULTI
extern int mips_mach_multi(SIM_DESC sd);
#define MIPS_MACH(SD)	mips_mach_multi(SD)
#else
#define	MIPS_MACH(SD)	MIPS_MACH_DEFAULT
#endif

/* Macros for determining whether a MIPS IV or MIPS V part is subject
   to the hi/lo restrictions described in mips.igen.  */

#define MIPS_MACH_HAS_MT_HILO_HAZARD(SD) \
  (MIPS_MACH (SD) != bfd_mach_mips5500)

#define MIPS_MACH_HAS_MULT_HILO_HAZARD(SD) \
  (MIPS_MACH (SD) != bfd_mach_mips5500)

#define MIPS_MACH_HAS_DIV_HILO_HAZARD(SD) \
  (MIPS_MACH (SD) != bfd_mach_mips5500)

#if H_REVEALS_MODULE_P (SIM_MAIN_INLINE)
#include "sim-main.c"
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
layout: article
title: "Brick wall beards"
excerpt: "PaperFaces portrait of @jaceanderson drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-jaceanderson-twitter-lg.jpg
  thumb: paperfaces-jaceanderson-twitter-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53, beard]
---

PaperFaces portrait of [@jaceanderson](http://twitter.com/jaceanderson).

{% include paperfaces-boilerplate.html %}


text:
//
//  GDataServiceACL.h
//

#if !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_ACLS \
  || GDATA_INCLUDE_CALENDAR_SERVICE || GDATA_INCLUDE_DOCS_SERVICE

#import "GDataServiceGoogle.h"

@class GDataEntryACL;

// GDataServiceGoogle is the version of the service class that supports
// Google authentication.
@interface GDataServiceGoogle (GDataServiceACLAdditions)

- (GDataServiceTicket *)fetchACLFeedWithURL:(NSURL *)feedURL
                                   delegate:(id)delegate
                          didFinishSelector:(SEL)finishedSelector;

- (GDataServiceTicket *)fetchACLEntryByInsertingEntry:(GDataEntryACL *)entryToInsert
                                           forFeedURL:(NSURL *)feedURL
                                             delegate:(id)delegate
                                    didFinishSelector:(SEL)finishedSelector;

- (GDataServiceTicket *)fetchACLEntryByUpdatingEntry:(GDataEntryACL *)entryToUpdate
                                            delegate:(id)delegate
                                   didFinishSelector:(SEL)finishedSelector;

- (GDataServiceTicket *)fetchACLEntryByUpdatingEntry:(GDataEntryACL *)entryToUpdate
                                         forEntryURL:(NSURL *)entryURL
                                            delegate:(id)delegate
                                   didFinishSelector:(SEL)finishedSelector;

- (GDataServiceTicket *)deleteACLEntry:(GDataEntryACL *)entryToDelete
                              delegate:(id)delegate
                     didFinishSelector:(SEL)finishedSelector;
@end

#endif // !GDATA_REQUIRE_SERVICE_INCLUDE || GDATA_INCLUDE_*


text:
package record

import (
	"bytes"
	"errors"

	key "github.com/ipfs/go-ipfs/blocks/key"
	path "github.com/ipfs/go-ipfs/path"
	pb "github.com/ipfs/go-ipfs/routing/dht/pb"
	ci "gx/ipfs/QmNefBbWHR9JEiP3KDVqZsBLQVRmH3GBG2D2Ke24SsFqfW/go-libp2p/p2p/crypto"
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
)

// ValidatorFunc is a function that is called to validate a given
// type of DHTRecord.
type ValidatorFunc func(key.Key, []byte) error

// ErrBadRecord is returned any time a dht record is found to be
// incorrectly formatted or signed.
var ErrBadRecord = errors.New("bad dht record")

// ErrInvalidRecordType is returned if a DHTRecord keys prefix
// is not found in the Validator map of the DHT.
var ErrInvalidRecordType = errors.New("invalid record keytype")

// Validator is an object that helps ensure routing records are valid.
// It is a collection of validator functions, each of which implements
// its own notion of validity.
type Validator map[string]*ValidChecker

type ValidChecker struct {
	Func ValidatorFunc
	Sign bool
}

// VerifyRecord checks a record and ensures it is still valid.
// It runs needed validators
func (v Validator) VerifyRecord(r *pb.Record) error {
	// Now, check validity func
	parts := path.SplitList(r.GetKey())
	if len(parts) < 3 {
		log.Infof("Record key does not have validator: %s", key.Key(r.GetKey()))
		return nil
	}

	val, ok := v[parts[1]]
	if !ok {
		log.Infof("Unrecognized key prefix: %s", parts[1])
		return ErrInvalidRecordType
	}

	return val.Func(key.Key(r.GetKey()), r.GetValue())
}

func (v Validator) IsSigned(k key.Key) (bool, error) {
	// Now, check validity func
	parts := path.SplitList(string(k))
	if len(parts) < 3 {
		log.Infof("Record key does not have validator: %s", k)
		return false, nil
	}

	val, ok := v[parts[1]]
	if !ok {
		log.Infof("Unrecognized key prefix: %s", parts[1])
		return false, ErrInvalidRecordType
	}

	return val.Sign, nil
}

// ValidatePublicKeyRecord implements ValidatorFunc and
// verifies that the passed in record value is the PublicKey
// that matches the passed in key.
func ValidatePublicKeyRecord(k key.Key, val []byte) error {
	keyparts := bytes.Split([]byte(k), []byte("/"))
	if len(keyparts) < 3 {
		return errors.New("invalid key")
	}

	pkh := u.Hash(val)
	if !bytes.Equal(keyparts[2], pkh) {
		return errors.New("public key does not match storage key")
	}
	return nil
}

var PublicKeyValidator = &ValidChecker{
	Func: ValidatePublicKeyRecord,
	Sign: false,
}

func CheckRecordSig(r *pb.Record, pk ci.PubKey) error {
	blob := RecordBlobForSig(r)
	good, err := pk.Verify(blob, r.Signature)
	if err != nil {
		return nil
	}
	if !good {
		return errors.New("invalid record signature")
	}
	return nil
}


text:
namespace DisclosureAccessoryDemo.Xaml
{
    public enum AccessoryType
    {
        None,
        DisclosureIndicator,
        DetailDisclosureButton,
        Checkmark,
        DetailButton
    }
}


text:
package com.lfkdsk.justel.literal;

import com.lfkdsk.justel.context.JustContext;
import com.lfkdsk.justel.exception.ParseException;
import com.lfkdsk.justel.token.NumberToken;
import com.lfkdsk.justel.token.Token;

import static com.lfkdsk.justel.utils.NumberUtils.castTokenValue;

/**
 * Number Literal.
 * We support two kinds of Number Value :
 * - Long Value
 * - Integer Value
 * - Float Value
 * - Double Value
 *
 * @author liufengkai
 *         Created by liufengkai on 2017/7/24.
 */
public class NumberLiteral extends Literal {

    /**
     * Inner number
     */
    private Number number;

    public NumberLiteral(Token token) {
        super(token);

        if (token instanceof NumberToken) {
            this.number = ((NumberToken) token).getNumberValue();
        } else {
            throw new ParseException("UnSupport number name where token " +
                    "type is not NumberToken");
        }
    }

    @Override
    public String toString() {
        switch (token.getTag()) {
            case Token.INTEGER:
                return String.valueOf(number.intValue());
            case Token.LONG:
                return String.valueOf(number.longValue());
            case Token.FLOAT:
                return String.valueOf(number.floatValue());
            case Token.DOUBLE:
                return String.valueOf(number.doubleValue());
            default:
                return "undefine number literal";
        }
    }

    public NumberToken numberToken() {
        return (NumberToken) token;
    }

    @Override
    public Object eval(JustContext env) {
        return castTokenValue(numberToken());
    }

    @Override
    public String compile(JustContext env) {
        switch (token.getTag()) {
            case Token.LONG:
                return number.longValue() + "L";
            case Token.FLOAT:
                return number.floatValue() + "F";
            case Token.DOUBLE:
                return number.doubleValue() + "D";
        }

        return super.compile(env);
    }
}


text:
from .loader import DefaultValueLoader
from .loader import ExclusionLoader


text:
package org.sakaiproject.user.impl;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class ReEncryptPasswords {

	private static Properties props;

	/**
	 * Command line utility to re-encrypt all passwords in the database that use unsalted MD5.
	 * It should be run on the command line in the sakai.home folder with both the kernel-impl
	 * and SQL drvier jars on the classpath.
	 * @param args
	 * @throws SQLException
	 */
	public static void main(String[] args) throws Exception {

		props = new Properties();
		props.load(new FileInputStream(System.getProperty("sakai.properties", "sakai.properties")));
		String location = null;
		try {
			location = System.getProperty("local.properties", "local.properties");
			props.load(new FileInputStream(location));
		} catch (Exception e) {
			System.out.println("Didn't load local.properties: "+ location);
		}
		try {
			location = System.getProperty("security.properties", "security.properties");
			props.load(new FileInputStream(location));
		} catch (Exception e) {
			System.out.println("Didn't load security.properties: "+ location);
		}

		String url, username, password, driver;

		url = getOrBail("url@javax.sql.BaseDataSource");
		username = getOrBail("username@javax.sql.BaseDataSource");
		password = getOrBail("password@javax.sql.BaseDataSource");
		driver = getOrBail("driverClassName@javax.sql.BaseDataSource");

		Class.forName(driver);

		PasswordService pwdService = new PasswordService();

		Connection conn = DriverManager.getConnection(url, username, password);
		conn.setAutoCommit(false);
		PreparedStatement usersSt = conn.prepareStatement("SELECT USER_ID, PW FROM SAKAI_USER FOR UPDATE", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
		ResultSet usersRs = usersSt.executeQuery();

		int total = 0, updated = 0;
		while (usersRs.next()) {
			total++;
			String currentPw = usersRs.getString("PW");
			String newPw = null;
			if (currentPw != null && currentPw.length() == 20) {
				newPw = PasswordService.MD5TRUNC_SALT_SHA256+ pwdService.encrypt(currentPw);
			} else if (currentPw != null && currentPw.length() == 24) {
				newPw = PasswordService.MD5_SALT_SHA256+ pwdService.encrypt(currentPw);
			}
			if (newPw != null) {
				usersRs.updateString("PW", newPw);
				usersRs.updateRow();
				updated++;
			}
		}
		conn.commit();
		System.out.println(" Users processed: "+ total+ " updated: "+ updated);
	}

	/**
	 * Get configuration from the properties or bail out.
	 * @param property The property to lookup.
	 * @return The value found.
	 * @throws java.lang.IllegalStateException If the property wasn't found.
	 */
	private static String getOrBail(String property) {
		String value = props.getProperty(property);
		if (value == null) {
			throw new IllegalStateException("Unable to find configuration for: "+ property);
		}
		return value;
	}

}


text:
set -ex
# check to see if the deps folder is empty
if [ ! "$(ls -A $HOME/deps)" ]; then
  mkdir -p $HOME/deps
  git clone https://github.com/nats-io/nats.c.deps.git $HOME/deps
else
  echo 'Using cached directory.';
fi
cd $HOME


text:
<!DOCTYPE html>

    <title>Semantic HTML</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/style.css" rel="stylesheet">

Interweb is easy!

Home

About

Blog

Sign Up

Semantic HTML

By Troy McClure. Published <time datetime="2017-1-3">January 3rd</time>

This is an example web page explaining HTML5 semantic markup.

The Document Outline

HTML5 includes several "sectioning content" elements that affect the document outline.

Headers

The <header> element is one such sectioning element.

Footers

And so is the <footer> element.

Inline Semantic HTML

The <time> element is semantic, but it's not sectioning content.

This fake article was written by somebody at InternetingIsHard.com, which is a pretty decent place to learn how to
                    become a web developer.

                  <address>
                    Please contact Troy
                    McClure for questions about this article.
                </address>

Sidebar

Some sidebar content

HTML & CSS Tutorial

Introduction

Basic Web Pages

etc...

JavaScript Tutorial

Introduction

Hello, JavaScript

etc...

© 2017 InternetingIsHard.com


text:
package com.tyutyutyu.api.moly4j.author;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Getter
@NoArgsConstructor
@ToString
public class AuthorWrapper {

	private Author author;

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	  <meta name="author" content="Julian Viso" />
    <meta name="description" content="Personal blog and resume">
    <link rel="favicon" href="static/img/favicon.ico">

      <title>Projects</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ=="
    crossorigin="anonymous">

	<link rel="stylesheet" type="text/css" href="static/css/main.css" />
	<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,200bold,400old" />
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
	<link rel="stylesheet" type="text/css" href="static/css/syntax.css" />

BLOG

PROJECTS

RESUME

Projects

			  Diagramaphone
			- Android app for users who are blind, that allows them to read charts and diagrams through
			the use of an open source OCR, and Android's accessibility services.

			  E-Commerce Database Store
			- Simple web store that manages to keep track of inventories, and user made accounts using MYSQL.

			  UberBerryPi
			- Through the use of Uber's API and speech-to-text on a Raspberry Pi a user will be able to set up an Uber ride. Project mainly consisted of experimenting with geolocations and speech recognition.

              Abusive Gym Reminder
            - Android gym reminder app that sends notifications to the user based on whether or not they missed a gym day.

			  GW2FractalDailies
			- A Discord bot that makes specific game API calls from Arena Net to display information to users.

© All rights reserved. Powered by Jekyll and
            github with ♥


text:
import noMerc from "./noMerc.json";
import noMill from "./noMill.json";
export { noMerc, noMill };
//# sourceMappingURL=index.js.map


text:
package com.fincatto.documentofiscal.cte300.classes;

public enum CTCodigoSituacaoTributariaICMS {

    TRIBUTACAO_INTEGRALMENTE("00", "Tributada integralmente"),
    TRIBUTADA_COM_COBRANCA_ICMS_POR_SUBSTITUICAO_TRIBUTARIA("10", "Tributada com cobrança de ICMS por ST"),
    COM_REDUCAO_BASE_CALCULO("20", "Com redução da base de cálculo"),
    ISENTA_OU_NAO_TRIBUTADA_COM_COBRANCA_ICMS_POR_SUBSTITUICAO_TRIBUTARIA("30", "Isenta ou não tributada com cobrança de ICMS por ST"),
    ISENTA("40", "Isenta"),
    NAO_TRIBUTADO("41", "Não tributada"),
    SUSPENSAO("50", "Suspensão"),
    DIFERIMENTO("51", "Diferimento"),
    ICMS_COBRADO_ANTERIORMENTE_POR_SUBSTITUICAO_TRIBUTARIA("60", "ICMS cobrado anteriormente por ST"),
    COM_REDUCAO_BASE_CALCULO_COBRANCA_ICMS_POR_SUBSTITUICAO_TRIBUTARIA_ICMS_SUBSTITUICAO_TRIBUTARIA("70", "Com redução da base de cálculo Cobrança ICMS por ST/ICMS ST"),
    OUTROS("90", "Outros");

    private final String codigo;
    private final String descricao;

    CTCodigoSituacaoTributariaICMS(final String codigo, final String descricao) {
        this.codigo = codigo;
        this.descricao = descricao;
    }

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

    public String getDescricao() {
        return this.descricao;
    }

    public static CTCodigoSituacaoTributariaICMS valueOfCodigo(final String codigoICMS) {
        for (final CTCodigoSituacaoTributariaICMS icms : CTCodigoSituacaoTributariaICMS.values()) {
            if (icms.getCodigo().equals(codigoICMS)) {
                return icms;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return codigo + " - " + descricao;
    }
}


text:
const assert = require('chai').assert;
const Enemy = require("../lib/enemies.js");

describe("Enemy", function () {

  it('should be a function', function () {
    assert.isFunction(Enemy);
  });

  it('should instantiate Enemy', function () {
    var enemy = new Enemy();
    assert.isObject(enemy);
  });

    context("it allows me to customize it", function () {
      it("should let me assign a height and width", function () {
        var enemy = new Enemy({height:10, width:15});
        assert.strictEqual(enemy.height, 10);
        assert.strictEqual(enemy.width, 15);
      });

      it("should default to 800 for its x coord", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.x, 800);
      });

      it('should assign the width to 50 by default', function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.width, 50);
      });

      it('should assign the height to 35 by default', function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.height, 35);
      });

  });
}); //end of describe Enemy

describe ('enemy', function () {

      it("should have a default width of 50", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.width, 50);
      });

      it("should have a default height of 35", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.height, 35);
      });
      it("should have a default pic of the airplane", function () {
        var enemy = new Enemy();
        assert.strictEqual(enemy.image, "../IMGS/airplane.png");
      });

      it("should have a default speed of equal or less than 3", function () {
        var enemy = new Enemy();
        assert.isBelow(enemy.speed, 3.001);
      });

      it("should have a default y coord of equal or less than 300", function () {
        var enemy = new Enemy();
        assert.isBelow(enemy.y, 301);
      });
}); // end of describe enemy

describe("Enemy.prototype.randomSpeed", function () {
  it("should never assign a speed below 0.5", function () {
    var enemy = new Enemy();
    assert.isAbove(enemy.randomSpeed(), 0.5);
  });

  it("should never assign a speed above 6", function () {
    var enemy = new Enemy();
    assert.isBelow(enemy.randomSpeed(), 6);
  });

}); // end of describe Enemy.prototype.randomSpeed


text:
mkdir -p /opt/hub3/narthex/fuseki/run/configuration
mkdir -p /opt/hub3/narthex/fuseki/run/databases/narthex
/usr/bin/id narthex >/dev/null 2>&1 || /usr/sbin/useradd -U -s /bin/false -c "User for Narthex daemon" -d /opt/hub3/narthex/ narthex
chown -R narthex: /opt/hub3/narthex/fuseki


text:
from django.contrib.admin.templatetags.admin_list import pagination
from django.template import Library

register = Library()

@register.inclusion_tag('admin/pagination_top.html')
def pagination_top(cl):
    return pagination(cl)


text:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class PuppyPlayDate extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = require('./style.js')

AppRegistry.registerComponent('PuppyPlayDate', () => PuppyPlayDate);


text:
using namespace std;

namespace simply
{
    TEST_CLASS(com_test)
    {
    public:
        TEST_METHOD(check_throws_com_error_with_failed_hresult)
        {
            auto e = assert::throws<com_error>([] { check(E_INVALIDARG); });
            assert::is_equal(E_INVALIDARG, e.get()->hresult());
        }

        TEST_METHOD(check_doesnt_throw_with_successful_hresult)
        {
            check(S_FALSE);
        }
    };
}


text:
package org.apache.lens.client;

import org.apache.lens.api.query.QueryResult;
import org.apache.lens.api.query.QueryResultSetMetadata;

/**
 * The Class LensClientResultSet.
 */
public class LensClientResultSet {

  /** The result. */
  private final QueryResult result;

  /** The result set metadata. */
  private final QueryResultSetMetadata resultSetMetadata;

  /**
   * Instantiates a new lens client result set.
   *
   * @param result            the result
   * @param resultSetMetaData the result set meta data
   */
  public LensClientResultSet(QueryResultSetMetadata resultSetMetaData, QueryResult result) {
    this.result = result;
    this.resultSetMetadata = resultSetMetaData;
  }

  public QueryResult getResult() {
    return result;
  }

  public QueryResultSetMetadata getResultSetMetadata() {
    return resultSetMetadata;
  }
}


text:
<!DOCTYPE html>

		<title>Angular Filters</title>

{{welcomeMsg}}

			Name: <input type="text" ng-model="user.name"></input>

			Select Gender <select ng-model="user.gender" ng-options="gender.id as gender.label for gender in genders"></select>

Hi {{user.name | gender: user.gender}}!


text:
/*jshint browser:true */
/*global WebInspector:true, InspectorFrontendHost:true, InspectorBackend:true, importScript:true */
/*global Preferences:true */

// Wire up websocket to talk to backend
WebInspector.loaded = function() {

  var webSocketUrl = function() {
    var a = document.createElement('a');
    // browser will resolve this relative path to an absolute one
    a.href = 'ws';
    a.search = window.location.search;
    a.protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    return a.href;
  }();

  WebInspector.socket = new WebSocket(webSocketUrl);

  WebInspector.socket.onmessage = onWebSocketMessage;
  WebInspector.socket.onerror = onWebSocketError;
  WebInspector.socket.onopen = onWebSocketConnected;
};

var _inspectorInitialized = false;

function onWebSocketError(error) {
  console.error(error);
}

function onWebSocketConnected() {
  if (_inspectorInitialized) return;
  InspectorFrontendHost.sendMessageToBackend = WebInspector.socket.send.bind(WebInspector.socket);

  WebInspector.dockController = new WebInspector.DockController();
  WebInspector.doLoadedDone();

  _inspectorInitialized = true;
}

function onWebSocketMessage(response) {

  var message = response.data;

  if (!message) return;

  if (message === 'showConsole') {
    WebInspector.showConsole();
  } else {
    InspectorBackend.dispatch(message);
  }
}

// Disable HTML & CSS inspections
WebInspector.queryParamsObject['isSharedWorker'] = true;

// disable everything besides scripts and console
// that means 'profiles' and 'timeline' at the moment
WebInspector._orig_panelDescriptors = WebInspector._panelDescriptors;
WebInspector._panelDescriptors = function() {
  var panelDescriptors = this._orig_panelDescriptors();
  return panelDescriptors.filter(function(pd) {
    return ['scripts', 'console'].indexOf(pd.name()) != -1;
  });
};

// Patch the expression used as an initial value for a new watch.
// DevTools' value "\n" breaks the debugger protocol.
importScript('WatchExpressionsSidebarPane.js');
WebInspector.WatchExpressionsSection.NewWatchExpression = '\'\'';

Preferences.localizeUI = false;
Preferences.applicationTitle = 'Node Inspector';

WebInspector._platformFlavor = WebInspector.PlatformFlavor.MacLeopard;

// Front-end uses `eval location.href` to get url of inspected page
// This does not work in node.js from obvious reasons, and cause
// a 'null' message to be printed in front-end console.
// Since Preferences.applicationTitle does not include inspected url,
// we can return arbitrary string as inspected URL.
WebInspector.WorkerManager._calculateWorkerInspectorTitle = function() {
  InspectorFrontendHost.inspectedURLChanged('');
};

// Do not offer download of the edited file when saving changes to V8.
// DevTools' implementation changes window.location which closes
// web-socket connection to the server and thus breaks the inspector.
InspectorFrontendHost.close = function(url, content, forceSaveAs) {
  delete this._fileBuffers[url];
};

// Let DevTools know we can save the content of modified files,
// so that a warning icon is not displayed in the file tab header.
// See UISourceCode.hasUnsavedCommittedChanges to understand why.
WebInspector.extensionServer._onSubscribe(
  {
    type:WebInspector.extensionAPI.Events.ResourceContentCommitted
  },
  {
    postMessage: function(msg) {
      // no-op
    }
  }
);

// Front-end intercepts Cmd+R, Ctrl+R and F5 keys and reloads the debugged
// page instead of the front-end page.  We want to disable this behaviour.
WebInspector._orig_documentKeyDown = WebInspector.documentKeyDown;
WebInspector.documentKeyDown = function(event) {
  switch (event.keyIdentifier) {
    case 'U+0052': // R key
    case 'F5':
      return;
  }
  WebInspector._orig_documentKeyDown(event);
};

var orig_createResourceFromFramePayload =
  WebInspector.ResourceTreeModel.prototype._createResourceFromFramePayload;

WebInspector.ResourceTreeModel.prototype._createResourceFromFramePayload =
  function(frame, url, type, mimeType) {
    // Force Script type for all node frames.
    // Front-end assigns Document type (i.e. HTML) to our main script file.
    if (frame._isNodeInspectorScript) {
      type = WebInspector.resourceTypes.Script;
    }

    return orig_createResourceFromFramePayload(frame, url, type, mimeType);
  };

//
// Open the main application file on startup
//

WebInspector.notifications.addEventListener(
  WebInspector.Events.InspectorLoaded,
  function() {
    WebInspector.resourceTreeModel.addEventListener(
      WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded,
      showMainAppFile,
      null
    );
  },
  null
);

function showMainAppFile() {
  var fileTabs = WebInspector.showPanel('scripts')._editorContainer._files;
  if (Object.keys(fileTabs).length > 0){
    // Some files are already opened - do not change user's workspace
    return;
  }

  var uiSourceCodes = getAllUiSourceCodes();
  var uriToShow = WebInspector.inspectedPageURL;

  for (var i in uiSourceCodes) {
    if (uiSourceCodes[i].uri() !== uriToShow) continue;
    WebInspector.showPanel('scripts').showUISourceCode(uiSourceCodes[i]);
    return true;
  }

  console.error('Cannot show the main application file ', uriToShow);
}

function getAllUiSourceCodes() {
  // Based on FilteredItemSectionDialog.js > SelectUISourceCodeDialog()
  var projects = WebInspector.workspace.projects();
  var uiSourceCodes = [];
  var projectFiles;

  for (var i = 0; i < projects.length; ++i) {
    projectFiles = projects[i]
      .uiSourceCodes()
      .filter(nameIsNotEmpty);
    uiSourceCodes = uiSourceCodes.concat(projectFiles);
  }

  return uiSourceCodes;

  function nameIsNotEmpty(p) {
    return p.name();
  }
}

var oldDetached = WebInspector.detached;
WebInspector.detached = function () {
  oldDetached.apply(this, arguments);
  setTimeout(function () {
    location.reload();
  }, 400);
};


text:
/*	$NetBSD: sdp_compat.c,v 1.2 2009/05/14 19:12:45 plunky Exp $	*/

/*-
 * Copyright (c) 2006 Itronix Inc.
 * All rights reserved.
 *
 * Written by Iain Hibbert for Itronix Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of Itronix Inc. may not be used to endorse
 *    or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*-
 * Copyright (c) 2001-2003 Maksim Yevmenkin <m_evmenkin@yahoo.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * This file provides compatibility with the original library API,
 * use -DSDP_COMPAT to access it.
 *
 * These functions are deprecated and will be removed eventually.
 *
 *	sdp_open(laddr, raddr)
 *	sdp_open_local(control)
 *	sdp_close(session)
 *	sdp_error(session)
 *	sdp_search(session, plen, protos, alen, attrs, vlen, values)
 *	sdp_register_service(session, uuid, bdaddr, data, datalen, handle)
 *	sdp_change_service(session, handle, data, datalen)
 *	sdp_unregister_service(session, handle)
 *	sdp_attr2desc(attribute)
 *	sdp_uuid2desc(uuid16)
 *	sdp_print(level, start, end)
 */
#define SDP_COMPAT

#include <sys/cdefs.h>
__RCSID("$NetBSD: sdp_compat.c,v 1.2 2009/05/14 19:12:45 plunky Exp $");

#include <errno.h>
#include <sdp.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "sdp-int.h"

struct sdp_compat {
	sdp_session_t	ss;
	int		error;
	uint8_t		buf[256];
};

void *
sdp_open(bdaddr_t const *l, bdaddr_t const *r)
{
	struct sdp_compat *sc;

	sc = malloc(sizeof(struct sdp_compat));
	if (sc == NULL)
		return NULL;

	if (l == NULL || r == NULL) {
		sc->error = EINVAL;
		return sc;
	}

	sc->ss = _sdp_open(l, r);
	if (sc->ss == NULL) {
		sc->error = errno;
		return sc;
	}

	sc->error = 0;
	return sc;
}

void *
sdp_open_local(char const *control)
{
	struct sdp_compat *sc;

	sc = malloc(sizeof(struct sdp_compat));
	if (sc == NULL)
		return NULL;

	sc->ss = _sdp_open_local(control);
	if (sc->ss == NULL) {
		sc->error = errno;
		return sc;
	}

	sc->error = 0;
	return sc;
}

int32_t
sdp_close(void *xss)
{
	struct sdp_compat *sc = xss;

	if (sc == NULL)
		return 0;

	if (sc->ss != NULL)
		_sdp_close(sc->ss);

	free(sc);

	return 0;
}

int32_t
sdp_error(void *xss)
{
	struct sdp_compat *sc = xss;

	if (sc == NULL)
		return EINVAL;

	return sc->error;
}

int32_t
sdp_search(void *xss, uint32_t plen, uint16_t const *pp, uint32_t alen,
    uint32_t const *ap, uint32_t vlen, sdp_attr_t *vp)
{
	struct sdp_compat *sc = xss;
	sdp_data_t seq, ssp, ail, rsp, value;
	uint16_t attr;
	size_t i;
	bool rv;

	if (sc == NULL)
		return -1;

	if (plen == 0 || pp == NULL || alen == 0 || ap == NULL) {
		sc->error = EINVAL;
		return -1;
	}

	/*
	 * encode ServiceSearchPattern
	 */
	ssp.next = sc->buf;
	ssp.end = sc->buf + sizeof(sc->buf);
	for (i = 0; i < plen; i++)
		sdp_put_uuid16(&ssp, pp[i]);

	ssp.end = ssp.next;
	ssp.next = sc->buf;

	/*
	 * encode AttributeIDList
	 */
	ail.next = ssp.end;
	ail.end = sc->buf + sizeof(sc->buf);
	for (i = 0; i < alen; i++)
		sdp_put_uint32(&ail, ap[i]);

	ail.end = ail.next;
	ail.next = ssp.end;

	/*
	 * perform ServiceSearchAttribute transaction
	 */
	rv = sdp_service_search_attribute(sc->ss, &ssp, &ail, &rsp);
	if (rv == false) {
		sc->error = errno;
		return -1;
	}

	if (vp == NULL)
		return 0;

	/*
	 * The response buffer is a list of data element sequences,
	 * each containing a list of attribute/value pairs. We want to
	 * parse those to the attribute array that the user passed in.
	 */
	while (vlen > 0 && sdp_get_seq(&rsp, &seq)) {
		while (vlen > 0 && sdp_get_attr(&seq, &attr, &value)) {
			vp->attr = attr;
			if (vp->value != NULL) {
				if (value.end - value.next > (ssize_t)vp->vlen) {
					vp->flags = SDP_ATTR_TRUNCATED;
				} else {
					vp->flags = SDP_ATTR_OK;
					vp->vlen = value.end - value.next;
				}
				memcpy(vp->value, value.next, vp->vlen);
			} else {
				vp->flags = SDP_ATTR_INVALID;
			}

			vp++;
			vlen--;
		}
	}

	while (vlen-- > 0)
		vp++->flags = SDP_ATTR_INVALID;

	return 0;
}

int32_t
sdp_register_service(void *xss, uint16_t uuid, bdaddr_t *bdaddr,
    uint8_t *data, uint32_t datalen, uint32_t *handle)
{
	struct sdp_compat *sc = xss;
	struct iovec req[4];
	ssize_t len;

	if (sc == NULL)
		return -1;

	if (bdaddr == NULL || data == NULL || datalen == 0) {
		sc->error = EINVAL;
		return -1;
	}

	uuid = htobe16(uuid);
	req[1].iov_base = &uuid;
	req[1].iov_len = sizeof(uint16_t);

	req[2].iov_base = bdaddr;
	req[2].iov_len = sizeof(bdaddr_t);

	req[3].iov_base = data;
	req[3].iov_len = datalen;

	if (!_sdp_send_pdu(sc->ss, SDP_PDU_SERVICE_REGISTER_REQUEST,
	    req, __arraycount(req))) {
		sc->error = errno;
		return -1;
	}

	len = _sdp_recv_pdu(sc->ss, SDP_PDU_ERROR_RESPONSE);
	if (len == -1) {
		sc->error = errno;
		return -1;
	}

	if (len != sizeof(uint16_t) + sizeof(uint32_t)
	    || be16dec(sc->ss->ibuf) != 0) {
		sc->error = EIO;
		return -1;
	}

	if (handle != NULL)
		*handle = be32dec(sc->ss->ibuf + sizeof(uint16_t));

	return 0;
}

int32_t
sdp_change_service(void *xss, uint32_t handle,
    uint8_t *data, uint32_t datalen)
{
	struct sdp_compat *sc = xss;
	struct iovec req[3];
	ssize_t len;

	if (data == NULL || datalen == 0) {
		sc->error = EINVAL;
		return -1;
	}

	handle = htobe32(handle);
	req[1].iov_base = &handle;
	req[1].iov_len = sizeof(uint32_t);

	req[2].iov_base = data;
	req[2].iov_len = datalen;

	if (!_sdp_send_pdu(sc->ss, SDP_PDU_SERVICE_CHANGE_REQUEST,
	    req, __arraycount(req))) {
		sc->error = errno;
		return -1;
	}

	len = _sdp_recv_pdu(sc->ss, SDP_PDU_ERROR_RESPONSE);
	if (len == -1) {
		sc->error = errno;
		return -1;
	}

	if (len != sizeof(uint16_t)
	    || be16dec(sc->ss->ibuf) != 0) {
		sc->error = EIO;
		return -1;
	}

	return 0;
}

int32_t
sdp_unregister_service(void *xss, uint32_t handle)
{
	struct sdp_compat *sc = xss;
	struct iovec req[2];
	ssize_t len;

	handle = htobe32(handle);
	req[1].iov_base = &handle;
	req[1].iov_len = sizeof(uint32_t);

	if (!_sdp_send_pdu(sc->ss, SDP_PDU_SERVICE_UNREGISTER_REQUEST,
	    req, __arraycount(req))) {
		sc->error = errno;
		return -1;
	}

	len = _sdp_recv_pdu(sc->ss, SDP_PDU_ERROR_RESPONSE);
	if (len == -1) {
		sc->error = errno;
		return -1;
	}

	if (len != sizeof(uint16_t)
	    || be16dec(sc->ss->ibuf) != 0) {
		sc->error = EIO;
		return -1;
	}

	return 0;
}

/*
 * SDP attribute description
 */

struct sdp_attr_desc {
	uint32_t	 attr;
	char const	*desc;
};
typedef struct sdp_attr_desc	sdp_attr_desc_t;
typedef struct sdp_attr_desc *	sdp_attr_desc_p;

static sdp_attr_desc_t	sdp_uuids_desc[] = {
{ SDP_UUID_PROTOCOL_SDP, "SDP", },
{ SDP_UUID_PROTOCOL_UDP, "UDP", },
{ SDP_UUID_PROTOCOL_RFCOMM, "RFCOMM", },
{ SDP_UUID_PROTOCOL_TCP, "TCP", },
{ SDP_UUID_PROTOCOL_TCS_BIN, "TCS BIN", },
{ SDP_UUID_PROTOCOL_TCS_AT, "TCS AT", },
{ SDP_UUID_PROTOCOL_OBEX, "OBEX", },
{ SDP_UUID_PROTOCOL_IP, "IP", },
{ SDP_UUID_PROTOCOL_FTP, "FTP", },
{ SDP_UUID_PROTOCOL_HTTP, "HTTP", },
{ SDP_UUID_PROTOCOL_WSP, "WSP", },
{ SDP_UUID_PROTOCOL_BNEP, "BNEP", },
{ SDP_UUID_PROTOCOL_UPNP, "UPNP", },
{ SDP_UUID_PROTOCOL_HIDP, "HIDP", },
{ SDP_UUID_PROTOCOL_HARDCOPY_CONTROL_CHANNEL, "Hardcopy Control Channel", },
{ SDP_UUID_PROTOCOL_HARDCOPY_DATA_CHANNEL, "Hardcopy Data Channel", },
{ SDP_UUID_PROTOCOL_HARDCOPY_NOTIFICATION, "Hardcopy Notification", },
{ SDP_UUID_PROTOCOL_AVCTP, "AVCTP", },
{ SDP_UUID_PROTOCOL_AVDTP, "AVDTP", },
{ SDP_UUID_PROTOCOL_CMPT, "CMPT", },
{ SDP_UUID_PROTOCOL_UDI_C_PLANE, "UDI C-Plane", },
{ SDP_UUID_PROTOCOL_L2CAP, "L2CAP", },
/* Service Class IDs/Bluetooth Profile IDs */
{ SDP_SERVICE_CLASS_SERVICE_DISCOVERY_SERVER, "Service Discovery Server", },
{ SDP_SERVICE_CLASS_BROWSE_GROUP_DESCRIPTOR, "Browse Group Descriptor", },
{ SDP_SERVICE_CLASS_PUBLIC_BROWSE_GROUP, "Public Browse Group", },
{ SDP_SERVICE_CLASS_SERIAL_PORT, "Serial Port", },
{ SDP_SERVICE_CLASS_LAN_ACCESS_USING_PPP, "LAN Access Using PPP", },
{ SDP_SERVICE_CLASS_DIALUP_NETWORKING, "Dial-Up Networking", },
{ SDP_SERVICE_CLASS_IR_MC_SYNC, "IrMC Sync", },
{ SDP_SERVICE_CLASS_OBEX_OBJECT_PUSH, "OBEX Object Push", },
{ SDP_SERVICE_CLASS_OBEX_FILE_TRANSFER, "OBEX File Transfer", },
{ SDP_SERVICE_CLASS_IR_MC_SYNC_COMMAND, "IrMC Sync Command", },
{ SDP_SERVICE_CLASS_HEADSET, "Headset", },
{ SDP_SERVICE_CLASS_CORDLESS_TELEPHONY, "Cordless Telephony", },
{ SDP_SERVICE_CLASS_AUDIO_SOURCE, "Audio Source", },
{ SDP_SERVICE_CLASS_AUDIO_SINK, "Audio Sink", },
{ SDP_SERVICE_CLASS_AV_REMOTE_CONTROL_TARGET, "A/V Remote Control Target", },
{ SDP_SERVICE_CLASS_ADVANCED_AUDIO_DISTRIBUTION, "Advanced Audio Distribution", },
{ SDP_SERVICE_CLASS_AV_REMOTE_CONTROL, "A/V Remote Control", },
{ SDP_SERVICE_CLASS_VIDEO_CONFERENCING, "Video Conferencing", },
{ SDP_SERVICE_CLASS_INTERCOM, "Intercom", },
{ SDP_SERVICE_CLASS_FAX, "Fax", },
{ SDP_SERVICE_CLASS_HEADSET_AUDIO_GATEWAY, "Headset Audio Gateway", },
{ SDP_SERVICE_CLASS_WAP, "WAP", },
{ SDP_SERVICE_CLASS_WAP_CLIENT, "WAP Client", },
{ SDP_SERVICE_CLASS_PANU, "PANU", },
{ SDP_SERVICE_CLASS_NAP, "Network Access Point", },
{ SDP_SERVICE_CLASS_GN, "GN", },
{ SDP_SERVICE_CLASS_DIRECT_PRINTING, "Direct Printing", },
{ SDP_SERVICE_CLASS_REFERENCE_PRINTING, "Reference Printing", },
{ SDP_SERVICE_CLASS_IMAGING, "Imaging", },
{ SDP_SERVICE_CLASS_IMAGING_RESPONDER, "Imaging Responder", },
{ SDP_SERVICE_CLASS_IMAGING_AUTOMATIC_ARCHIVE, "Imaging Automatic Archive", },
{ SDP_SERVICE_CLASS_IMAGING_REFERENCED_OBJECTS, "Imaging Referenced Objects", },
{ SDP_SERVICE_CLASS_HANDSFREE, "Handsfree", },
{ SDP_SERVICE_CLASS_HANDSFREE_AUDIO_GATEWAY, "Handsfree Audio Gateway", },
{ SDP_SERVICE_CLASS_DIRECT_PRINTING_REFERENCE_OBJECTS, "Direct Printing Reference Objects", },
{ SDP_SERVICE_CLASS_REFLECTED_UI, "Reflected UI", },
{ SDP_SERVICE_CLASS_BASIC_PRINTING, "Basic Printing", },
{ SDP_SERVICE_CLASS_PRINTING_STATUS, "Printing Status", },
{ SDP_SERVICE_CLASS_HUMAN_INTERFACE_DEVICE, "Human Interface Device", },
{ SDP_SERVICE_CLASS_HARDCOPY_CABLE_REPLACEMENT, "Hardcopy Cable Replacement", },
{ SDP_SERVICE_CLASS_HCR_PRINT, "HCR Print", },
{ SDP_SERVICE_CLASS_HCR_SCAN, "HCR Scan", },
{ SDP_SERVICE_CLASS_COMMON_ISDN_ACCESS, "Common ISDN Access", },
{ SDP_SERVICE_CLASS_VIDEO_CONFERENCING_GW, "Video Conferencing Gateway", },
{ SDP_SERVICE_CLASS_UDI_MT, "UDI MT", },
{ SDP_SERVICE_CLASS_UDI_TA, "UDI TA", },
{ SDP_SERVICE_CLASS_AUDIO_VIDEO, "Audio/Video", },
{ SDP_SERVICE_CLASS_SIM_ACCESS, "SIM Access", },
{ SDP_SERVICE_CLASS_PNP_INFORMATION, "PNP Information", },
{ SDP_SERVICE_CLASS_GENERIC_NETWORKING, "Generic Networking", },
{ SDP_SERVICE_CLASS_GENERIC_FILE_TRANSFER, "Generic File Transfer", },
{ SDP_SERVICE_CLASS_GENERIC_AUDIO, "Generic Audio", },
{ SDP_SERVICE_CLASS_GENERIC_TELEPHONY, "Generic Telephony", },
{ SDP_SERVICE_CLASS_UPNP, "UPNP", },
{ SDP_SERVICE_CLASS_UPNP_IP, "UPNP IP", },
{ SDP_SERVICE_CLASS_ESDP_UPNP_IP_PAN, "ESDP UPNP IP PAN", },
{ SDP_SERVICE_CLASS_ESDP_UPNP_IP_LAP, "ESDP UPNP IP LAP", },
{ SDP_SERVICE_CLASS_ESDP_UPNP_L2CAP, "ESDP UPNP L2CAP", },
{ 0xffff, NULL, }
};

static sdp_attr_desc_t	sdp_attrs_desc[] = {
{ SDP_ATTR_SERVICE_RECORD_HANDLE,
  "Record handle",
  },
{ SDP_ATTR_SERVICE_CLASS_ID_LIST,
  "Service Class ID list",
  },
{ SDP_ATTR_SERVICE_RECORD_STATE,
  "Service Record State",
  },
{ SDP_ATTR_SERVICE_ID,
  "Service ID",
  },
{ SDP_ATTR_PROTOCOL_DESCRIPTOR_LIST,
  "Protocol Descriptor List",
  },
{ SDP_ATTR_BROWSE_GROUP_LIST,
  "Browse Group List",
  },
{ SDP_ATTR_LANGUAGE_BASE_ATTRIBUTE_ID_LIST,
  "Language Base Attribute ID List",
  },
{ SDP_ATTR_SERVICE_INFO_TIME_TO_LIVE,
  "Service Info Time-To-Live",
  },
{ SDP_ATTR_SERVICE_AVAILABILITY,
  "Service Availability",
  },
{ SDP_ATTR_BLUETOOTH_PROFILE_DESCRIPTOR_LIST,
  "Bluetooh Profile Descriptor List",
  },
{ SDP_ATTR_DOCUMENTATION_URL,
  "Documentation URL",
  },
{ SDP_ATTR_CLIENT_EXECUTABLE_URL,
  "Client Executable URL",
  },
{ SDP_ATTR_ICON_URL,
  "Icon URL",
  },
{ SDP_ATTR_ADDITIONAL_PROTOCOL_DESCRIPTOR_LISTS,
  "Additional Protocol Descriptor Lists" },
{ SDP_ATTR_GROUP_ID,
/*SDP_ATTR_IP_SUBNET,
  SDP_ATTR_VERSION_NUMBER_LIST*/
  "Group ID/IP Subnet/Version Number List",
  },
{ SDP_ATTR_SERVICE_DATABASE_STATE,
  "Service Database State",
  },
{ SDP_ATTR_SERVICE_VERSION,
  "Service Version",
  },
{ SDP_ATTR_EXTERNAL_NETWORK,
/*SDP_ATTR_NETWORK,
  SDP_ATTR_SUPPORTED_DATA_STORES_LIST*/
  "External Network/Network/Supported Data Stores List",
  },
{ SDP_ATTR_FAX_CLASS1_SUPPORT,
/*SDP_ATTR_REMOTE_AUDIO_VOLUME_CONTROL*/
  "Fax Class1 Support/Remote Audio Volume Control",
  },
{ SDP_ATTR_FAX_CLASS20_SUPPORT,
/*SDP_ATTR_SUPPORTED_FORMATS_LIST*/
  "Fax Class20 Support/Supported Formats List",
  },
{ SDP_ATTR_FAX_CLASS2_SUPPORT,
  "Fax Class2 Support",
  },
{ SDP_ATTR_AUDIO_FEEDBACK_SUPPORT,
  "Audio Feedback Support",
  },
{ SDP_ATTR_NETWORK_ADDRESS,
  "Network Address",
  },
{ SDP_ATTR_WAP_GATEWAY,
  "WAP Gateway",
  },
{ SDP_ATTR_HOME_PAGE_URL,
  "Home Page URL",
  },
{ SDP_ATTR_WAP_STACK_TYPE,
  "WAP Stack Type",
  },
{ SDP_ATTR_SECURITY_DESCRIPTION,
  "Security Description",
  },
{ SDP_ATTR_NET_ACCESS_TYPE,
  "Net Access Type",
  },
{ SDP_ATTR_MAX_NET_ACCESS_RATE,
  "Max Net Access Rate",
  },
{ SDP_ATTR_IPV4_SUBNET,
  "IPv4 Subnet",
  },
{ SDP_ATTR_IPV6_SUBNET,
  "IPv6 Subnet",
  },
{ SDP_ATTR_SUPPORTED_CAPABALITIES,
  "Supported Capabalities",
  },
{ SDP_ATTR_SUPPORTED_FEATURES,
  "Supported Features",
  },
{ SDP_ATTR_SUPPORTED_FUNCTIONS,
  "Supported Functions",
  },
{ SDP_ATTR_TOTAL_IMAGING_DATA_CAPACITY,
  "Total Imaging Data Capacity",
  },
{ 0xffff, NULL, }
};

char const *
sdp_attr2desc(uint16_t attr)
{
	register sdp_attr_desc_p	a = sdp_attrs_desc;

	for (; a->desc != NULL; a++)
		if (attr == a->attr)
			break;

	return ((a->desc != NULL)? a->desc : "Unknown");
}

char const *
sdp_uuid2desc(uint16_t uuid)
{
	register sdp_attr_desc_p	a = sdp_uuids_desc;

	for (; a->desc != NULL; a++)
		if (uuid == a->attr)
			break;

	return ((a->desc != NULL)? a->desc : "Unknown");
}

void
sdp_print(uint32_t level, uint8_t *start, uint8_t const *end)
{

	(void)_sdp_data_print(start, end, level);
}


text:
package main.java.de.c4.controller.shared.listener;

import main.java.de.c4.model.messages.ContactDto;

public interface ContactListReceivedListener {

	public void receivedContactList(ContactDto[] list);

}