text:
__version__ = "0.1.10"

import argparse, json, os.path, sys
import jinja2, requests

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-i", "--input",
        default="swagger.json",
        help="path to or URL of the Swagger JSON file (default: swagger.json)",
        metavar="SWAGGER_LOCATION"
    )

    parser.add_argument(
        "-a", "--additional",
        default=None,
        help="path to or URL of an complementary Swagger JSON file",
        metavar="SWAGGER_LOCATION"
    )

    parser.add_argument(
        "-o", "--output",
        default="swagger.md",
        help="path to the output Markdown file (default: swagger.md)",
        metavar="OUTPUT"
    )

    parser.add_argument(
        "-t", "--template",
        default=os.path.join(os.path.dirname(__file__), "swagger.md.j2"),
        help="Jinja2 template used for conversion",
        metavar="TEMPLATE"
    )

    parser.add_argument(
        "-v", "--version",
        action="version",
        version="swagger2markdown " + __version__
    )

    args = parser.parse_args()

    print("Parsing Swagger JSON... ", end="")

    try:
        swagger_data = json.load(open(args.input, encoding="utf8"))

    except (FileNotFoundError, OSError):
        try:
            swagger_data = requests.get(args.input).json()
        except requests.exceptions.MissingSchema:
            sys.exit('Please specify the URL with schema, e.g. "http://"')
        except requests.exceptions.ConnectionError:
            sys.exit("No Swagger file found.")

    if args.additional:
        try:
            additional_data = json.load(open(args.additional, encoding="utf8"))
        except (FileNotFoundError, OSError):
            try:
                additional_data = requests.get(args.additional).json()
            except requests.exceptions.MissingSchema:
                sys.exit('Please specify the URL with schema, e.g. "http://"')
            except requests.exceptions.ConnectionError:
                sys.exit("No Swagger file found.")
    else:
        additional_data = {}

    swagger_data = {**additional_data, **swagger_data}

    print("Done!")

    print("Parsing the template... ", end="")

    env = jinja2.Environment(extensions=["jinja2.ext.do"])
    template = env.from_string(open(args.template, encoding="utf8").read())

    print("Done!")

    print("Baking Markdown... ", end="")

    with open(args.output, "w", encoding="utf8") as output:
        output.write(template.render(swagger_data=swagger_data))
    print("Done!")

    print("---")

    print("Result: ", args.output)

redpajama_set_name: RedPajamaGithub


text:
package org.contikios.coffee;

import java.io.IOException;

public class CoffeeMicroLog extends CoffeeFile {
	private int logRecords;
	private int logRecordSize;
	private int indexStart;
	private int indexSize;
	private int recordStart;
	private int[] index;

	public CoffeeMicroLog(CoffeeFS fs, CoffeeHeader header)
			throws IOException {
		super(fs, header);

		CoffeeConfiguration conf = fs.getConfiguration();
		if (header.logRecordSize == 0) {
			logRecordSize = conf.pageSize;
		}
		if (header.logRecords == 0) {
			logRecords = conf.defaultLogSize / logRecordSize;
		} else {
			logRecords = header.logRecords;
		}

		indexStart = header.getPage() * conf.pageSize +
			     header.rawLength();
		/* An index entry uses two bytes. */
		indexSize = logRecords * 2;
		recordStart = indexStart + indexSize;

		index = new int[logRecords];
		byte[] bytes = new byte[2];

		for (int i = 0; i < logRecords; i++) {
			coffeeFS.getImage().read(bytes, bytes.length,
				indexStart + i * 2);
			index[i] = bytes[1] << 8 | bytes[0];
		}
	}

	public byte[] getRegion(int region) throws IOException {
		for (int i = logRecords - 1; i >= 0; i--) {
			if (index[i] - 1 == region) {
				byte[] bytes = new byte[logRecordSize];
				coffeeFS.getImage().read(bytes, bytes.length,
					recordStart + i * logRecordSize);
				return bytes;
			}
		}

		return null;
	}

	public int getLogRecords() {
		return logRecords;
	}

	public int getLogRecordSize() {
		return logRecordSize;
	}
}


text:
package jenkins.plugins.fauxpasapp;

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

import jenkins.plugins.fauxpasapp.commands.BuildContext;
import jenkins.plugins.fauxpasapp.commands.Command;

public class CommandExecutor
{
    public static final int SUCCESS = 0;
    public static final int FAILURE = 1;

    private final List<Command> commands = new ArrayList<Command>();

    private CommandExecutor(Command command)
    {
        commands.add(command);
    }

    public static CommandExecutor execute(Command command)
    {
        return new CommandExecutor(command);
    }

    public CommandExecutor and(Command command)
    {
        commands.add(command);
        return this;
    }

    public int withContext(BuildContext context)
    {
        for (Command command : commands)
        {
            try
            {
                return command.execute(context);
            }
            catch (Exception e)
            {
                context.log("Error executing command: " + command + "\n" +
                            "Exception: " + e.getClass() + " " + e.getMessage());
            }
        }
        return FAILURE;
    }
}


text:
"""This module implements the low level device API.

This module exposes a low level SecurityKey class,
representing the physical security key device.
"""
import logging

from pyu2f import apdu
from pyu2f import errors

class SecurityKey(object):
  """Low level api for talking to a security key.

  This class implements the low level api specified in FIDO
  U2F for talking to a security key.
  """

  def __init__(self, transport):
    self.transport = transport
    self.use_legacy_format = False
    self.logger = logging.getLogger('pyu2f.hardware')

  def CmdRegister(self, challenge_param, app_param):
    """Register security key.

    Ask the security key to register with a particular origin & client.

    Args:
      challenge_param: Arbitrary 32 byte challenge string.
      app_param: Arbitrary 32 byte applciation parameter.

    Returns:
      A binary structure containing the key handle, attestation, and a
      signature over that by the attestation key.  The precise format
      is dictated by the FIDO U2F specs.

    Raises:
      TUPRequiredError: A Test of User Precense is required to proceed.
      ApduError: Something went wrong on the device.
    """
    self.logger.debug('CmdRegister')
    if len(challenge_param) != 32 or len(app_param) != 32:
      raise errors.InvalidRequestError()

    body = bytearray(challenge_param + app_param)
    response = self.InternalSendApdu(apdu.CommandApdu(
        0,
        apdu.CMD_REGISTER,
        0x03,  # Per the U2F reference code tests
        0x00,
        body))
    response.CheckSuccessOrRaise()

    return response.body

  def CmdAuthenticate(self,
                      challenge_param,
                      app_param,
                      key_handle,
                      check_only=False):
    """Attempt to obtain an authentication signature.

    Ask the security key to sign a challenge for a particular key handle
    in order to authenticate the user.

    Args:
      challenge_param: SHA-256 hash of client_data object.
      app_param: SHA-256 hash of the app id.
      key_handle: The key handle to use to issue the signature
      check_only: If true, only check if key_handle is valid.

    Returns:
      A binary structure containing the key handle, attestation, and a
      signature over that by the attestation key.  The precise format
      is dictated by the FIDO U2F specs.

    Raises:
      TUPRequiredError: If check_only is False, a Test of User Precense
          is required to proceed.  If check_only is True, this means
          the key_handle is valid.
      InvalidKeyHandleError: The key_handle is not valid for this device.
      ApduError: Something else went wrong on the device.
    """
    self.logger.debug('CmdAuthenticate')
    if len(challenge_param) != 32 or len(app_param) != 32:
      raise errors.InvalidRequestError()
    control = 0x07 if check_only else 0x03

    body = bytearray(challenge_param + app_param + bytearray([len(key_handle)])
                     + key_handle)
    response = self.InternalSendApdu(apdu.CommandApdu(
        0, apdu.CMD_AUTH, control, 0x00, body))
    response.CheckSuccessOrRaise()

    return response.body

  def CmdVersion(self):
    """Obtain the version of the device and test transport format.

    Obtains the version of the device and determines whether to use ISO
    7816-4 or the U2f variant.  This function should be called at least once
    before CmdAuthenticate or CmdRegister to make sure the object is using the
    proper transport for the device.

    Returns:
      The version of the U2F protocol in use.
    """
    self.logger.debug('CmdVersion')
    response = self.InternalSendApdu(apdu.CommandApdu(
        0, apdu.CMD_VERSION, 0x00, 0x00))

    if not response.IsSuccess():
      raise errors.ApduError(response.sw1, response.sw2)

    return response.body

  def CmdBlink(self, time):
    self.logger.debug('CmdBlink')
    self.transport.SendBlink(time)

  def CmdWink(self):
    self.logger.debug('CmdWink')
    self.transport.SendWink()

  def CmdPing(self, data):
    self.logger.debug('CmdPing')
    return self.transport.SendPing(data)

  def InternalSendApdu(self, apdu_to_send):
    """Send an APDU to the device.

    Sends an APDU to the device, possibly falling back to the legacy
    encoding format that is not ISO7816-4 compatible.

    Args:
      apdu_to_send: The CommandApdu object to send

    Returns:
      The ResponseApdu object constructed out of the devices reply.
    """
    response = None
    if not self.use_legacy_format:
      response = apdu.ResponseApdu(self.transport.SendMsgBytes(
          apdu_to_send.ToByteArray()))
      if response.sw1 == 0x67 and response.sw2 == 0x00:
        # If we failed using the standard format, retry with the
        # legacy format.
        self.use_legacy_format = True
        return self.InternalSendApdu(apdu_to_send)
    else:
      response = apdu.ResponseApdu(self.transport.SendMsgBytes(
          apdu_to_send.ToLegacyU2FByteArray()))
    return response


text:
package org.apache.camel.component.johnzon;

import java.math.BigDecimal;
import java.util.Comparator;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class JohnzonAttributeOrderTest extends CamelTestSupport {

    final String expectedJson = "{\"bool\":true,\"bg\":123.123,\"doubleNumber\":123.123,\"intNumber\":123,\"floatNumber\":123.0,\"longNumber\":123}";

    @Test
    public void testMarshalAndUnmarshalMap() throws Exception {
        NumberPojo nc = new NumberPojo();
        nc.setBg(new BigDecimal("123.123"));
        nc.setDoubleNumber(123.123);
        nc.setBool(true);
        nc.setFloatNumber(123);
        nc.setLongNumber(123L);
        nc.setIntNumber(123);

        MockEndpoint mock = getMockEndpoint("mock:reverse");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(NumberPojo.class);
        mock.message(0).body().isEqualTo(nc);

        Object marshalled = template.requestBody("direct:in", nc);
        String marshalledAsString = context.getTypeConverter().convertTo(String.class, marshalled);
        assertEquals(expectedJson, marshalledAsString);

        template.sendBody("direct:back", marshalled);

        mock.assertIsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {

            @Override
            public void configure() {
                final Comparator<String> attributeOrder = new Comparator<String>() {
                    @Override
                    public int compare(final String o1, final String o2) {
                        return expectedJson.indexOf(o1) - expectedJson.indexOf(o2);
                    }
                };
                JohnzonDataFormat format = new JohnzonDataFormat(NumberPojo.class);
                format.setAttributeOrder(attributeOrder);

                from("direct:in").marshal(format);
                from("direct:back").unmarshal(format).to("mock:reverse");
            }
        };
    }

}


text:
/*
 *  Exception.h: Base exception class
 *
 *  Written by:
 *   Steven G. Parker
 *   Department of Computer Science
 *   University of Utah
 *   March 2000
 *
 *  Copyright (C) 2000 SCI Group
 */

#include <Core/Exceptions/Exception.h>
#include <errno.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#ifndef _WIN32
#include <unistd.h>
#else
#define strcasecmp stricmp
#include <io.h>
#include <process.h>
#include "StackWalker.h"
#endif
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string.h>
#ifdef HAVE_EXC
#include <libexc.h>
#elif defined(__GNUC__) && defined(__linux)
#include <execinfo.h>
#include <cxxabi.h>
#include <dlfcn.h>
#endif

#if defined(_AIX)
// Needed for strcasecmp on aix 4.3 (on 5.1 we don't need this.)
// currently blue is 4.3.
#  include <strings.h>
#endif

namespace Manta {

using namespace std;

Exception::Exception()
{
  stacktrace_ = strdup(getStackTrace().c_str());
}

Exception::~Exception() throw()
{
  if(stacktrace_) {
    free((char*)stacktrace_);
    stacktrace_ = 0;
  }
}

void Exception::sci_throw(const Exception& exc)
{
  // This is a function invoked by the SCI_THROW macro.  It
  // can be useful for tracking down fatal errors, since the
  // normal exception mechanism will unwind the stack before
  // you can get anything useful out of it.

  // Set this environment variable if you want to have a default
  // response to the question below.  Value values are:
  // ask, dbx, throw, abort
  const char* emode = getenv("SCI_EXCEPTIONMODE");
  if(!emode)
    emode = "dbx"; // Default exceptionmode

  // If the mode is not "throw", we print out a message
  if(strcasecmp(emode, "throw") != 0){
    cerr << "\n\nAn exception was thrown.  Msg: " << exc.message() << "\n";
    if(exc.stacktrace_){
      cerr << exc.stacktrace_;
    }
    // Print out the exception type (clasname) and the message
    cerr << "\nException type: " << exc.type() << '\n';
    cerr << "Exception message: " << exc.message() << '\n';
  }
  // See what we should do
  for(;;){
    if(strcasecmp(emode, "ask") == 0){
      // Ask the user
      cerr << "\nthrow(t)/gdb(d)/abort(a)? ";
      emode=0;
      while(!emode){
        char action;
        char buf[100];
        while(read(fileno(stdin), buf, 100) <= 0){
          if(errno != EINTR){
            cerr <<  "\nCould not read response, throwing exception\n";
            emode = "throw";
            break;
          }
        }
        action=buf[0];
        switch(action){
        case 't': case 'T':
          emode="throw";
          break;
        case 'd': case 'D':
          emode="dbx";
          break;
        case 'a': case 'A':
          emode="abort";
          break;
        default:
          break;
        }
      }
    }

    if(strcasecmp(emode, "throw") == 0) {
      // We cannot throw from here, so we just return and the
      // exception will be thrown by the SCI_THROW macro
      return;
    } else if(strcasecmp(emode, "dbx") == 0){
#if defined( REDSTORM )
      cout << "Error: running debugger at exception is not supported on RedStorm\n";
#else
      // Fire up the debugger
      char command[100];
      if(getenv("SCI_DBXCOMMAND")){
        sprintf(command, getenv("SCI_DBXCOMMAND"), getpid());
      } else {
      cout << "Error: running debugger at exception is not supported on RedStorm\n";
#ifdef HAVE_EXC
        sprintf(command, "winterm -c dbx -p %d &", getpid());
#else
        sprintf(command, "xterm -e gdb -c %d&", getpid());
#endif
      }
      cerr << "Starting: " << command << '\n';
      system(command);
      emode="ask";
#endif
    } else if(strcasecmp(emode, "abort") == 0){
      // This will trigger the thread library, but we cannot
      // directly call the thread library here or it would create
      // a circular dependency
      abort();
    } else {
      cerr << "Unknown exception mode: " << emode << ", aborting\n";
      abort();
    }
  }
}

string getStackTrace(void* context /*=0*/)
{
  ostringstream stacktrace;
#if defined(HAVE_EXC) || (defined(__GNUC__) && defined(__linux))
  static const int MAXSTACK = 100;
#endif

#ifdef HAVE_EXC
  // Use -lexc to print out a stack trace
  static const int MAXNAMELEN = 1000;
  __uint64_t addrs[MAXSTACK];
  char* cnames_str = new char[MAXSTACK*MAXNAMELEN];
  char* names[MAXSTACK];
  for(int i=0;i<MAXSTACK;i++)
    names[i]=cnames_str+i*MAXNAMELEN;
  int nframes = trace_back_stack(0, addrs, names, MAXSTACK, MAXNAMELEN);
  if(nframes == 0){
    stacktrace << "Backtrace not available!\n";
  } else {
    stacktrace << "Backtrace:\n";
    stacktrace.flags(ios::hex);
    // Skip the first procedure (us)
    for(int i=1;i<nframes;i++)
      stacktrace << "0x" << (void*)addrs[i] << ": " << names[i] << '\n';
  }
#elif defined(__GNUC__) && defined(__linux)
  static void *addresses[MAXSTACK];
  int n = backtrace( addresses, MAXSTACK );
  if (n < 2){
    stacktrace << "Backtrace not available!\n";
  } else {
    stacktrace << "Backtrace:\n";
    stacktrace.flags(ios::hex);
    char **names = backtrace_symbols( addresses, n );
    for ( int i = 2; i < n; i++ ) {
     Dl_info info;
     char *demangled = NULL;

     //Attempt to demangle this if possible
     //Get the nearest symbol to feed to demangler
     if(dladdr(addresses[i], &info) != 0) {
      int stat;
      // __cxa_demangle is a naughty obscure backend and no
      // self-respecting person would ever call it directly. ;-)
      // However it is a convenient glibc way to demangle syms.
      demangled = abi::__cxa_demangle(info.dli_sname,0,0,&stat);
     }
     if (demangled != NULL) {
      //Chop off the garbage from the raw symbol
      char *loc = strchr(names[i], '(');
      if (loc != NULL) *loc = '\0';

      stacktrace << i - 1 << ". " << names[i] << '\n';
      stacktrace << "  in " << demangled << '\n';
      free(demangled);
     } else { // Just output the raw symbol
      stacktrace << i - 1 << ". " << names[i] << '\n';
     }
    }
    free(names);
  }
#elif defined(_WIN32)
  StackWalker sw;
  stacktrace << sw.GetCallstack(context);
#endif
  return stacktrace.str();
}

} // End namespace Manta


text:
package org.pc.traking.model.jass;
import java.security.Principal;

public class RolePrincipal implements Principal {

    private String name;

    public RolePrincipal(String name) {
        super();
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }

}


text:
/*
  drbd_limits.h
  This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
*/

/*
 * Our current limitations.
 * Some of them are hard limits,
 * some of them are arbitrary range limits, that make it easier to provide
 * feedback about nonsense settings for certain configurable values.
 */

#ifndef DRBD_LIMITS_H
#define DRBD_LIMITS_H 1

#define DEBUG_RANGE_CHECK 0

#define DRBD_MINOR_COUNT_MIN 1
#define DRBD_MINOR_COUNT_MAX 255
#define DRBD_MINOR_COUNT_DEF 32
#define DRBD_MINOR_COUNT_SCALE '1'

#define DRBD_VOLUME_MAX 65535

#define DRBD_DIALOG_REFRESH_MIN 0
#define DRBD_DIALOG_REFRESH_MAX 600
#define DRBD_DIALOG_REFRESH_SCALE '1'

/* valid port number */
#define DRBD_PORT_MIN 1
#define DRBD_PORT_MAX 0xffff
#define DRBD_PORT_SCALE '1'

/* startup { */
  /* if you want more than 3.4 days, disable */
#define DRBD_WFC_TIMEOUT_MIN 0
#define DRBD_WFC_TIMEOUT_MAX 300000
#define DRBD_WFC_TIMEOUT_DEF 0
#define DRBD_WFC_TIMEOUT_SCALE '1'

#define DRBD_DEGR_WFC_TIMEOUT_MIN 0
#define DRBD_DEGR_WFC_TIMEOUT_MAX 300000
#define DRBD_DEGR_WFC_TIMEOUT_DEF 0
#define DRBD_DEGR_WFC_TIMEOUT_SCALE '1'

#define DRBD_OUTDATED_WFC_TIMEOUT_MIN 0
#define DRBD_OUTDATED_WFC_TIMEOUT_MAX 300000
#define DRBD_OUTDATED_WFC_TIMEOUT_DEF 0
#define DRBD_OUTDATED_WFC_TIMEOUT_SCALE '1'
/* }*/

/* net { */
  /* timeout, unit centi seconds
   * more than one minute timeout is not useful */
#define DRBD_TIMEOUT_MIN 1
#define DRBD_TIMEOUT_MAX 600
#define DRBD_TIMEOUT_DEF 60       /* 6 seconds */
#define DRBD_TIMEOUT_SCALE '1'

 /* If backing disk takes longer than disk_timeout, mark the disk as failed */
#define DRBD_DISK_TIMEOUT_MIN 0    /* 0 = disabled */
#define DRBD_DISK_TIMEOUT_MAX 6000 /* 10 Minutes */
#define DRBD_DISK_TIMEOUT_DEF 0    /* disabled */
#define DRBD_DISK_TIMEOUT_SCALE '1'

  /* active connection retries when C_WF_CONNECTION */
#define DRBD_CONNECT_INT_MIN 1
#define DRBD_CONNECT_INT_MAX 120
#define DRBD_CONNECT_INT_DEF 10   /* seconds */
#define DRBD_CONNECT_INT_SCALE '1'

  /* keep-alive probes when idle */
#define DRBD_PING_INT_MIN 1
#define DRBD_PING_INT_MAX 120
#define DRBD_PING_INT_DEF 10
#define DRBD_PING_INT_SCALE '1'

 /* timeout for the ping packets.*/
#define DRBD_PING_TIMEO_MIN  1
#define DRBD_PING_TIMEO_MAX  300
#define DRBD_PING_TIMEO_DEF  5
#define DRBD_PING_TIMEO_SCALE '1'

  /* max number of write requests between write barriers */
#define DRBD_MAX_EPOCH_SIZE_MIN 1
#define DRBD_MAX_EPOCH_SIZE_MAX 20000
#define DRBD_MAX_EPOCH_SIZE_DEF 2048
#define DRBD_MAX_EPOCH_SIZE_SCALE '1'

  /* I don't think that a tcp send buffer of more than 10M is useful */
#define DRBD_SNDBUF_SIZE_MIN  0
#define DRBD_SNDBUF_SIZE_MAX  (10<<20)
#define DRBD_SNDBUF_SIZE_DEF  0
#define DRBD_SNDBUF_SIZE_SCALE '1'

#define DRBD_RCVBUF_SIZE_MIN  0
#define DRBD_RCVBUF_SIZE_MAX  (10<<20)
#define DRBD_RCVBUF_SIZE_DEF  0
#define DRBD_RCVBUF_SIZE_SCALE '1'

  /* @4k PageSize -> 128kB - 512MB */
#define DRBD_MAX_BUFFERS_MIN  32
#define DRBD_MAX_BUFFERS_MAX  131072
#define DRBD_MAX_BUFFERS_DEF  2048
#define DRBD_MAX_BUFFERS_SCALE '1'

  /* @4k PageSize -> 4kB - 512MB */
#define DRBD_UNPLUG_WATERMARK_MIN  1
#define DRBD_UNPLUG_WATERMARK_MAX  131072
#define DRBD_UNPLUG_WATERMARK_DEF (DRBD_MAX_BUFFERS_DEF/16)
#define DRBD_UNPLUG_WATERMARK_SCALE '1'

  /* 0 is disabled.
   * 200 should be more than enough even for very short timeouts */
#define DRBD_KO_COUNT_MIN  0
#define DRBD_KO_COUNT_MAX  200
#define DRBD_KO_COUNT_DEF  7
#define DRBD_KO_COUNT_SCALE '1'
/* } */

/* syncer { */
  /* FIXME allow rate to be zero? */
#define DRBD_RESYNC_RATE_MIN 1
/* channel bonding 10 GbE, or other hardware */
#define DRBD_RESYNC_RATE_MAX (4 << 20)
#define DRBD_RESYNC_RATE_DEF 250
#define DRBD_RESYNC_RATE_SCALE 'k'  /* kilobytes */

  /* less than 7 would hit performance unnecessarily. */
#define DRBD_AL_EXTENTS_MIN  7
  /* we use u16 as "slot number", (u16)~0 is "FREE".
   * If you use >= 292 kB on-disk ring buffer,
   * this is the maximum you can use: */
#define DRBD_AL_EXTENTS_MAX  0xfffe
#define DRBD_AL_EXTENTS_DEF  1237
#define DRBD_AL_EXTENTS_SCALE '1'

#define DRBD_MINOR_NUMBER_MIN  -1
#define DRBD_MINOR_NUMBER_MAX  ((1 << 20) - 1)
#define DRBD_MINOR_NUMBER_DEF  -1
#define DRBD_MINOR_NUMBER_SCALE '1'

/* } */

/* drbdsetup XY resize -d Z
 * you are free to reduce the device size to nothing, if you want to.
 * the upper limit with 64bit kernel, enough ram and flexible meta data
 * is 1 PiB, currently. */
/* DRBD_MAX_SECTORS */
#define DRBD_DISK_SIZE_MIN  0
#define DRBD_DISK_SIZE_MAX  (1 * (2LLU << 40))
#define DRBD_DISK_SIZE_DEF  0 /* = disabled = no user size... */
#define DRBD_DISK_SIZE_SCALE 's'  /* sectors */

#define DRBD_ON_IO_ERROR_DEF EP_DETACH
#define DRBD_FENCING_DEF FP_DONT_CARE
#define DRBD_AFTER_SB_0P_DEF ASB_DISCONNECT
#define DRBD_AFTER_SB_1P_DEF ASB_DISCONNECT
#define DRBD_AFTER_SB_2P_DEF ASB_DISCONNECT
#define DRBD_RR_CONFLICT_DEF ASB_DISCONNECT
#define DRBD_ON_NO_DATA_DEF OND_IO_ERROR
#define DRBD_ON_CONGESTION_DEF OC_BLOCK
#define DRBD_READ_BALANCING_DEF RB_PREFER_LOCAL

#define DRBD_MAX_BIO_BVECS_MIN 0
#define DRBD_MAX_BIO_BVECS_MAX 128
#define DRBD_MAX_BIO_BVECS_DEF 0
#define DRBD_MAX_BIO_BVECS_SCALE '1'

#define DRBD_C_PLAN_AHEAD_MIN  0
#define DRBD_C_PLAN_AHEAD_MAX  300
#define DRBD_C_PLAN_AHEAD_DEF  20
#define DRBD_C_PLAN_AHEAD_SCALE '1'

#define DRBD_C_DELAY_TARGET_MIN 1
#define DRBD_C_DELAY_TARGET_MAX 100
#define DRBD_C_DELAY_TARGET_DEF 10
#define DRBD_C_DELAY_TARGET_SCALE '1'

#define DRBD_C_FILL_TARGET_MIN 0
#define DRBD_C_FILL_TARGET_MAX (1<<20) /* 500MByte in sec */
#define DRBD_C_FILL_TARGET_DEF 100 /* Try to place 50KiB in socket send buffer during resync */
#define DRBD_C_FILL_TARGET_SCALE 's'  /* sectors */

#define DRBD_C_MAX_RATE_MIN     250
#define DRBD_C_MAX_RATE_MAX     (4 << 20)
#define DRBD_C_MAX_RATE_DEF     102400
#define DRBD_C_MAX_RATE_SCALE	'k'  /* kilobytes */

#define DRBD_C_MIN_RATE_MIN     0
#define DRBD_C_MIN_RATE_MAX     (4 << 20)
#define DRBD_C_MIN_RATE_DEF     250
#define DRBD_C_MIN_RATE_SCALE	'k'  /* kilobytes */

#define DRBD_CONG_FILL_MIN	0
#define DRBD_CONG_FILL_MAX	(10<<21) /* 10GByte in sectors */
#define DRBD_CONG_FILL_DEF	0
#define DRBD_CONG_FILL_SCALE	's'  /* sectors */

#define DRBD_CONG_EXTENTS_MIN	DRBD_AL_EXTENTS_MIN
#define DRBD_CONG_EXTENTS_MAX	DRBD_AL_EXTENTS_MAX
#define DRBD_CONG_EXTENTS_DEF	DRBD_AL_EXTENTS_DEF
#define DRBD_CONG_EXTENTS_SCALE DRBD_AL_EXTENTS_SCALE

#define DRBD_PROTOCOL_DEF DRBD_PROT_C

#define DRBD_DISK_BARRIER_DEF	0
#define DRBD_DISK_FLUSHES_DEF	1
#define DRBD_DISK_DRAIN_DEF	1
#define DRBD_MD_FLUSHES_DEF	1
#define DRBD_TCP_CORK_DEF	1
#define DRBD_AL_UPDATES_DEF     1

#define DRBD_ALLOW_TWO_PRIMARIES_DEF	0
#define DRBD_ALWAYS_ASBP_DEF	0
#define DRBD_USE_RLE_DEF	1
#define DRBD_CSUMS_AFTER_CRASH_ONLY_DEF 0

#define DRBD_AL_STRIPES_MIN     1
#define DRBD_AL_STRIPES_MAX     1024
#define DRBD_AL_STRIPES_DEF     1
#define DRBD_AL_STRIPES_SCALE   '1'

#define DRBD_AL_STRIPE_SIZE_MIN   4
#define DRBD_AL_STRIPE_SIZE_MAX   16777216
#define DRBD_AL_STRIPE_SIZE_DEF   32
#define DRBD_AL_STRIPE_SIZE_SCALE 'k' /* kilobytes */

#define DRBD_SOCKET_CHECK_TIMEO_MIN 0
#define DRBD_SOCKET_CHECK_TIMEO_MAX DRBD_PING_TIMEO_MAX
#define DRBD_SOCKET_CHECK_TIMEO_DEF 0
#define DRBD_SOCKET_CHECK_TIMEO_SCALE '1'
#endif


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Threading.Tasks;

namespace Nether.Ingest.Parsers
{
    public interface IMessageParser<T>
    {
        Task<Message> ParseMessageAsync(T msg);
    }
}


text:
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using UnityEngine;
using System.Collections;

/// Class that can fade the pages of a PagedScrollRect based on the page's offset.
public class FadeScrollEffect : BaseScrollEffect {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
  [Range(0.0f, 1.0f)]
  [Tooltip("The alpha of the page when it is one page-length away.")]
  public float minAlpha = 0.0f;

  public override void ApplyEffect(BaseScrollEffect.UpdateData updateData) {
    CanvasGroup pageCanvasGroup = updateData.page.GetComponent<CanvasGroup>();

    /// All pages require a CanvasGroup for manipulating Alpha.
    if (pageCanvasGroup == null) {
      Debug.LogError("Cannot adjust alpha for page " + updateData.page.name + ", missing CanvasGroup");
      return;
    }

    // Calculate the difference
    float difference = updateData.scrollOffset - updateData.pageOffset;

    /// Calculate the alpha for this page.
    float alpha = 1.0f - (Mathf.Abs(difference) / updateData.spacing);
    alpha = (alpha * (1.0f - minAlpha)) + minAlpha;
    alpha = Mathf.Clamp(alpha, 0.0f, 1.0f);

    /// If this is the last page or the first page,
    /// Then we clamp the alpha to 1 when dragging past the edge
    /// Of the scrolling region.
    if (!updateData.looping) {
      if (updateData.pageIndex == 0 && difference < 0) {
        alpha = 1.0f;
      } else if (updateData.pageIndex == updateData.pageCount - 1 && difference > 0) {
        alpha = 1.0f;
      }
    }

    pageCanvasGroup.alpha = alpha;
  }
#endif  // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}


text:
package org.deviceconnect.android.manager.setting;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

import org.deviceconnect.android.manager.R;

/**
 * Device Connect Manager device plug-in list Activity.
 *
 * @author NTT DOCOMO, INC.
 */
public class DevicePluginListActivity extends Activity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.activity_devicepluginlist_title);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        if (savedInstanceState == null) {
            Fragment f = new DevicePluginListFragment();
            FragmentManager fm = getFragmentManager();
            FragmentTransaction t = fm.beginTransaction();
            t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            t.add(android.R.id.content, f, "container");
            t.commit();
        }
    }
}


text:
package com.epimorphics.registry.webapi;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.epimorphics.registry.core.Registry;
import com.epimorphics.registry.security.RegAuthorizationInfo;
import com.epimorphics.registry.security.RegPermission;
import com.epimorphics.registry.security.RegToken;
import com.epimorphics.registry.security.UserInfo;
import com.epimorphics.registry.security.UserStore;
import com.epimorphics.server.webapi.WebApiException;

@Path("/system/security")
public class Login {
    static final Logger log = LoggerFactory.getLogger( Login.class );

    public static final String DEFAULT_PROVIDER = "https://www.google.com/accounts/o8/id";
    public static final String PROVIDER_COOKIE = "ukgovld-login-provider";

    // Session attribute names
    public static final String SA_OPENID_DISC = "openid_disc";
    public static final String SA_OPENID_PROVIDER = "openid_provider";
    public static final String SA_REGISTRATION = "isRegistration";
    public static final String SA_RETURN_URL = "returnURL";

    // Attribute parameter names
    public static final String AP_EMAIL = "email";
    public static final String AP_FIRST_NAME = "firstName";
    public static final String AP_LAST_NAME = "lastName";
    public static final String AP_FULL_NAME = "fullname";

    // Velocity binding names
    public static final String VN_SUBJECT = "subject";
    public static final String VN_REGISTRATION_STATUS = "registrationStatus";
    public static final String RS_NEW = "new";
    public static final String RS_ALREADY_REGISTERED = "already";
    public static final String RS_LOGIN = "login";

    private static ConsumerManager manager = null;
    static {
        try {
            manager = new ConsumerManager();
        } catch (Exception e) {
            log.error("Failed to initialize openid subsystem", e);
        }
    }

    protected @Context UriInfo uriInfo;
    protected @Context ServletContext servletContext;
    protected @Context HttpServletRequest request;

    @Path("/login")
    @POST
    public Response login(@FormParam("provider") String provider, @FormParam("return") String returnURL, @Context HttpServletResponse response) {
        processOpenID(request, response, provider, returnURL, false);
        return Response.ok().build();
    }

    @Path("/register")
    @POST
    public Response register(@FormParam("provider") String provider, @FormParam("return") String returnURL,  @Context HttpServletResponse response) {
        processOpenID(request, response, provider, returnURL, true);
        return Response.ok().build();
    }

    @Path("/logout")
    @POST
    public void logout(@Context HttpServletResponse response) throws IOException {
        // TODO set session attribute as part of Shiro realm
        request.getSession().removeAttribute(VN_SUBJECT);
        SecurityUtils.getSubject().logout();
        response.sendRedirect("/");
    }

    @Path("/apilogin")
    @POST
    public Response apilogin(@FormParam("userid") String userid, @FormParam("password") String password) {
        try {
            RegToken token = new RegToken(userid, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            log.info("API Login for userid " + userid);
            return Response.ok().build();
        } catch (Exception e) {
            log.warn(String.format("API Login failure for userid %s [%s]: %s", userid, e.getClass().toString(), e.getMessage()));
        }
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    @Path("/response")
    @GET
    public Response openIDResponse(@Context HttpServletResponse response) {
        return verifyResponse(request, response);
    }

    // Return the name of the loggedin user on this session, for test purposes
    @Path("/username")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getUsername() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return ((UserInfo)subject.getPrincipal()).getName();
        } else {
            throw new WebApiException(Response.Status.UNAUTHORIZED, "No logged in user in this session");
        }
    }

    @Path("/listusers")
    @GET
    @Produces(MediaType.TEXT_HTML)
    public Response listusers(@QueryParam("query") String query, @QueryParam("grant") String action, @QueryParam("uri") String uri) {
        if (SecurityUtils.getSubject().isPermitted("Grant:"+uri)) {
            List<UserInfo> users = Registry.get().getUserStore().listUsers(query);
            return RequestProcessor.render("user-list.vm", uriInfo, servletContext, request, "grant", action, "uri", uri, "users", users);
        } else {
            return error("You do not have sufficient privileges to grant further access");
        }
    }

    @Path("/grant")
    @POST
    public Response grant(@FormParam("user") String id, @FormParam("grant") String action, @FormParam("path") String inpath) {
        String path = inpath;
        if (path == null || path.isEmpty()) {
            // Occurrs when setting global admin permissions
            path = "/ui/admin";
        }
        UserStore userstore = Registry.get().getUserStore();
        try {
            if (action.equals("administrator")) {
                userstore.setRole(id, RegAuthorizationInfo.ADMINSTRATOR_ROLE);
            } else {
                userstore.addPermision(id, new RegPermission(action, path));
            }
            return redirectTo(path);
        } catch (Exception e) {
            return error("Permission grant failed: " + e);
        }
    }

    @Path("/ungrant")
    @POST
    public Response ungrant(@FormParam("user") String id, @FormParam("path") String path) {
        UserStore userstore = Registry.get().getUserStore();
        try {
            userstore.removePermission(id, path);
            return redirectTo(path);
        } catch (Exception e) {
            return error("Permission grant failed: " + e);
        }
    }

    @Path("/createpassword")
    @POST
    public Response ungrant(@FormParam("minstolive") String minstolive) {
        int mins = 0;
        try {
            mins = Integer.parseInt(minstolive);
        } catch (Exception e) {
            return error("Minutes to live must be an integer");
        }
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            UserStore userstore = Registry.get().getUserStore();
            try {
                String id = ((UserInfo)subject.getPrincipal()).getOpenid();
                String pwd = userstore.createCredentials(id, mins);
                return RequestProcessor.render("api-key-result.vm", uriInfo, servletContext, request, "password", pwd, "id", id);
            } catch (Exception e) {
                return error("Permission grant failed: " + e);
            }
        } else {
            return error("You must be logged in to do this");
        }
    }

    @Path("/listadmins")
    @GET
    public Response listadmins() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() && subject.hasRole(RegAuthorizationInfo.ADMINSTRATOR_ROLE)) {
            UserStore userstore = Registry.get().getUserStore();
            return RequestProcessor.render("admin-list.vm", uriInfo, servletContext, request, "admins", userstore.listAdminUsers());
        } else {
            return error("You must be logged in as an administrator to do this");
        }
    }

    @Path("/setrole")
    @POST
    public Response setrole(@FormParam("id") String id, @FormParam("role") String role) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() && subject.hasRole(RegAuthorizationInfo.ADMINSTRATOR_ROLE)) {
            UserStore userstore = Registry.get().getUserStore();
            try {
                userstore.setRole(id, role.isEmpty() ? null : role);
                return redirectTo("/ui/admin");
            } catch (Exception e) {
                return error("Role assignment failed: " + e);
            }
        } else {
            return error("You must be logged in as an administrator to do this");
        }
    }

    private Response error(String message) {
        return RequestProcessor.render("error.vm", uriInfo, servletContext, request, "message", message);
    }

    private Response redirectTo(String path) {
        URI uri;
        try {
            uri = new URI(path);
            return Response.seeOther(uri).build();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    @SuppressWarnings("rawtypes")
    protected void processOpenID(HttpServletRequest request, HttpServletResponse response, String provider, String returnURL, boolean isRegister) {
        HttpSession session = request.getSession();
        session.setAttribute(SA_REGISTRATION, isRegister);
        session.setAttribute(SA_OPENID_PROVIDER, provider);
        if (returnURL == null || returnURL.isEmpty()) {
            returnURL = "/ui/admin";
        }
        session.setAttribute(SA_RETURN_URL, returnURL);

        if (provider == null || provider.isEmpty()) {
            provider = DEFAULT_PROVIDER;
        }
        log.info("Authentication request for " + provider + (isRegister ? " (registration)" : ""));

        String responseURL = uriInfo.getBaseUri().toString() + "system/security/response";
        try
        {
            // perform discovery on the user-supplied identifier
            List discoveries = manager.discover(provider);

            // attempt to associate with the OpenID provider
            // and retrieve one service endpoint for authentication
            DiscoveryInformation discovered = manager.associate(discoveries);

            // store the discovery information in the user's session
            request.getSession().setAttribute(SA_OPENID_DISC, discovered);

            // obtain a AuthRequest message to be sent to the OpenID provider
            AuthRequest authReq = manager.authenticate(discovered, responseURL);

            if (isRegister) {
                // Attribute Exchange example: fetching the 'email' attribute
                FetchRequest fetch = FetchRequest.createFetchRequest();
                if (provider.contains("google.com")) {
//                    fetch.addAttribute(AP_EMAIL, "http://axschema.org/contact/email", false);
                    fetch.addAttribute(AP_FIRST_NAME, "http://axschema.org/namePerson/first", true);
                    fetch.addAttribute(AP_LAST_NAME, "http://axschema.org/namePerson/last", true);
                } else if (provider.contains("yahoo.com")) {
//                    fetch.addAttribute(AP_EMAIL, "http://axschema.org/contact/email", false);
                    fetch.addAttribute(AP_FULL_NAME, "http://axschema.org/namePerson", true);
                } else { //works for myOpenID
//                    fetch.addAttribute(AP_EMAIL, "http://schema.openid.net/contact/email", false);
                    fetch.addAttribute(AP_FULL_NAME, "http://schema.openid.net/namePerson", true);
                }

                // attach the extension to the authentication request
                authReq.addExtension(fetch);
            }

            // For version2 endpoints can do a form-redirect but this is easier,
            // Relies on payload being less ~ 2k, currently ~ 800 bytes
            response.sendRedirect(authReq.getDestinationUrl(true));
        }
        catch (Exception e)
        {
            throw new WebApplicationException(e);
        }
    }

    @SuppressWarnings({ "unchecked" })
    public Response verifyResponse(HttpServletRequest request, HttpServletResponse httpresponse) {
        try {
            HttpSession session = request.getSession();

            // extract the parameters from the authentication response
            // (which comes in as a HTTP request from the OpenID provider)
            ParameterList response =
                    new ParameterList(request.getParameterMap());

            // retrieve the previously stored discovery information
            DiscoveryInformation discovered = (DiscoveryInformation)
                    session.getAttribute("openid-disc");

            // extract the receiving URL from the HTTP request
            StringBuffer receivingURL = request.getRequestURL();
            String queryString = request.getQueryString();
            if (queryString != null && queryString.length() > 0)
                receivingURL.append("?").append(request.getQueryString());

            // verify the response; ConsumerManager needs to be the same
            // (static) instance used to place the authentication request
            VerificationResult verification = manager.verify(
                    receivingURL.toString(),
                    response, discovered);

            // examine the verification result and extract the verified identifier
            Identifier verified = verification.getVerifiedId();
            if (verified != null) {
                AuthSuccess authSuccess =  (AuthSuccess) verification.getAuthResponse();
                String name = null;
                if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
                    FetchResponse fetchResp = (FetchResponse) authSuccess
                            .getExtension(AxMessage.OPENID_NS_AX);
                    Map<String, List<String>> attributes = fetchResp.getAttributes();
                    if (attributes.containsKey(AP_FULL_NAME)) {
                        name = attributes.get(AP_FULL_NAME).get(0);
                    } else {
                        name = attributes.get(AP_FIRST_NAME).get(0) + " " + attributes.get(AP_LAST_NAME).get(0);
                    }
                }
                log.info(String.format("Verified identity %s = %s", verified.getIdentifier(), name));
                UserStore userstore = Registry.get().getUserStore();
                boolean isRegistration = ((Boolean)session.getAttribute(SA_REGISTRATION)).booleanValue();
                String registrationStatus = RS_LOGIN;
                if (isRegistration) {
                    UserInfo userinfo = new UserInfo(verified.getIdentifier(), name);
                    if (userstore.register( userinfo )) {
                        registrationStatus = RS_NEW;
                    } else {
                        registrationStatus = RS_ALREADY_REGISTERED;
                    }
                }

                RegToken token = new RegToken(verified.getIdentifier(), true);
                Subject subject = SecurityUtils.getSubject();
                try {
                    subject.login(token);
                    session.setAttribute(VN_REGISTRATION_STATUS, registrationStatus);
                    String provider = (String)session.getAttribute(SA_OPENID_PROVIDER);
                    if (provider != null && !provider.isEmpty()) {
                        Cookie cookie = new Cookie(PROVIDER_COOKIE, provider);
                        cookie.setComment("Records the openid provider you last used to log in to a UKGovLD registry");
                        cookie.setMaxAge(60 * 60 * 24 * 30);
                        cookie.setHttpOnly(true);
                        cookie.setPath("/");
                        httpresponse.addCookie(cookie);
                    }
                    return redirectTo( session.getAttribute(SA_RETURN_URL).toString() );
//                    return RequestProcessor.render("admin.vm", uriInfo, servletContext, request, VN_SUBJECT, subject, VN_REGISTRATION_STATUS, registrationStatus);
                } catch (Exception e) {
                    log.error("Authentication failure: " + e);
                    return RequestProcessor.render("error.vm", uriInfo, servletContext, request, "message", "Could not find a registration for you.");
                }
            }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        }
        return RequestProcessor.render("error.vm", uriInfo, servletContext, request, "message", "OpenID login failed");
    }
}


text:
package org.apache.lucene.index;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;

@SuppressCodecs("Lucene3x")
public class TestDocValuesWithThreads extends LuceneTestCase {

  public void test() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random()))
                                           .setMergePolicy(newLogMergePolicy()));

    final List<Long> numbers = new ArrayList<>();
    final List<BytesRef> binary = new ArrayList<>();
    final List<BytesRef> sorted = new ArrayList<>();
    final int numDocs = atLeast(100);
    for(int i=0;i<numDocs;i++) {
      Document d = new Document();
      long number = random().nextLong();
      d.add(new NumericDocValuesField("number", number));
      BytesRef bytes = new BytesRef(TestUtil.randomRealisticUnicodeString(random()));
      d.add(new BinaryDocValuesField("bytes", bytes));
      binary.add(bytes);
      bytes = new BytesRef(TestUtil.randomRealisticUnicodeString(random()));
      d.add(new SortedDocValuesField("sorted", bytes));
      sorted.add(bytes);
      w.addDocument(d);
      numbers.add(number);
    }

    w.forceMerge(1);
    final IndexReader r = w.getReader();
    w.close();

    assertEquals(1, r.leaves().size());
    final AtomicReader ar = r.leaves().get(0).reader();

    int numThreads = TestUtil.nextInt(random(), 2, 5);
    List<Thread> threads = new ArrayList<>();
    final CountDownLatch startingGun = new CountDownLatch(1);
    for(int t=0;t<numThreads;t++) {
      final Random threadRandom = new Random(random().nextLong());
      Thread thread = new Thread() {
          @Override
          public void run() {
            try {
              //NumericDocValues ndv = ar.getNumericDocValues("number");
              FieldCache.Longs ndv = FieldCache.DEFAULT.getLongs(ar, "number", false);
              //BinaryDocValues bdv = ar.getBinaryDocValues("bytes");
              BinaryDocValues bdv = FieldCache.DEFAULT.getTerms(ar, "bytes", false);
              SortedDocValues sdv = FieldCache.DEFAULT.getTermsIndex(ar, "sorted");
              startingGun.await();
              int iters = atLeast(1000);
              for(int iter=0;iter<iters;iter++) {
                int docID = threadRandom.nextInt(numDocs);
                switch(threadRandom.nextInt(6)) {
                case 0:
                  assertEquals((byte) numbers.get(docID).longValue(), FieldCache.DEFAULT.getBytes(ar, "number", false).get(docID));
                  break;
                case 1:
                  assertEquals((short) numbers.get(docID).longValue(), FieldCache.DEFAULT.getShorts(ar, "number", false).get(docID));
                  break;
                case 2:
                  assertEquals((int) numbers.get(docID).longValue(), FieldCache.DEFAULT.getInts(ar, "number", false).get(docID));
                  break;
                case 3:
                  assertEquals(numbers.get(docID).longValue(), FieldCache.DEFAULT.getLongs(ar, "number", false).get(docID));
                  break;
                case 4:
                  assertEquals(Float.intBitsToFloat((int) numbers.get(docID).longValue()), FieldCache.DEFAULT.getFloats(ar, "number", false).get(docID), 0.0f);
                  break;
                case 5:
                  assertEquals(Double.longBitsToDouble(numbers.get(docID).longValue()), FieldCache.DEFAULT.getDoubles(ar, "number", false).get(docID), 0.0);
                  break;
                }
                BytesRef scratch = bdv.get(docID);
                assertEquals(binary.get(docID), scratch);
                // Cannot share a single scratch against two "sources":
                BytesRef scratch2 = sdv.get(docID);
                assertEquals(sorted.get(docID), scratch2);
              }
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }
        };
      thread.start();
      threads.add(thread);
    }

    startingGun.countDown();

    for(Thread thread : threads) {
      thread.join();
    }

    r.close();
    dir.close();
  }

  public void test2() throws Exception {
    Random random = random();
    final int NUM_DOCS = atLeast(100);
    final Directory dir = newDirectory();
    final RandomIndexWriter writer = new RandomIndexWriter(random, dir);
    final boolean allowDups = random.nextBoolean();
    final Set<String> seen = new HashSet<>();
    if (VERBOSE) {
      System.out.println("TEST: NUM_DOCS=" + NUM_DOCS + " allowDups=" + allowDups);
    }
    int numDocs = 0;
    final List<BytesRef> docValues = new ArrayList<>();

    // TODO: deletions
    while (numDocs < NUM_DOCS) {
      final String s;
      if (random.nextBoolean()) {
        s = TestUtil.randomSimpleString(random);
      } else {
        s = TestUtil.randomUnicodeString(random);
      }
      final BytesRef br = new BytesRef(s);

      if (!allowDups) {
        if (seen.contains(s)) {
          continue;
        }
        seen.add(s);
      }

      if (VERBOSE) {
        System.out.println("  " + numDocs + ": s=" + s);
      }

      final Document doc = new Document();
      doc.add(new SortedDocValuesField("stringdv", br));
      doc.add(new NumericDocValuesField("id", numDocs));
      docValues.add(br);
      writer.addDocument(doc);
      numDocs++;

      if (random.nextInt(40) == 17) {
        // force flush
        writer.getReader().close();
      }
    }

    writer.forceMerge(1);
    final DirectoryReader r = writer.getReader();
    writer.close();

    final AtomicReader sr = getOnlySegmentReader(r);

    final long END_TIME = System.currentTimeMillis() + (TEST_NIGHTLY ? 30 : 1);

    final int NUM_THREADS = TestUtil.nextInt(random(), 1, 10);
    Thread[] threads = new Thread[NUM_THREADS];
    for(int thread=0;thread<NUM_THREADS;thread++) {
      threads[thread] = new Thread() {
          @Override
          public void run() {
            Random random = random();
            final SortedDocValues stringDVDirect;
            final NumericDocValues docIDToID;
            try {
              stringDVDirect = sr.getSortedDocValues("stringdv");
              docIDToID = sr.getNumericDocValues("id");
              assertNotNull(stringDVDirect);
            } catch (IOException ioe) {
              throw new RuntimeException(ioe);
            }
            while(System.currentTimeMillis() < END_TIME) {
              final SortedDocValues source;
              source = stringDVDirect;

              for(int iter=0;iter<100;iter++) {
                final int docID = random.nextInt(sr.maxDoc());
                BytesRef scratch = source.get(docID);
                assertEquals(docValues.get((int) docIDToID.get(docID)), scratch);
              }
            }
          }
        };
      threads[thread].start();
    }

    for(Thread thread : threads) {
      thread.join();
    }

    r.close();
    dir.close();
  }

}


text:
package co.edu.sena.adsi.rest.auth;

import co.edu.sena.adsi.jpa.entities.Usuario;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.ReadOnlyJWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.text.ParseException;
import java.util.Arrays;
import org.joda.time.DateTime;

/**
 *
 * @author ruber19
 */
public final class AuthUtils {

    private static final JWSHeader JWT_HEADER = new JWSHeader(JWSAlgorithm.HS256);
    private static final String TOKEN_SECRET = "adsilomejor**";
    public static final String AUTH_HEADER_KEY = "Authorization";

    public static String getSubject(String authHeader) throws ParseException, JOSEException {
        return decodeToken(authHeader).getSubject();
    }

    public static ReadOnlyJWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException {
        SignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader));
        if (signedJWT.verify(new MACVerifier(TOKEN_SECRET))) {
            return signedJWT.getJWTClaimsSet();
        } else {
            throw new JOSEException("Signature verification failed");
        }
    }

    public static Token createToken(String host, Usuario user) throws JOSEException {
        JWTClaimsSet claim = new JWTClaimsSet();
        claim.setSubject(Integer.toString(user.getId()));
        claim.setIssuer(host);
        claim.setIssueTime(DateTime.now().toDate());
        claim.setExpirationTime(DateTime.now().plusDays(1).toDate());
        claim.setCustomClaim("user", user.getNombres() + " " + user.getApellidos());
        claim.setCustomClaim("roles", Arrays.toString(user.getRolesList().toArray()));
        System.out.println("ROLES"+Arrays.toString(user.getRolesList().toArray()));
        JWSSigner signer = new MACSigner(TOKEN_SECRET);
        SignedJWT jwt = new SignedJWT(JWT_HEADER, claim);
        jwt.sign(signer);

        return new Token(jwt.serialize());
    }

    public static String getSerializedToken(String authHeader) {
        return authHeader.split(" ")[1];
    }
}