text:
<?php

require_once "Bookmark.class.php";

/**
 * Represents a folder with bookmarks and subfolders.
 *
 * @package    bmparser
 * @author     Pablo D. Sánchez <pdsanchez.contacto@gmail.com>
 */
class Folder {
	/**
	 * @var String The name of the folder
	 */
	private $name;
	/**
	 * @var String The description of the folder
	 */
	private $description;
	/**
	 * @var array List of Bookmarks objects for this folder
	 */
	private $bookmarkList;
	/**
	 * @var array List of Folder objects (subfolders)
	 */
	private $folderList;

	/**
	 * Constructor
	 *
	 * @param String $name The name of the folder
	 */
	function __construct($name) {
		$this->name = $name;
		$this->folderList = array();
		$this->bookmarkList = array();
	}

  /**
	 * Add a new bookmark
	 *
	 * @param Bookmark $bookmark The Bookmark object
	 */
	public function addBookmark(Bookmark $bookmark) {
		if ($bookmark instanceof Bookmark) {
			array_push($this->bookmarkList, $bookmark);
		}
		else {
			trigger_error("Bookmark object expected");
		}
	}

	/**
	 * Create and add a new bookmark
	 *
	 * @param string $name             The name of the bookmark
	 * @param string $url              The url of the bookmark
	 * @param string $description|null The description of the bookmark
	 * @param string $icon|null        The icon of the bookmark
	 *
	 * @return Bookmark    The Bookmark object created
	 */
	public function createBookmark($name, $url, $description=null, $icon=null) {
		$bookmark = new Bookmark($name, $url, $description, $icon);
		array_push($this->bookmarkList, $bookmark);
		return $bookmark;
	}

	/**
	 * Gets the bookmark list.
	 *
	 * @return array    An array of Bookmark objects
	 */
	public function getBookmarks() {
		return $this->bookmarkList;
	}

	/**
	 * Add a new folder (subfolder)
	 *
	 * @param Folder|string $folder The folder object or the name of the folder.
	 *
	 * @return Folder    The Folder object added
	 */
	public function addFolder($folder) {
		if (! $folder instanceof Folder) {
			$folder = new Folder($folder);
		}
		array_push($this->folderList, $folder);
		return $folder;
	}

	/**
	 * Gets the subfolder list.
	 *
	 * @return array    An array of Folder objects
	 */
	public function getFolders() {
		return $this->folderList;
	}

	/**
	 * Gets the name of the folder.
	 *
	 * @return string    The name of the folder
	 */
	public function getName() {
		return $this->name;
	}

	/**
	 * Gets the description of the folder.
	 *
	 * @return string    The description of the folder
	 */
	public function getDescription() {
		return $this->description;
	}

	/**
	 * Sets the description of the folder.
	 *
	 * @param string $description The description of the folder
	 */
	public function setDescription($description) {
		$this->description = $description;
	}
}

?>


text:
"use strict";

var url = require('url');
var Readable = require('barrage').Readable;
var Promise = require('promise');
var throat = require('throat');
var download = require('./lib/download.js');

exports.log = require('./lib/log.js');
exports.checkStatusCodes = require('./lib/status-codes.js');
exports.addFavicon = require('./lib/favicon.js');
exports.minifyJS = require('./lib/minify-js.js');
exports.minifyCSS = require('./lib/minify-css.js');
exports.addManifest = require('./lib/manifest.js');

exports.writeFileSystem = require('./lib/write-file-system.js');

exports.getWebsiteStream = getWebsiteStream;

/**
 * Gets a stream of web pages from a starting point
 * where each object in the stream looks like:
 *
 * {
 *   url: 'http://example.com/foo',
 *   statusCode: 200,
 *   headers: {},
 *   body: <Buffer...>,
 *   dependencies: []
 * }
 */
function getWebsiteStream(start, options) {
  var highWaterMark = 2;
  if (options && options.highWaterMark) {
    highWaterMark = options.highWaterMark;
  } else if (options && options.parallel) {
    highWaterMark = options.parallel + 1;
  }
  var stream = new Readable({
    objectMode: true,
    highWaterMark: highWaterMark
  });

  var downloaded = {};
  function handleUri(uri, push) {
    uri = uri.split('#')[0];
    if (downloaded[uri] === true || !isHttp(uri) || !filter(options, uri)) {
      return Promise.resolve(null);
    }
    downloaded[uri] = true;
    return download(uri).then(function (result) {
      result.dependencies.forEach(function (dependency) {
        push(url.resolve(uri, dependency));
      });
      return result;
    });
  }

  var queue = Array.isArray(start) ? start : [start];
  var finished = false;
  var inProgress = 0;
  function process(session) {
    if (inProgress === 0 && !finished && queue.length === 0) {
      finished = true;
      stream.push(null);
    }
    if (queue.length === 0) {
      return;
    }
    inProgress++;
    return handleUri(queue.shift(), queue.push.bind(queue)).done(function (result) {
      inProgress--;
      if (finished) return;
      if (result !== null) {
        if (stream.push(result) && session.live) {
          process(session);
        } else {
          session.live = false;
        }
      } else if (session.live) {
        process(session);
      }
    }, function (err) {
      inProgress--;
      if (finished) return;
      finished = true;
      stream.emit('error', err);
      stream.push(null);
    });
  }

  var session = {live: false};
  stream._read = function () {
    if (session.live) return;
    session = {live: true};
    if (options && options.parallel) {
      for (var i = 0; i < options.parallel; i++) {
        process(session);
      }
    } else {
      process(session);
    }
  };

  return stream;
}

function isHttp(uri) {
  return ['http:', 'https:'].indexOf(url.parse(uri).protocol) !== -1;
}
function filter(options, uri) {
  return !(options && options.filter && !options.filter(uri));
}

redpajama_set_name: RedPajamaGithub


text:
#include "parser.h"
#include "ipcalc.h"
#include "defs.h"
#include "process_package.h"
#include "olsr_clock.h"
#include "duplicate_set.h"
#include "mid_set.h"
#include "olsr.h"
#include "os_net.h"
#include "olsr_logging.h"
#include "net_olsr.h"

#include <assert.h>
#include <errno.h>
#include <stdlib.h>

#ifdef WIN32
#undef EWOULDBLOCK
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif

static void parse_packet(uint8_t *binary, int size, struct interface *in_if, union olsr_ip_addr *from_addr);

static struct parse_function_entry *parse_functions = NULL;
static struct preprocessor_function_entry *preprocessor_functions = NULL;
static struct packetparser_function_entry *packetparser_functions = NULL;

static int olsr_forward_message(struct olsr_message *msg,
    uint8_t *binary, struct interface *in_if, union olsr_ip_addr *from_addr);

/**
 *Initialize the parser.
 *
 *@return nada
 */
void
olsr_init_parser(void)
{
  OLSR_INFO(LOG_PACKET_PARSING, "Initializing parser...\n");

  /* Initialize the packet functions */
  olsr_init_package_process();
}

void
olsr_deinit_parser(void)
{
  OLSR_INFO(LOG_PACKET_PARSING, "Deinitializing parser...\n");
  olsr_deinit_package_process();
}

void
olsr_parser_add_function(parse_function * function, uint32_t type)
{
  struct parse_function_entry *new_entry;

  new_entry = olsr_malloc(sizeof(*new_entry), "Register parse function");

  new_entry->function = function;
  new_entry->type = type;

  /* Queue */
  new_entry->next = parse_functions;
  parse_functions = new_entry;

  OLSR_INFO(LOG_PACKET_PARSING, "Register parse function: Added function for type %u\n", type);
}

int
olsr_parser_remove_function(parse_function * function)
{
  struct parse_function_entry *entry, *prev;

  for (entry = parse_functions, prev = NULL; entry != NULL; prev = entry, entry = entry->next) {
    if ((entry->function == function)) {
      if (entry == parse_functions) {
        parse_functions = entry->next;
      } else {
        prev->next = entry->next;
      }
      free(entry);
      return 1;
    }
  }
  return 0;
}

void
olsr_preprocessor_add_function(preprocessor_function * function)
{
  struct preprocessor_function_entry *new_entry;

  new_entry = olsr_malloc(sizeof(*new_entry), "Register preprocessor function");
  new_entry->function = function;

  /* Queue */
  new_entry->next = preprocessor_functions;
  preprocessor_functions = new_entry;

  OLSR_INFO(LOG_PACKET_PARSING, "Registered preprocessor function\n");
}

int
olsr_preprocessor_remove_function(preprocessor_function * function)
{
  struct preprocessor_function_entry *entry, *prev;

  for (entry = preprocessor_functions, prev = NULL; entry != NULL; prev = entry, entry = entry->next) {
    if (entry->function == function) {
      if (entry == preprocessor_functions) {
        preprocessor_functions = entry->next;
      } else {
        prev->next = entry->next;
      }
      free(entry);
      return 1;
    }
  }
  return 0;
}

void
olsr_packetparser_add_function(packetparser_function * function)
{
  struct packetparser_function_entry *new_entry;

  new_entry = olsr_malloc(sizeof(struct packetparser_function_entry), "Register packetparser function");

  new_entry->function = function;

  /* Queue */
  new_entry->next = packetparser_functions;
  packetparser_functions = new_entry;

  OLSR_INFO(LOG_PACKET_PARSING, "Registered packetparser  function\n");
}

int
olsr_packetparser_remove_function(packetparser_function * function)
{
  struct packetparser_function_entry *entry, *prev;

  for (entry = packetparser_functions, prev = NULL; entry != NULL; prev = entry, entry = entry->next) {
    if (entry->function == function) {
      if (entry == packetparser_functions) {
        packetparser_functions = entry->next;
      } else {
        prev->next = entry->next;
      }
      free(entry);
      return 1;
    }
  }
  return 0;
}

static void
olsr_parse_msg_hdr(const uint8_t **curr, struct olsr_message *msg)
{
  assert(curr);
  assert(msg);

  msg->header = *curr;

  pkt_get_u8(curr, &msg->type);
  pkt_get_reltime(curr, &msg->vtime);
  pkt_get_u16(curr, &msg->size);
  pkt_get_ipaddress(curr, &msg->originator);
  pkt_get_u8(curr, &msg->ttl);
  pkt_get_u8(curr, &msg->hopcnt);
  pkt_get_u16(curr, &msg->seqno);

  msg->payload = *curr;
  msg->end = msg->header + msg->size;
}

/**
 *Process a newly received OLSR packet. Checks the type
 *and to the neccessary convertions and call the
 *corresponding functions to handle the information.
 *@param from the sockaddr struct describing the sender
 *@param olsr the olsr struct containing the message
 *@param size the size of the message
 *@return nada
 */
static void
parse_packet(uint8_t *binary, int size, struct interface *in_if, union olsr_ip_addr *from_addr)
{
  struct olsr_packet pkt;
  struct olsr_message msg;
  struct parse_function_entry *entry;
  struct packetparser_function_entry *packetparser;
  enum duplicate_status dup_status = 0;
  uint8_t *curr, *end;
  const uint8_t *packet;

#if !defined(REMOVE_LOG_INFO) || !defined(REMOVE_LOG_WARN)
  struct ipaddr_str buf;
#endif

  curr = binary;
  packet = binary;
  end = binary + size;

  /* packet smaller than minimal olsr packet ? */
  if (size < 4) {
    OLSR_WARN(LOG_PACKET_PARSING, "Received too small packet (%u bytes) from %s\n",
        size, olsr_ip_to_string(&buf, from_addr));
    return;
  }

  pkt_get_u16(&packet, &pkt.size);
  pkt_get_u16(&packet, &pkt.seqno);

  if (pkt.size != (size_t) size) {
    OLSR_WARN(LOG_PACKET_PARSING, "Received packet from %s (%u bytes) has bad size field: %u bytes\n",
              olsr_ip_to_string(&buf, from_addr), size, pkt.size);
    return;
  }

  // call packetparser
  for (packetparser = packetparser_functions; packetparser != NULL; packetparser = packetparser->next) {
    packetparser->function(&pkt, binary, in_if, from_addr);
  }

  /* advance pointer to messages */
  curr += 4;

  for (;curr <= end - MIN_MESSAGE_SIZE(); curr += msg.size) {
    const uint8_t *msg_payload = curr;
    olsr_parse_msg_hdr(&msg_payload, &msg);

    /* Check size of message */
    if (curr + msg.size > end) {
      OLSR_WARN(LOG_PACKET_PARSING, "Packet received from %s is too short (%u bytes) for message %u (%u bytes)!",
          olsr_ip_to_string(&buf, from_addr), size, msg.type, msg.size);
      break;
    }
    else if (msg.size == 0) {
      OLSR_WARN(LOG_PACKET_PARSING, "Received a zero lengthed message from %s (typde %d), ignoring all further content of the packet!",
          olsr_ip_to_string(&buf, from_addr), msg.type);
      return;
    }

    /*RFC 3626 section 3.4:
     *  2    If the time to live of the message is less than or equal to
     *  '0' (zero), or if the message was sent by the receiving node
     *  (i.e., the Originator Address of the message is the main
     *  address of the receiving node): the message MUST silently be
     *  dropped.
     */

    /* Should be the same for IPv4 and IPv6 */
    if (olsr_ipcmp(&msg.originator, &olsr_cnf->router_id) == 0
        || !olsr_validate_address(&msg.originator)) {
      OLSR_INFO(LOG_PACKET_PARSING, "Skip processing our own message coming from %s!\n",
                olsr_ip_to_string(&buf, from_addr));
      continue;
    }

    if (msg.ttl == 0 || (int)msg.ttl + (int)msg.hopcnt > 255) {
#if !defined(REMOVE_LOG_WARN)
      struct ipaddr_str buf2;
#endif
      OLSR_WARN(LOG_PACKET_PARSING, "Malformed incoming message type %u from %s with originator %s: ttl=%u and hopcount=%u\n",
          msg.type, olsr_ip_to_string(&buf, from_addr), olsr_ip_to_string(&buf2, &msg.originator), msg.ttl, msg.hopcnt);
      continue;
    }
    if (olsr_is_duplicate_message(&msg, false, &dup_status)) {
      OLSR_INFO(LOG_PACKET_PARSING, "Not processing message duplicate from %s (seqnr %u)!\n",
          olsr_ip_to_string(&buf, &msg.originator), msg.seqno);
    }
    else {
      OLSR_DEBUG(LOG_PACKET_PARSING, "Processing message type %u (seqno %u) from %s\n",
          msg.type, msg.seqno, olsr_ip_to_string(&buf, &msg.originator));
      for (entry = parse_functions; entry != NULL; entry = entry->next) {
        /* Should be the same for IPv4 and IPv6 */
        /* Promiscuous or exact match */
        if ((entry->type == PROMISCUOUS) || (entry->type == msg.type)) {
          entry->function(&msg, in_if, from_addr, dup_status);
        }
      }
    }
    olsr_forward_message(&msg, curr, in_if, from_addr);
  }                             /* for olsr_msg */
}

/**
 *Processing OLSR data from socket. Reading data, setting
 *wich interface recieved the message, Sends IPC(if used)
 *and passes the packet on to parse_packet().
 *
 *@param fd the filedescriptor that data should be read from.
 *@return nada
 */
void
olsr_input(int fd, void *data __attribute__ ((unused)), unsigned int flags __attribute__ ((unused)))
{
  unsigned int cpu_overload_exit = 0;
#ifndef REMOVE_LOG_DEBUG
  char addrbuf[128];
#endif
#if !defined(REMOVE_LOG_INFO) || !defined(REMOVE_LOG_WARN)
  struct ipaddr_str buf;
#endif

  for (;;) {
    struct interface *olsr_in_if;
    union olsr_ip_addr from_addr;
    struct preprocessor_function_entry *entry;
    uint8_t *packet;
    /* sockaddr_in6 is bigger than sockaddr !!!! */
    union olsr_sockaddr from;
    socklen_t fromlen;
    int size;
    uint8_t inbuf[MAXMESSAGESIZE] __attribute__ ((aligned));

    if (32 < ++cpu_overload_exit) {
      OLSR_WARN(LOG_PACKET_PARSING, "CPU overload detected, ending olsr_input() loop\n");
      break;
    }

    fromlen = sizeof(from);
    size = os_recvfrom(fd, inbuf, sizeof(inbuf), 0, &from, &fromlen);

    if (size <= 0) {
      if (size < 0 && errno != EWOULDBLOCK) {
        OLSR_WARN(LOG_PACKET_PARSING, "error recvfrom: %s", strerror(errno));
      }
      break;
    }

    OLSR_DEBUG(LOG_PACKET_PARSING, "Recieved a packet from %s (fd=%d)\n",
               sockaddr_to_string(addrbuf, sizeof(addrbuf), (struct sockaddr *)&from, fromlen),
               fd);

    if (olsr_cnf->ip_version == AF_INET) {
      /* IPv4 sender address */
      if (fromlen != sizeof(struct sockaddr_in)) {
        OLSR_WARN(LOG_PACKET_PARSING, "Got wrong ip size from recv()\n");
        break;
      }
      from_addr.v4 = ((struct sockaddr_in *)&from)->sin_addr;
    } else {
      /* IPv6 sender address */
      if (fromlen != sizeof(struct sockaddr_in6)) {
        OLSR_WARN(LOG_PACKET_PARSING, "Got wrong ip size from recv()\n");
        break;
      }
      from_addr.v6 = ((struct sockaddr_in6 *)&from)->sin6_addr;
    }

    /* are we talking to ourselves? */
    if (if_ifwithaddr(&from_addr) != NULL) {
      OLSR_INFO(LOG_PACKET_PARSING, "Ignore packet from ourself (%s).\n",
          olsr_ip_to_string(&buf, &from_addr));
      return;
    }
    olsr_in_if = if_ifwithsock(fd);
    if (olsr_in_if == NULL) {
      OLSR_WARN(LOG_PACKET_PARSING, "Could not find input interface for message from %s size %d\n",
                olsr_ip_to_string(&buf, &from_addr), size);
      return;
    }
    // call preprocessors
    packet = &inbuf[0];
    for (entry = preprocessor_functions; entry != NULL; entry = entry->next) {
      packet = entry->function(packet, olsr_in_if, &from_addr, &size);
      // discard package ?
      if (packet == NULL) {
        OLSR_INFO(LOG_PACKET_PARSING, "Discard package because of preprocessor\n");
        return;
      }
    }

    /*
     * &from - sender
     * &inbuf.olsr
     * size - bytes read
     */
    parse_packet(packet, size, olsr_in_if, &from_addr);
  }
}

/**
 *Check if a message is to be forwarded and forward
 *it if necessary.
 *
 *@param m the OLSR message recieved
 *
 *@returns positive if forwarded
 */
static int
olsr_forward_message(struct olsr_message *msg, uint8_t *binary, struct interface *in_if, union olsr_ip_addr *from_addr)
{
  union olsr_ip_addr *src;
  struct nbr_entry *neighbor;
  struct interface *ifn, *iterator;
  uint8_t *tmp;
#if !defined REMOVE_LOG_DEBUG
  struct ipaddr_str buf;
#endif

  /* Lookup sender address */
  src = olsr_lookup_main_addr_by_alias(from_addr);
  if (!src)
    src = from_addr;

  neighbor = olsr_lookup_nbr_entry(src, true);
  if (!neighbor) {
    OLSR_DEBUG(LOG_PACKET_PARSING, "Not forwarding message type %d because no nbr entry found for %s\n",
        msg->type, olsr_ip_to_string(&buf, src));
    return 0;
  }
  if (!neighbor->is_sym) {
    OLSR_DEBUG(LOG_PACKET_PARSING, "Not forwarding message type %d because received by non-symmetric neighbor %s\n",
        msg->type, olsr_ip_to_string(&buf, src));
    return 0;
  }

  /* Check MPR */
  if (neighbor->mprs_count == 0) {
    OLSR_DEBUG(LOG_PACKET_PARSING, "Not forwarding message type %d because we are no MPR for %s\n",
        msg->type, olsr_ip_to_string(&buf, src));
    /* don't forward packages if not a MPR */
    return 0;
  }

  /* check if we already forwarded this message */
  if (olsr_is_duplicate_message(msg, true, NULL)) {
    OLSR_DEBUG(LOG_PACKET_PARSING, "Not forwarding message type %d from %s because we already forwarded it.\n",
        msg->type, olsr_ip_to_string(&buf, src));
    return 0;                   /* it's a duplicate, forget about it */
  }

  /* Treat TTL hopcnt */
  msg->hopcnt++;
  msg->ttl--;
  tmp = binary;
  olsr_put_msg_hdr(&tmp, msg);

  if (msg->ttl == 0) {
    OLSR_DEBUG(LOG_PACKET_PARSING, "Not forwarding message type %d from %s because TTL is 0.\n",
        msg->type, olsr_ip_to_string(&buf, src));
    return 0;                   /* TTL 0, forget about it */
  }
  OLSR_DEBUG(LOG_PACKET_PARSING, "Forwarding message type %d from %s.\n",
      msg->type, olsr_ip_to_string(&buf, src));

  /* looping trough interfaces */
  OLSR_FOR_ALL_INTERFACES(ifn, iterator) {
    if (net_output_pending(ifn)) {
      /* dont forward to incoming interface if interface is mode ether */
      if (in_if->mode == IF_MODE_ETHER && ifn == in_if)
        continue;

      /*
       * Check if message is to big to be piggybacked
       */
      if (net_outbuffer_push(ifn, binary, msg->size) != msg->size) {
        /* Send */
        net_output(ifn);
        /* Buffer message */
        set_buffer_timer(ifn);

        if (net_outbuffer_push(ifn, binary, msg->size) != msg->size) {
          OLSR_WARN(LOG_NETWORKING, "Received message to big to be forwarded in %s(%d bytes)!", ifn->int_name, msg->size);
        }
      }
    } else {
      /* No forwarding pending */
      set_buffer_timer(ifn);

      if (net_outbuffer_push(ifn, binary, msg->size) != msg->size) {
        OLSR_WARN(LOG_NETWORKING, "Received message to big to be forwarded in %s(%d bytes)!", ifn->int_name, msg->size);
      }
    }
  }

  return 1;
}

/*
 * Local Variables:
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
/**
 * Use `AccordionActions` instead. This component will be removed in v5.
 *
 * @deprecated
 */
export { default } from '../AccordionActions';


text:
package net.bytebuddy.description.annotation;

import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.AbstractFilterableListTest;
import net.bytebuddy.matcher.ElementMatchers;
import org.hamcrest.CoreMatchers;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

public abstract class AbstractAnnotationListTest<U> extends AbstractFilterableListTest<AnnotationDescription, AnnotationList, U> {

    @Test
    public void testAnnotationIsPresent() throws Exception {
        assertThat(asList(getFirst()).isAnnotationPresent(Foo.class), is(true));
    }

    @Test
    public void testAnnotationIsNotPresent() throws Exception {
        assertThat(asList(getFirst()).isAnnotationPresent(Annotation.class), is(false));
    }

    @Test
    public void testAnnotationIsPresentDescription() throws Exception {
        assertThat(asList(getFirst()).isAnnotationPresent(new TypeDescription.ForLoadedType(Foo.class)), is(true));
    }

    @Test
    public void testAnnotationIsNotPresentDescription() throws Exception {
        assertThat(asList(getFirst()).isAnnotationPresent(new TypeDescription.ForLoadedType(Annotation.class)), is(false));
    }

    @Test
    public void testAnnotationOfType() throws Exception {
        assertThat(asList(getFirst()).ofType(Foo.class), is(AnnotationDescription.ForLoadedAnnotation.of(Holder.class.getAnnotation(Foo.class))));
    }

    @Test
    public void testAnnotationOfTypeWrongType() throws Exception {
        assertThat(asList(getFirst()).ofType(Annotation.class), nullValue(AnnotationDescription.Loadable.class));
    }

    @Test
    public void testAnnotationOfTypeDescription() throws Exception {
        assertThat(asList(getFirst()).ofType(new TypeDescription.ForLoadedType(Foo.class)),
                is((AnnotationDescription) AnnotationDescription.ForLoadedAnnotation.of(Holder.class.getAnnotation(Foo.class))));
    }

    @Test
    public void testAnnotationWrongTypeOfTypeDescription() throws Exception {
        assertThat(asList(getFirst()).ofType(new TypeDescription.ForLoadedType(Annotation.class)), nullValue(AnnotationDescription.class));
    }

    @Test
    public void testInherited() throws Exception {
        assertThat(asList(getFirst()).inherited(Collections.<TypeDescription>emptySet()), is(asList(getFirst())));
    }

    @Test
    public void testInheritedIgnoreType() throws Exception {
        assertThat(asList(getFirst()).inherited(Collections.<TypeDescription>singleton(new TypeDescription.ForLoadedType(Foo.class))).size(), is(0));
    }

    @Test
    public void testInheritedIgnoreNonInherited() throws Exception {
        assertThat(asList(getSecond()).inherited(Collections.<TypeDescription>emptySet()).size(), is(0));
    }

    @Test
    public void testVisible() throws Exception {
        assertThat(asList(getFirst()).visibility(ElementMatchers.is(RetentionPolicy.RUNTIME)), is(asList(getFirst())));
    }

    @Test
    public void testNotVisible() throws Exception {
        assertThat(asList(getFirst()).visibility(ElementMatchers.is(RetentionPolicy.SOURCE)).size(), is(0));
    }

    @Test
    public void testAsTypeList() throws Exception {
        assertThat(asList(getFirst()).asTypeList(), is(Collections.singletonList(asElement(getFirst()).getAnnotationType())));
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    protected @interface Foo {
        /* empty */
    }

    @Retention(RetentionPolicy.RUNTIME)
    protected @interface Bar {
        /* empty */
    }

    @Foo
    @Bar
    public static class Holder {
        /* empty */
    }
}


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

namespace Diameter
{
    // Longest distance after run 1 is the starting point for the longest distance overall.
    public class Diameter
    {
        private static Dictionary<int, int>[] nodes;

        public static void Main()
        {
            var nodesCount = int.Parse(Console.ReadLine());

            nodes = new Dictionary<int, int>[nodesCount];
            for (var i = 0; i < nodesCount; i++)
            {
                nodes[i] = new Dictionary<int, int>();
            }

            for (var i = 0; i < nodesCount - 1; i++)
            {
                var nextConnection = Console.ReadLine()
                    .Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(int.Parse)
                    .ToArray();

                if (nodes[nextConnection[0]].ContainsKey(nextConnection[2]) == false)
                {
                    nodes[nextConnection[0]].Add(nextConnection[2], nextConnection[1]);
                }

                if (nodes[nextConnection[1]].ContainsKey(nextConnection[2]) == false)
                {
                    nodes[nextConnection[1]].Add(nextConnection[2], nextConnection[0]);
                }
            }

            // RUN 1
            var nodeIndex = 0;
            var node = nodes[nodeIndex];

            var distances = new int[nodesCount];
            var visited = new bool[nodesCount];
            var currentMaxDistance = 0;

            distances[nodeIndex] = 0;
            visited[nodeIndex] = true;

            var queue = new Queue<Dictionary<int, int>>();
            queue.Enqueue(node);

            var indexesQueue = new Queue<int>();
            indexesQueue.Enqueue(nodeIndex);

            while (queue.Count != 0)
            {
                var currentNode = queue.Dequeue();
                var currentIndex = indexesQueue.Dequeue();

                foreach (var connection in currentNode)
                {
                    var nextIndex = connection.Value;

                    var connectingNode = nodes[connection.Value];
                    if (visited[nextIndex])
                    {
                        continue;
                    }

                    var potentialDistance = distances[currentIndex] + connection.Key;
                    if (potentialDistance > distances[nextIndex])
                    {
                        distances[nextIndex] = potentialDistance;
                    }

                    queue.Enqueue(connectingNode);
                    indexesQueue.Enqueue(nextIndex);

                    visited[currentIndex] = true;
                }
            }

            var maxDistance = 0;
            var maxDistanceIndex = -1;
            for (int i = 0; i < distances.Length; i++)
            {
                if (maxDistance < distances[i])
                {
                    maxDistance = distances[i];
                    maxDistanceIndex = i;
                }
            }

            // RUN 2
            nodeIndex = maxDistanceIndex;
            node = nodes[nodeIndex];

            distances = new int[nodesCount];
            visited = new bool[nodesCount];
            currentMaxDistance = 0;

            distances[nodeIndex] = 0;
            visited[nodeIndex] = true;

            queue = new Queue<Dictionary<int, int>>();
            queue.Enqueue(node);

            indexesQueue = new Queue<int>();
            indexesQueue.Enqueue(nodeIndex);

            while (queue.Count != 0)
            {
                var currentNode = queue.Dequeue();
                var currentIndex = indexesQueue.Dequeue();

                foreach (var connection in currentNode)
                {
                    var nextIndex = connection.Value;

                    var connectingNode = nodes[connection.Value];
                    if (visited[nextIndex])
                    {
                        continue;
                    }

                    var potentialDistance = distances[currentIndex] + connection.Key;
                    if (potentialDistance > distances[nextIndex])
                    {
                        distances[nextIndex] = potentialDistance;
                    }

                    if (currentMaxDistance < potentialDistance)
                    {
                        currentMaxDistance = potentialDistance;
                    }

                    queue.Enqueue(connectingNode);
                    indexesQueue.Enqueue(nextIndex);

                    visited[currentIndex] = true;
                }
            }

            Console.WriteLine(currentMaxDistance);
        }
    }
}


text:
package kubelet

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"github.com/golang/glog"
	"k8s.io/api/core/v1"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	"k8s.io/kubernetes/pkg/kubelet/network"
	kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
	"k8s.io/kubernetes/pkg/kubelet/util/format"
	utiliptables "k8s.io/kubernetes/pkg/util/iptables"
)

const (
	// KubeMarkMasqChain is the mark-for-masquerade chain
	// TODO: clean up this logic in kube-proxy
	KubeMarkMasqChain utiliptables.Chain = "KUBE-MARK-MASQ"

	// KubeMarkDropChain is the mark-for-drop chain
	KubeMarkDropChain utiliptables.Chain = "KUBE-MARK-DROP"

	// KubePostroutingChain is kubernetes postrouting rules
	KubePostroutingChain utiliptables.Chain = "KUBE-POSTROUTING"

	// KubeFirewallChain is kubernetes firewall rules
	KubeFirewallChain utiliptables.Chain = "KUBE-FIREWALL"
)

// This just exports required functions from kubelet proper, for use by network
// plugins.
// TODO(#35457): get rid of this backchannel to the kubelet. The scope of
// the back channel is restricted to host-ports/testing, and restricted
// to kubenet. No other network plugin wrapper needs it. Other plugins
// only require a way to access namespace information, which they can do
// directly through the methods implemented by criNetworkHost.
type networkHost struct {
	kubelet *Kubelet
}

func (nh *networkHost) GetPodByName(name, namespace string) (*v1.Pod, bool) {
	return nh.kubelet.GetPodByName(name, namespace)
}

func (nh *networkHost) GetKubeClient() clientset.Interface {
	return nh.kubelet.kubeClient
}

func (nh *networkHost) GetRuntime() kubecontainer.Runtime {
	return nh.kubelet.GetRuntime()
}

func (nh *networkHost) SupportsLegacyFeatures() bool {
	return true
}

// criNetworkHost implements the part of network.Host required by the
// cri (NamespaceGetter). It leechs off networkHost for all other
// methods, because networkHost is slated for deletion.
type criNetworkHost struct {
	*networkHost
	// criNetworkHost currently support legacy features. Hence no need to support PortMappingGetter
	*network.NoopPortMappingGetter
}

// GetNetNS returns the network namespace of the given containerID.
// This method satisfies the network.NamespaceGetter interface for
// networkHost. It's only meant to be used from network plugins
// that are directly invoked by the kubelet (aka: legacy, pre-cri).
// Any network plugin invoked by a cri must implement NamespaceGetter
// to talk directly to the runtime instead.
func (c *criNetworkHost) GetNetNS(containerID string) (string, error) {
	return c.kubelet.GetRuntime().GetNetNS(kubecontainer.ContainerID{Type: "", ID: containerID})
}

// NoOpLegacyHost implements the network.LegacyHost interface for the remote
// runtime shim by just returning empties. It doesn't support legacy features
// like host port and bandwidth shaping.
type NoOpLegacyHost struct{}

// GetPodByName always returns "nil, true" for 'NoOpLegacyHost'
func (n *NoOpLegacyHost) GetPodByName(namespace, name string) (*v1.Pod, bool) {
	return nil, true
}

// GetKubeClient always returns "nil" for 'NoOpLegacyHost'
func (n *NoOpLegacyHost) GetKubeClient() clientset.Interface {
	return nil
}

// GetRuntime always returns "nil" for 'NoOpLegacyHost'
func (n *NoOpLegacyHost) GetRuntime() kubecontainer.Runtime {
	return nil
}

// SupportsLegacyFeatures always returns "false" for 'NoOpLegacyHost'
func (n *NoOpLegacyHost) SupportsLegacyFeatures() bool {
	return false
}

// effectiveHairpinMode determines the effective hairpin mode given the
// configured mode, container runtime, and whether cbr0 should be configured.
func effectiveHairpinMode(hairpinMode kubeletconfig.HairpinMode, containerRuntime string, networkPlugin string) (kubeletconfig.HairpinMode, error) {
	// The hairpin mode setting doesn't matter if:
	// - We're not using a bridge network. This is hard to check because we might
	//   be using a plugin.
	// - It's set to hairpin-veth for a container runtime that doesn't know how
	//   to set the hairpin flag on the veth's of containers. Currently the
	//   docker runtime is the only one that understands this.
	// - It's set to "none".
	if hairpinMode == kubeletconfig.PromiscuousBridge || hairpinMode == kubeletconfig.HairpinVeth {
		// Only on docker.
		if containerRuntime != kubetypes.DockerContainerRuntime {
			glog.Warningf("Hairpin mode set to %q but container runtime is %q, ignoring", hairpinMode, containerRuntime)
			return kubeletconfig.HairpinNone, nil
		}
		if hairpinMode == kubeletconfig.PromiscuousBridge && networkPlugin != "kubenet" {
			// This is not a valid combination, since promiscuous-bridge only works on kubenet. Users might be using the
			// default values (from before the hairpin-mode flag existed) and we
			// should keep the old behavior.
			glog.Warningf("Hairpin mode set to %q but kubenet is not enabled, falling back to %q", hairpinMode, kubeletconfig.HairpinVeth)
			return kubeletconfig.HairpinVeth, nil
		}
	} else if hairpinMode != kubeletconfig.HairpinNone {
		return "", fmt.Errorf("unknown value: %q", hairpinMode)
	}
	return hairpinMode, nil
}

// providerRequiresNetworkingConfiguration returns whether the cloud provider
// requires special networking configuration.
func (kl *Kubelet) providerRequiresNetworkingConfiguration() bool {
	// TODO: We should have a mechanism to say whether native cloud provider
	// is used or whether we are using overlay networking. We should return
	// true for cloud providers if they implement Routes() interface and
	// we are not using overlay networking.
	if kl.cloud == nil || kl.cloud.ProviderName() != "gce" {
		return false
	}
	_, supported := kl.cloud.Routes()
	return supported
}

func omitDuplicates(pod *v1.Pod, combinedSearch []string) []string {
	uniqueDomains := map[string]bool{}

	for _, dnsDomain := range combinedSearch {
		if _, exists := uniqueDomains[dnsDomain]; !exists {
			combinedSearch[len(uniqueDomains)] = dnsDomain
			uniqueDomains[dnsDomain] = true
		}
	}
	return combinedSearch[:len(uniqueDomains)]
}

func (kl *Kubelet) formDNSSearchFitsLimits(pod *v1.Pod, composedSearch []string) []string {
	// resolver file Search line current limitations
	resolvSearchLineDNSDomainsLimit := 6
	resolvSearchLineLenLimit := 255
	limitsExceeded := false

	if len(composedSearch) > resolvSearchLineDNSDomainsLimit {
		composedSearch = composedSearch[:resolvSearchLineDNSDomainsLimit]
		limitsExceeded = true
	}

	if resolvSearchhLineStrLen := len(strings.Join(composedSearch, " ")); resolvSearchhLineStrLen > resolvSearchLineLenLimit {
		cutDomainsNum := 0
		cutDoaminsLen := 0
		for i := len(composedSearch) - 1; i >= 0; i-- {
			cutDoaminsLen += len(composedSearch[i]) + 1
			cutDomainsNum++

			if (resolvSearchhLineStrLen - cutDoaminsLen) <= resolvSearchLineLenLimit {
				break
			}
		}

		composedSearch = composedSearch[:(len(composedSearch) - cutDomainsNum)]
		limitsExceeded = true
	}

	if limitsExceeded {
		log := fmt.Sprintf("Search Line limits were exceeded, some dns names have been omitted, the applied search line is: %s", strings.Join(composedSearch, " "))
		kl.recorder.Event(pod, v1.EventTypeWarning, "DNSSearchForming", log)
		glog.Error(log)
	}
	return composedSearch
}

func (kl *Kubelet) formDNSSearchForDNSDefault(hostSearch []string, pod *v1.Pod) []string {
	return kl.formDNSSearchFitsLimits(pod, hostSearch)
}

func (kl *Kubelet) formDNSSearch(hostSearch []string, pod *v1.Pod) []string {
	if kl.clusterDomain == "" {
		kl.formDNSSearchFitsLimits(pod, hostSearch)
		return hostSearch
	}

	nsSvcDomain := fmt.Sprintf("%s.svc.%s", pod.Namespace, kl.clusterDomain)
	svcDomain := fmt.Sprintf("svc.%s", kl.clusterDomain)
	dnsSearch := []string{nsSvcDomain, svcDomain, kl.clusterDomain}

	combinedSearch := append(dnsSearch, hostSearch...)

	combinedSearch = omitDuplicates(pod, combinedSearch)
	return kl.formDNSSearchFitsLimits(pod, combinedSearch)
}

func (kl *Kubelet) checkLimitsForResolvConf() {
	// resolver file Search line current limitations
	resolvSearchLineDNSDomainsLimit := 6
	resolvSearchLineLenLimit := 255

	f, err := os.Open(kl.resolverConfig)
	if err != nil {
		kl.recorder.Event(kl.nodeRef, v1.EventTypeWarning, "checkLimitsForResolvConf", err.Error())
		glog.Error("checkLimitsForResolvConf: " + err.Error())
		return
	}
	defer f.Close()

	_, hostSearch, _, err := kl.parseResolvConf(f)
	if err != nil {
		kl.recorder.Event(kl.nodeRef, v1.EventTypeWarning, "checkLimitsForResolvConf", err.Error())
		glog.Error("checkLimitsForResolvConf: " + err.Error())
		return
	}

	domainCntLimit := resolvSearchLineDNSDomainsLimit

	if kl.clusterDomain != "" {
		domainCntLimit -= 3
	}

	if len(hostSearch) > domainCntLimit {
		log := fmt.Sprintf("Resolv.conf file '%s' contains search line consisting of more than %d domains!", kl.resolverConfig, domainCntLimit)
		kl.recorder.Event(kl.nodeRef, v1.EventTypeWarning, "checkLimitsForResolvConf", log)
		glog.Error("checkLimitsForResolvConf: " + log)
		return
	}

	if len(strings.Join(hostSearch, " ")) > resolvSearchLineLenLimit {
		log := fmt.Sprintf("Resolv.conf file '%s' contains search line which length is more than allowed %d chars!", kl.resolverConfig, resolvSearchLineLenLimit)
		kl.recorder.Event(kl.nodeRef, v1.EventTypeWarning, "checkLimitsForResolvConf", log)
		glog.Error("checkLimitsForResolvConf: " + log)
		return
	}

	return
}

// parseResolveConf reads a resolv.conf file from the given reader, and parses
// it into nameservers, searches and options, possibly returning an error.
// TODO: move to utility package
func (kl *Kubelet) parseResolvConf(reader io.Reader) (nameservers []string, searches []string, options []string, err error) {
	file, err := ioutil.ReadAll(reader)
	if err != nil {
		return nil, nil, nil, err
	}

	// Lines of the form "nameserver 1.2.3.4" accumulate.
	nameservers = []string{}

	// Lines of the form "search example.com" overrule - last one wins.
	searches = []string{}

	// Lines of the form "option ndots:5 attempts:2" overrule - last one wins.
	// Each option is recorded as an element in the array.
	options = []string{}

	lines := strings.Split(string(file), "\n")
	for l := range lines {
		trimmed := strings.TrimSpace(lines[l])
		if strings.HasPrefix(trimmed, "#") {
			continue
		}
		fields := strings.Fields(trimmed)
		if len(fields) == 0 {
			continue
		}
		if fields[0] == "nameserver" && len(fields) >= 2 {
			nameservers = append(nameservers, fields[1])
		}
		if fields[0] == "search" {
			searches = fields[1:]
		}
		if fields[0] == "options" {
			options = fields[1:]
		}
	}

	// There used to be code here to scrub DNS for each cloud, but doesn't
	// make sense anymore since cloudproviders are being factored out.
	// contact @thockin or @wlan0 for more information

	return nameservers, searches, options, nil
}

// GetClusterDNS returns a list of the DNS servers, a list of the DNS search
// domains of the cluster, and a list of resolv.conf options.
func (kl *Kubelet) GetClusterDNS(pod *v1.Pod) ([]string, []string, []string, bool, error) {
	var hostDNS, hostSearch, hostOptions []string
	// Get host DNS settings
	if kl.resolverConfig != "" {
		f, err := os.Open(kl.resolverConfig)
		if err != nil {
			return nil, nil, nil, false, err
		}
		defer f.Close()

		hostDNS, hostSearch, hostOptions, err = kl.parseResolvConf(f)
		if err != nil {
			return nil, nil, nil, false, err
		}
	}
	useClusterFirstPolicy := ((pod.Spec.DNSPolicy == v1.DNSClusterFirst && !kubecontainer.IsHostNetworkPod(pod)) || pod.Spec.DNSPolicy == v1.DNSClusterFirstWithHostNet)
	if useClusterFirstPolicy && len(kl.clusterDNS) == 0 {
		// clusterDNS is not known.
		// pod with ClusterDNSFirst Policy cannot be created
		kl.recorder.Eventf(pod, v1.EventTypeWarning, "MissingClusterDNS", "kubelet does not have ClusterDNS IP configured and cannot create Pod using %q policy. Falling back to DNSDefault policy.", pod.Spec.DNSPolicy)
		log := fmt.Sprintf("kubelet does not have ClusterDNS IP configured and cannot create Pod using %q policy. pod: %q. Falling back to DNSDefault policy.", pod.Spec.DNSPolicy, format.Pod(pod))
		kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, "MissingClusterDNS", log)

		// fallback to DNSDefault
		useClusterFirstPolicy = false
	}

	if !useClusterFirstPolicy {
		// When the kubelet --resolv-conf flag is set to the empty string, use
		// DNS settings that override the docker default (which is to use
		// /etc/resolv.conf) and effectively disable DNS lookups. According to
		// the bind documentation, the behavior of the DNS client library when
		// "nameservers" are not specified is to "use the nameserver on the
		// local machine". A nameserver setting of localhost is equivalent to
		// this documented behavior.
		if kl.resolverConfig == "" {
			hostDNS = []string{"127.0.0.1"}
			hostSearch = []string{"."}
		} else {
			hostSearch = kl.formDNSSearchForDNSDefault(hostSearch, pod)
		}
		return hostDNS, hostSearch, hostOptions, useClusterFirstPolicy, nil
	}

	// for a pod with DNSClusterFirst policy, the cluster DNS server is the only nameserver configured for
	// the pod. The cluster DNS server itself will forward queries to other nameservers that is configured to use,
	// in case the cluster DNS server cannot resolve the DNS query itself
	dns := make([]string, len(kl.clusterDNS))
	for i, ip := range kl.clusterDNS {
		dns[i] = ip.String()
	}
	dnsSearch := kl.formDNSSearch(hostSearch, pod)

	return dns, dnsSearch, hostOptions, useClusterFirstPolicy, nil
}

// Replace the nameserver in containerized-mounter's rootfs/etc/resolve.conf with kubelet.ClusterDNS
func (kl *Kubelet) setupDNSinContainerizedMounter(mounterPath string) {
	resolvePath := filepath.Join(strings.TrimSuffix(mounterPath, "/mounter"), "rootfs", "etc", "resolv.conf")
	dnsString := ""
	for _, dns := range kl.clusterDNS {
		dnsString = dnsString + fmt.Sprintf("nameserver %s\n", dns)
	}
	if kl.resolverConfig != "" {
		f, err := os.Open(kl.resolverConfig)
		defer f.Close()
		if err != nil {
			glog.Error("Could not open resolverConf file")
		} else {
			_, hostSearch, _, err := kl.parseResolvConf(f)
			if err != nil {
				glog.Errorf("Error for parsing the reslov.conf file: %v", err)
			} else {
				dnsString = dnsString + "search"
				for _, search := range hostSearch {
					dnsString = dnsString + fmt.Sprintf(" %s", search)
				}
				dnsString = dnsString + "\n"
			}
		}
	}
	if err := ioutil.WriteFile(resolvePath, []byte(dnsString), 0600); err != nil {
		glog.Errorf("Could not write dns nameserver in file %s, with error %v", resolvePath, err)
	}
}

// syncNetworkStatus updates the network state
func (kl *Kubelet) syncNetworkStatus() {
	// For cri integration, network state will be updated in updateRuntimeUp,
	// we'll get runtime network status through cri directly.
	// TODO: Remove this once we completely switch to cri integration.
	if kl.networkPlugin != nil {
		kl.runtimeState.setNetworkState(kl.networkPlugin.Status())
	}
}

// updatePodCIDR updates the pod CIDR in the runtime state if it is different
// from the current CIDR.
func (kl *Kubelet) updatePodCIDR(cidr string) {
	podCIDR := kl.runtimeState.podCIDR()

	if podCIDR == cidr {
		return
	}

	// kubelet -> network plugin
	// cri runtime shims are responsible for their own network plugins
	if kl.networkPlugin != nil {
		details := make(map[string]interface{})
		details[network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE_DETAIL_CIDR] = cidr
		kl.networkPlugin.Event(network.NET_PLUGIN_EVENT_POD_CIDR_CHANGE, details)
	}

	// kubelet -> generic runtime -> runtime shim -> network plugin
	// docker/rkt non-cri implementations have a passthrough UpdatePodCIDR
	if err := kl.GetRuntime().UpdatePodCIDR(cidr); err != nil {
		glog.Errorf("Failed to update pod CIDR: %v", err)
		return
	}

	glog.Infof("Setting Pod CIDR: %v -> %v", podCIDR, cidr)
	kl.runtimeState.setPodCIDR(cidr)
}

// syncNetworkUtil ensures the network utility are present on host.
// Network util includes:
// 1. 	In nat table, KUBE-MARK-DROP rule to mark connections for dropping
// 	Marked connection will be drop on INPUT/OUTPUT Chain in filter table
// 2. 	In nat table, KUBE-MARK-MASQ rule to mark connections for SNAT
// 	Marked connection will get SNAT on POSTROUTING Chain in nat table
func (kl *Kubelet) syncNetworkUtil() {
	if kl.iptablesMasqueradeBit < 0 || kl.iptablesMasqueradeBit > 31 {
		glog.Errorf("invalid iptables-masquerade-bit %v not in [0, 31]", kl.iptablesMasqueradeBit)
		return
	}

	if kl.iptablesDropBit < 0 || kl.iptablesDropBit > 31 {
		glog.Errorf("invalid iptables-drop-bit %v not in [0, 31]", kl.iptablesDropBit)
		return
	}

	if kl.iptablesDropBit == kl.iptablesMasqueradeBit {
		glog.Errorf("iptables-masquerade-bit %v and iptables-drop-bit %v must be different", kl.iptablesMasqueradeBit, kl.iptablesDropBit)
		return
	}

	// Setup KUBE-MARK-DROP rules
	dropMark := getIPTablesMark(kl.iptablesDropBit)
	if _, err := kl.iptClient.EnsureChain(utiliptables.TableNAT, KubeMarkDropChain); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s exists: %v", utiliptables.TableNAT, KubeMarkDropChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubeMarkDropChain, "-j", "MARK", "--set-xmark", dropMark); err != nil {
		glog.Errorf("Failed to ensure marking rule for %v: %v", KubeMarkDropChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureChain(utiliptables.TableFilter, KubeFirewallChain); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s exists: %v", utiliptables.TableFilter, KubeFirewallChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Append, utiliptables.TableFilter, KubeFirewallChain,
		"-m", "comment", "--comment", "kubernetes firewall for dropping marked packets",
		"-m", "mark", "--mark", dropMark,
		"-j", "DROP"); err != nil {
		glog.Errorf("Failed to ensure rule to drop packet marked by %v in %v chain %v: %v", KubeMarkDropChain, utiliptables.TableFilter, KubeFirewallChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableFilter, utiliptables.ChainOutput, "-j", string(KubeFirewallChain)); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s jumps to %s: %v", utiliptables.TableFilter, utiliptables.ChainOutput, KubeFirewallChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableFilter, utiliptables.ChainInput, "-j", string(KubeFirewallChain)); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s jumps to %s: %v", utiliptables.TableFilter, utiliptables.ChainInput, KubeFirewallChain, err)
		return
	}

	// Setup KUBE-MARK-MASQ rules
	masqueradeMark := getIPTablesMark(kl.iptablesMasqueradeBit)
	if _, err := kl.iptClient.EnsureChain(utiliptables.TableNAT, KubeMarkMasqChain); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s exists: %v", utiliptables.TableNAT, KubeMarkMasqChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureChain(utiliptables.TableNAT, KubePostroutingChain); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s exists: %v", utiliptables.TableNAT, KubePostroutingChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubeMarkMasqChain, "-j", "MARK", "--set-xmark", masqueradeMark); err != nil {
		glog.Errorf("Failed to ensure marking rule for %v: %v", KubeMarkMasqChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Prepend, utiliptables.TableNAT, utiliptables.ChainPostrouting,
		"-m", "comment", "--comment", "kubernetes postrouting rules", "-j", string(KubePostroutingChain)); err != nil {
		glog.Errorf("Failed to ensure that %s chain %s jumps to %s: %v", utiliptables.TableNAT, utiliptables.ChainPostrouting, KubePostroutingChain, err)
		return
	}
	if _, err := kl.iptClient.EnsureRule(utiliptables.Append, utiliptables.TableNAT, KubePostroutingChain,
		"-m", "comment", "--comment", "kubernetes service traffic requiring SNAT",
		"-m", "mark", "--mark", masqueradeMark, "-j", "MASQUERADE"); err != nil {
		glog.Errorf("Failed to ensure SNAT rule for packets marked by %v in %v chain %v: %v", KubeMarkMasqChain, utiliptables.TableNAT, KubePostroutingChain, err)
		return
	}
}

// getIPTablesMark returns the fwmark given the bit
func getIPTablesMark(bit int) string {
	value := 1 << uint(bit)
	return fmt.Sprintf("%#08x/%#08x", value, value)
}


text:
'use strict';

var utils = require('../../lib/utils');
var toISOString = require('../../lib/to-iso-string');
var JSON = require('json3');

describe('lib/utils', function () {
  describe('clean', function () {
    it('should remove the wrapping function declaration', function () {
      expect(utils.clean('function  (one, two, three)  {\n//code\n}'))
        .to
        .equal('//code');
    });

    it('should handle newlines in the function declaration', function () {
      expect(utils.clean('function  (one, two, three)\n  {\n//code\n}'))
        .to
        .equal('//code');
    });

    it('should remove space character indentation from the function body',
      function () {
        expect(utils.clean('  //line1\n    //line2'))
          .to
          .equal('//line1\n  //line2');
      });

    it('should remove tab character indentation from the function body',
      function () {
        expect(utils.clean('\t//line1\n\t\t//line2'))
          .to
          .equal('//line1\n\t//line2');
      });

    it('should handle functions with tabs in their declarations', function () {
      expect(utils.clean('function\t(\t)\t{\n//code\n}'))
        .to
        .equal('//code');
    });

    it('should handle named functions without space after name', function () {
      expect(utils.clean('function withName() {\n//code\n}'))
        .to
        .equal('//code');
    });

    it('should handle named functions with space after name', function () {
      expect(utils.clean('function withName () {\n//code\n}'))
        .to
        .equal('//code');
    });

    it(
      'should handle functions with no space between the end and the closing brace',
      function () {
        expect(utils.clean('function() {/*code*/}'))
          .to
          .equal('/*code*/');
      });

    it('should handle functions with parentheses in the same line',
      function () {
        expect(utils.clean('function() { if (true) { /* code */ } }'))
          .to
          .equal('if (true) { /* code */ }');
      });

    it('should handle empty functions', function () {
      expect(utils.clean('function() {}'))
        .to
        .equal('');
    });

    it('should format a single line test function', function () {
      var fn = [
        'function () {',
        '  var a = 1;',
        '}'
      ].join('\n');
      expect(utils.clean(fn))
        .to
        .equal('var a = 1;');
    });

    it('should format a multi line test indented with spaces', function () {
      // and no new lines after curly braces, shouldn't matter
      var fn = [
        'function(){  var a = 1;',
        // this one has more spaces
        '    var b = 2;',
        '  var c = 3;  }'
      ].join('\n');
      expect(utils.clean(fn))
        .to
        .equal('var a = 1;\n  var b = 2;\nvar c = 3;');
    });

    it('should format a multi line test indented with tabs', function () {
      var fn = [
        'function (arg1, arg2)   {',
        '\tif (true) {',
        '\t\tvar a = 1;',
        '\t}',
        '}'
      ].join('\n');
      expect(utils.clean(fn))
        .to
        .equal('if (true) {\n\tvar a = 1;\n}');
    });

    it('should format functions saved in windows style - spaces', function () {
      var fn = [
        'function (one) {',
        '   do {',
        '    "nothing";',
        '   } while (false);',
        ' }'
      ].join('\r\n');
      expect(utils.clean(fn))
        .to
        .equal('do {\n "nothing";\n} while (false);');
    });

    it('should format functions saved in windows style - tabs', function () {
      var fn = [
        'function ( )   {',
        '\tif (false) {',
        '\t\tvar json = {',
        '\t\t\tone : 1',
        '\t\t};',
        '\t}',
        '}'
      ].join('\r\n');
      expect(utils.clean(fn))
        .to
        .equal('if (false) {\n\tvar json = {\n\t\tone : 1\n\t};\n}');
    });

    it('should format es6 arrow functions', function () {
      var fn = [
        '() => {',
        '  var a = 1;',
        '}'
      ].join('\n');
      expect(utils.clean(fn))
        .to
        .equal('var a = 1;');
    });

    it('should format es6 arrow functions with implicit return', function () {
      var fn = '() => foo()';
      expect(utils.clean(fn))
        .to
        .equal('foo()');
    });
  });

  describe('stringify', function () {
    var stringify = utils.stringify;

    it('should return an object representation of a string created with a String constructor', function () {
      /* eslint no-new-wrappers: off */
      expect(stringify(new String('foo'))).to.equal('{\n  "0": "f"\n  "1": "o"\n  "2": "o"\n}');
    });

    it('should return Buffer with .toJSON representation', function () {
      expect(stringify(new Buffer([0x01]))).to.equal('[\n  1\n]');
      expect(stringify(new Buffer([0x01, 0x02]))).to.equal('[\n  1\n  2\n]');

      expect(stringify(new Buffer('ABCD'))).to.equal('[\n  65\n  66\n  67\n  68\n]');
    });

    it('should return Date object with .toISOString() + string prefix', function () {
      expect(stringify(new Date(0))).to.equal('[Date: ' + shimToISOString(new Date(0)) + ']');

      var date = new Date(); // now
      expect(stringify(date)).to.equal('[Date: ' + shimToISOString(date) + ']');

      function shimToISOString (date) {
        if (date.toISOString) {
          return date.toISOString();
        } else {
          return toISOString(date);
        }
      }
    });

    it('should return invalid Date object with .toString() + string prefix', function () {
      expect(stringify(new Date(''))).to.equal('[Date: ' + new Date('').toString() + ']');
    });

    describe('#Number', function () {
      it('should show the handle -0 situations', function () {
        expect(stringify(-0)).to.eql('-0');
        expect(stringify(0)).to.eql('0');
        expect(stringify('-0')).to.eql('"-0"');
      });

      it('should work well with `NaN` and `Infinity`', function () {
        expect(stringify(NaN)).to.equal('NaN');
        expect(stringify(Infinity)).to.equal('Infinity');
        expect(stringify(-Infinity)).to.equal('-Infinity');
      });

      it('floats and ints', function () {
        expect(stringify(1)).to.equal('1');
        expect(stringify(1.2)).to.equal('1.2');
        expect(stringify(1e9)).to.equal('1000000000');
      });
    });

    describe('canonicalize example', function () {
      it('should represent the actual full result', function () {
        var expected = {
          str: 'string',
          int: 90,
          float: 9.99,
          boolean: false,
          nil: null,
          undef: undefined,
          regex: /^[a-z|A-Z]/,
          date: new Date(0),
          func: function () {},
          infi: Infinity,
          nan: NaN,
          zero: -0,
          buffer: new Buffer([0x01, 0x02]),
          array: [1, 2, 3],
          empArr: [],
          matrix: [[1],
            [
              2,
              3,
              4
            ]
          ],
          object: { a: 1, b: 2 },
          canObj: { a: { b: 1, c: 2 }, b: {} },
          empObj: {}
        };
        expected.circular = expected; // Make `Circular` situation
        var actual = [
          '{',
          '  "array": [',
          '    1',
          '    2',
          '    3',
          '  ]',
          '  "boolean": false',
          '  "buffer": [Buffer: [',
          '    1',
          '    2',
          '  ]]',
          '  "canObj": {',
          '    "a": {',
          '      "b": 1',
          '      "c": 2',
          '    }',
          '    "b": {}',
          '  }',
          '  "circular": [Circular]',
          '  "date": [Date: 1970-01-01T00:00:00.000Z]',
          '  "empArr": []',
          '  "empObj": {}',
          '  "float": 9.99',
          '  "func": [Function]',
          '  "infi": Infinity',
          '  "int": 90',
          '  "matrix": [',
          '    [',
          '      1',
          '    ]',
          '    [',
          '      2',
          '      3',
          '      4',
          '    ]',
          '  ]',
          '  "nan": NaN',
          '  "nil": [null]',
          '  "object": {',
          '    "a": 1',
          '    "b": 2',
          '  }',
          '  "regex": /^[a-z|A-Z]/',
          '  "str": "string"',
          '  "undef": [undefined]',
          '  "zero": -0',
          '}'
        ].join('\n');
        expect(stringify(expected)).to.equal(actual);
      });
    });

    it('should canonicalize the object', function () {
      var travis = { name: 'travis', age: 24 };
      var travis2 = { age: 24, name: 'travis' };

      expect(stringify(travis)).to.equal(stringify(travis2));
    });

    it('should handle circular structures in objects', function () {
      var travis = { name: 'travis' };
      travis.whoami = travis;

      expect(stringify(travis)).to.equal('{\n  "name": "travis"\n  "whoami": [Circular]\n}');
    });

    it('should handle circular structures in arrays', function () {
      var travis = ['travis'];
      travis.push(travis);

      expect(stringify(travis)).to.equal('[\n  "travis"\n  [Circular]\n]');
    });

    it('should handle circular structures in functions', function () {
      var travis = function () {};
      travis.fn = travis;

      expect(stringify(travis)).to.equal('{\n  "fn": [Circular]\n}');
    });

    it('should handle various non-undefined, non-null, non-object, non-array, non-date, and non-function values', function () {
      var regexp = new RegExp('(?:)');
      var regExpObj = {regexp: regexp};
      var regexpString = '/(?:)/';

      expect(stringify(regExpObj)).to.equal('{\n  "regexp": ' + regexpString + '\n}');
      expect(stringify(regexp)).to.equal(regexpString);

      var number = 1;
      var numberObj = {number: number};
      var numberString = '1';

      expect(stringify(numberObj)).to.equal('{\n  "number": ' + number + '\n}');
      expect(stringify(number)).to.equal(numberString);

      var boolean = false;
      var booleanObj = {boolean: boolean};
      var booleanString = 'false';

      expect(stringify(booleanObj)).to.equal('{\n  "boolean": ' + boolean + '\n}');
      expect(stringify(boolean)).to.equal(booleanString);

      var string = 'sneepy';
      var stringObj = {string: string};

      expect(stringify(stringObj)).to.equal('{\n  "string": "' + string + '"\n}');
      expect(stringify(string)).to.equal(JSON.stringify(string));

      var nullValue = null;
      var nullObj = {'null': null};
      var nullString = '[null]';

      expect(stringify(nullObj)).to.equal('{\n  "null": [null]\n}');
      expect(stringify(nullValue)).to.equal(nullString);
    });

    it('should handle arrays', function () {
      var array = ['dave', 'dave', 'dave', 'dave'];
      var arrayObj = {array: array};
      var arrayString = '    "dave"\n    "dave"\n    "dave"\n    "dave"';

      expect(stringify(arrayObj)).to.equal('{\n  "array": [\n' + arrayString + '\n  ]\n}');
      expect(stringify(array)).to.equal('[' + arrayString.replace(/\s+/g, '\n  ') + '\n]');
    });

    it('should handle functions', function () {
      var fn = function () {};
      var fnObj = {fn: fn};
      var fnString = '[Function]';

      expect(stringify(fnObj)).to.equal('{\n  "fn": ' + fnString + '\n}');
      expect(stringify(fn)).to.equal('[Function]');
    });

    it('should handle empty objects', function () {
      expect(stringify({})).to.equal('{}');
      expect(stringify({foo: {}})).to.equal('{\n  "foo": {}\n}');
    });

    it('should handle empty arrays', function () {
      expect(stringify([])).to.equal('[]');
      expect(stringify({foo: []})).to.equal('{\n  "foo": []\n}');
    });

    it('should handle non-empty arrays', function () {
      expect(stringify(['a', 'b', 'c'])).to.equal('[\n  "a"\n  "b"\n  "c"\n]');
    });

    it('should handle empty functions (with no properties)', function () {
      expect(stringify(function () {})).to.equal('[Function]');
      expect(stringify({foo: function () {}})).to.equal('{\n  "foo": [Function]\n}');
      expect(stringify({foo: function () {}, bar: 'baz'})).to.equal('{\n  "bar": "baz"\n  "foo": [Function]\n}');
    });

    it('should handle functions w/ properties', function () {
      var fn = function () {};
      fn.bar = 'baz';
      expect(stringify(fn)).to.equal('{\n  "bar": "baz"\n}');
      expect(stringify({foo: fn})).to.equal('{\n  "foo": {\n    "bar": "baz"\n  }\n}');
    });

    it('should handle undefined values', function () {
      expect(stringify({foo: undefined})).to.equal('{\n  "foo": [undefined]\n}');
      expect(stringify({foo: 'bar', baz: undefined})).to.equal('{\n  "baz": [undefined]\n  "foo": "bar"\n}');
      expect(stringify()).to.equal('[undefined]');
    });

    it('should recurse', function () {
      expect(stringify({foo: {bar: {baz: {quux: {herp: 'derp'}}}}})).to.equal('{\n  "foo": {\n    "bar": {\n      "baz": {\n        "quux": {\n          "herp": "derp"\n        }\n      }\n    }\n  }\n}');
    });

    it('might get confusing', function () {
      expect(stringify(null)).to.equal('[null]');
    });

    it('should not freak out if it sees a primitive twice', function () {
      expect(stringify({foo: null, bar: null})).to.equal('{\n  "bar": [null]\n  "foo": [null]\n}');
      expect(stringify({foo: 1, bar: 1})).to.equal('{\n  "bar": 1\n  "foo": 1\n}');
    });

    it('should stringify dates', function () {
      var date = new Date(0);
      expect(stringify(date)).to.equal('[Date: 1970-01-01T00:00:00.000Z]');
      expect(stringify({date: date})).to.equal('{\n  "date": [Date: 1970-01-01T00:00:00.000Z]\n}');
    });

    it('should handle object without an Object prototype', function () {
      var a;
      if (Object.create) {
        a = Object.create(null);
      } else {
        a = {};
      }
      a.foo = 1;

      expect(stringify(a)).to.equal('{\n  "foo": 1\n}');
    });

    // In old version node.js, Symbol is not available by default.
    if (typeof global.Symbol === 'function') {
      it('should handle Symbol', function () {
        var symbol = Symbol('value');
        expect(stringify(symbol)).to.equal('Symbol(value)');
        expect(stringify({symbol: symbol})).to.equal('{\n  "symbol": Symbol(value)\n}');
      });
    }

    it('should handle length properties that cannot be coerced to a number', function () {
      expect(stringify({length: {nonBuiltinProperty: 0}})).to.equal('{\n  "length": {\n    "nonBuiltinProperty": 0\n  }\n}');
      expect(stringify({length: 'a string where length should be'})).to.equal('{\n  "length": "a string where length should be"\n}');
    });
  });

  describe('type', function () {
    /* eslint no-extend-native: off */

    var type = utils.type;
    var toString = Object.prototype.toString;

    beforeEach(function () {
      // some JS engines such as PhantomJS 1.x exhibit this behavior
      Object.prototype.toString = function () {
        if (this === global) {
          return '[object DOMWindow]';
        }
        return toString.call(this);
      };
    });

    it('should recognize various types', function () {
      expect(type({})).to.equal('object');
      expect(type([])).to.equal('array');
      expect(type(1)).to.equal('number');
      expect(type(Infinity)).to.equal('number');
      expect(type(null)).to.equal('null');
      expect(type(undefined)).to.equal('undefined');
      expect(type(new Date())).to.equal('date');
      expect(type(/foo/)).to.equal('regexp');
      expect(type('type')).to.equal('string');
      expect(type(global)).to.equal('domwindow');
      expect(type(true)).to.equal('boolean');
    });

    describe('when toString on null or undefined stringifies window', function () {
      it('should recognize null and undefined', function () {
        expect(type(null)).to.equal('null');
        expect(type(undefined)).to.equal('undefined');
      });
    });

    afterEach(function () {
      Object.prototype.toString = toString;
    });
  });

  describe('isBuffer()', function () {
    var isBuffer = utils.isBuffer;
    it('should test if object is a Buffer', function () {
      expect(isBuffer(new Buffer([0x01])))
        .to
        .equal(true);
      expect(isBuffer({}))
        .to
        .equal(false);
    });
  });

  describe('map()', function () {
    var map = utils.map;
    it('should behave same as Array.prototype.map', function () {
      if (!Array.prototype.map) {
        this.skip();
        return;
      }

      var arr = [
        1,
        2,
        3
      ];
      expect(map(arr, JSON.stringify))
        .to
        .eql(arr.map(JSON.stringify));
    });

    it('should call the callback with 3 arguments[currentValue, index, array]',
      function () {
        var index = 0;
        map([
          1,
          2,
          3
        ], function (e, i, arr) {
          expect(e).to.equal(arr[index]);
          expect(i).to.equal(index++);
        });
      });

    it('should apply with the given scope', function () {
      var scope = {};
      map([
        'a',
        'b',
        'c'
      ], function () {
        expect(this).to.equal(scope);
      }, scope);
    });
  });

  describe('some()', function () {
    var some = utils.some;

    it(
      'should return true when some array elements pass the check of the fn parameter',
      function () {
        var result = some([
          'a',
          'b',
          'c'
        ], function (e) {
          return e === 'b';
        });
        expect(result).to.eql(true);
      });

    it(
      'should return false when none of the array elements pass the check of the fn parameter',
      function () {
        var result = some([
          'a',
          'b',
          'c'
        ], function (e) {
          return e === 'd';
        });
        expect(result).to.eql(false);
      });
  });

  describe('parseQuery()', function () {
    var parseQuery = utils.parseQuery;
    it('should get queryString and return key-value object', function () {
      expect(parseQuery('?foo=1&bar=2&baz=3'))
        .to
        .eql({
          foo: '1',
          bar: '2',
          baz: '3'
        });

      expect(parseQuery('?r1=^@(?!.*\\)$)&r2=m{2}&r3=^co.*'))
        .to
        .eql({
          r1: '^@(?!.*\\)$)',
          r2: 'm{2}',
          r3: '^co.*'
        });
    });

    it('should parse "+" as a space', function () {
      expect(parseQuery('?grep=foo+bar'))
        .to
        .eql({grep: 'foo bar'});
    });
  });

  describe('isPromise', function () {
    it('should return true if the value is Promise-ish', function () {
      expect(utils.isPromise({
        then: function () {
        }
      })).to.be(true);
    });

    it('should return false if the value is not an object', function () {
      expect(utils.isPromise(1)).to.be(false);
    });

    it('should return false if the value is an object w/o a "then" function',
      function () {
        expect(utils.isPromise({})).to.be(false);
      });
  });
});


text:
package robot_algorithm;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	private MazeSolverAlgorithm solver;

	public Server() throws Exception {
		System.out.println("Maze Solver Server Ready. Wait on port 31000");
		Socket sock = new ServerSocket(31000).accept();
		this.response(sock);
		sock.close();
	}

	private void response(Socket sock) throws Exception {
		InputStream in = sock.getInputStream();
		OutputStream out = sock.getOutputStream();

		solver = new MazeSolver_DepthFirst1();
		solver.init();

		byte[] bytes = new byte[1];
		while (true) {
			in.read(bytes);
			System.out.println("==================================");
			System.out.println("From Robot:" + Client.byteArrayToHex(bytes));
			process(bytes, out, sock);
			if (sock.isClosed())
				break;
		}
	}

	private void process(byte[] bytes, OutputStream out, Socket sock) throws Exception {

		switch (bytes[0]) {
		case 0x1:// full map ¿äû
			byte[] mazeBytes = solver.getMaze().getMazeAsBytes();
			out.write(mazeBytes);
			out.flush();
			break;
		case 0x4:// ´ÙÀ½ ¹æÇâ ¿äû
			try {
				byte[] input = new byte[12];
				sock.getInputStream().read(input);
				System.out.println("From Robot:" + Client.byteArrayToHex(input));
				solver.getMaze().setCell(input);
				byte[] rv = solver.getNext();
				System.out.println("Next Direction: " + Client.byteArrayToHex(rv));
				out.write(rv);
				out.flush();
			} catch (Exception e) {
				out.write(MazeSolverAlgorithm.ERROR);
				out.flush();
			}
			break;
		case 0x9:// reset ¿äû
			byte[] input = new byte[1];
			sock.getInputStream().read(input);
			System.out.println("From Robot:" + Client.byteArrayToHex(input));
			switch (input[0]) {
			case 0x01:
				solver = new MazeSolver_DepthFirst1();
				break;
			case 0x02:
				solver = new MazeSolver_DepthFirst2();
				break;
			case 0x03:
				solver = new MazeSolver_DepthFirst3();
				break;
			case 0x04:
				solver = new MazeSolver_StraightFirst();
				break;
			case 0x05:
				solver = new MazeSolver_DepthFirst_skip2();
				break;
			default:
				solver = new MazeSolver_DepthFirst1();
			}
			solver.init();
			out.write(MazeSolverAlgorithm.INIT_OK);
			out.flush();
			System.out.println("==============INIT_OK=================");
			break;
		}
	}

	public static void main(String[] args) {
		try {
			new Server();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
#ifndef _DECAF_UTIL_CONCURRENT_LOCKS_REENTRANTREADWRITELOCKTEST_H_
#define _DECAF_UTIL_CONCURRENT_LOCKS_REENTRANTREADWRITELOCKTEST_H_

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <decaf/util/concurrent/ExecutorsTestSupport.h>

namespace decaf {
namespace util {
namespace concurrent {
namespace locks {

    class ReentrantReadWriteLockTest : public ExecutorsTestSupport {

        CPPUNIT_TEST_SUITE( ReentrantReadWriteLockTest );
        CPPUNIT_TEST( testConstructor );
        CPPUNIT_TEST( testLock );
        CPPUNIT_TEST( testFairLock );
        CPPUNIT_TEST( testGetWriteHoldCount );
        CPPUNIT_TEST( testUnlockIllegalMonitorStateException );
        CPPUNIT_TEST( testReadHoldingWriteLock );
        CPPUNIT_TEST( testReadHoldingWriteLock2 );
        CPPUNIT_TEST( testReadHoldingWriteLock3 );
        CPPUNIT_TEST( testReadHoldingWriteLockFair );
        CPPUNIT_TEST( testAwaitIllegalMonitor );
        CPPUNIT_TEST( testSignalIllegalMonitor );
        CPPUNIT_TEST( testAwaitNanosTimeout );
        CPPUNIT_TEST( testAwaitTimeout );
        CPPUNIT_TEST( testAwaitUntilTimeout );
        CPPUNIT_TEST( testHasQueuedThreadNPE );
        CPPUNIT_TEST( testHasWaitersNPE );
        CPPUNIT_TEST( testGetWaitQueueLengthNPE );
        CPPUNIT_TEST( testGetWaitingThreadsNPE );
        CPPUNIT_TEST( testHasWaitersIAE );
        CPPUNIT_TEST( testHasWaitersIMSE );
        CPPUNIT_TEST( testGetWaitQueueLengthIAE );
        CPPUNIT_TEST( testGetWaitQueueLengthIMSE );
        CPPUNIT_TEST( testGetWaitingThreadsIAE );
        CPPUNIT_TEST( testGetWaitingThreadsIMSE );
        CPPUNIT_TEST( testToString );
        CPPUNIT_TEST( testReadLockToString );
        CPPUNIT_TEST( testWriteLockToString );
        CPPUNIT_TEST( testWriteLockInterruptiblyInterrupted );
        CPPUNIT_TEST( testWriteTryLockInterrupted );
        CPPUNIT_TEST( testReadLockInterruptiblyInterrupted );
        CPPUNIT_TEST( testReadTryLockInterrupted );
        CPPUNIT_TEST( testWriteTryLockWhenLocked );
        CPPUNIT_TEST( testReadTryLockWhenLocked );
        CPPUNIT_TEST( testMultipleReadLocks );
        CPPUNIT_TEST( testReadAfterWriteLock );
        CPPUNIT_TEST( testWriteHoldingWriteLock4 );
        CPPUNIT_TEST( testReadHoldingWriteLockFair2 );
        CPPUNIT_TEST( testReadHoldingWriteLockFair3 );
        CPPUNIT_TEST( testWriteHoldingWriteLockFair4 );
        CPPUNIT_TEST( testTryLockWhenReadLocked );
        CPPUNIT_TEST( testWriteAfterMultipleReadLocks );
        CPPUNIT_TEST( testTryLockWhenReadLockedFair );
        CPPUNIT_TEST( testWriteTryLockWhenReadLockedFair );
        CPPUNIT_TEST( testWriteTryLockTimeout );
        CPPUNIT_TEST( testReadTryLockTimeout );
        CPPUNIT_TEST( testWriteLockInterruptibly );
        CPPUNIT_TEST( testReadLockInterruptibly );
        CPPUNIT_TEST( testAwait );
        CPPUNIT_TEST( testAwaitUninterruptibly );
        CPPUNIT_TEST( testAwaitInterrupt );
        CPPUNIT_TEST( testAwaitNanosInterrupt );
        CPPUNIT_TEST( testAwaitUntilInterrupt );
        CPPUNIT_TEST( testSignalAll );
        CPPUNIT_TEST( testHasQueuedThreads );
        CPPUNIT_TEST( testHasQueuedThread );
        CPPUNIT_TEST( testGetQueueLength );
        CPPUNIT_TEST( testGetQueuedThreads );
        CPPUNIT_TEST( testHasWaiters );
        CPPUNIT_TEST( testGetWaitQueueLength );
        CPPUNIT_TEST( testGetWaitingThreads );
        CPPUNIT_TEST( testMultipleReaderThreads );
        CPPUNIT_TEST_SUITE_END();

    public:

        ReentrantReadWriteLockTest();
        virtual ~ReentrantReadWriteLockTest();

        void testConstructor();
        void testLock();
        void testFairLock();
        void testWriteLockInterruptiblyInterrupted();
        void testGetWriteHoldCount();
        void testUnlockIllegalMonitorStateException();
        void testReadHoldingWriteLock();
        void testReadHoldingWriteLock2();
        void testReadHoldingWriteLock3();
        void testReadHoldingWriteLockFair();
        void testAwaitIllegalMonitor();
        void testSignalIllegalMonitor();
        void testAwaitNanosTimeout();
        void testAwaitTimeout();
        void testAwaitUntilTimeout();
        void testHasQueuedThreadNPE();
        void testHasWaitersNPE();
        void testGetWaitQueueLengthNPE();
        void testGetWaitingThreadsNPE();
        void testHasWaitersIAE();
        void testHasWaitersIMSE();
        void testGetWaitQueueLengthIAE();
        void testGetWaitQueueLengthIMSE();
        void testGetWaitingThreadsIAE();
        void testGetWaitingThreadsIMSE();
        void testToString();
        void testReadLockToString();
        void testWriteLockToString();
        void testWriteTryLockInterrupted();
        void testReadLockInterruptiblyInterrupted();
        void testReadTryLockInterrupted();
        void testWriteTryLockWhenLocked();
        void testReadTryLockWhenLocked();
        void testMultipleReadLocks();
        void testWriteAfterMultipleReadLocks();
        void testReadAfterWriteLock();
        void testWriteHoldingWriteLock4();
        void testReadHoldingWriteLockFair2();
        void testReadHoldingWriteLockFair3();
        void testWriteHoldingWriteLockFair4();
        void testTryLockWhenReadLocked();
        void testWriteTryLockWhenReadLocked();
        void testTryLockWhenReadLockedFair();
        void testWriteTryLockWhenReadLockedFair();
        void testWriteTryLockTimeout();
        void testReadTryLockTimeout();
        void testWriteLockInterruptibly();
        void testReadLockInterruptibly();
        void testAwait();
        void testAwaitUninterruptibly();
        void testAwaitInterrupt();
        void testAwaitNanosInterrupt();
        void testAwaitUntilInterrupt();
        void testSignalAll();
        void testHasQueuedThreads();
        void testHasQueuedThread();
        void testGetQueueLength();
        void testGetQueuedThreads();
        void testHasWaiters();
        void testGetWaitQueueLength();
        void testGetWaitingThreads();
        void testMultipleReaderThreads();

    };

}}}}

#endif /* _DECAF_UTIL_CONCURRENT_LOCKS_REENTRANTREADWRITELOCKTEST_H_ */


text:
require 'optparse'
require 'hocon'
require 'hocon/version'
require 'hocon/config_render_options'
require 'hocon/config_factory'
require 'hocon/config_value_factory'
require 'hocon/parser/config_document_factory'
require 'hocon/config_error'

module Hocon::CLI
  # Aliases
  ConfigMissingError = Hocon::ConfigError::ConfigMissingError
  ConfigWrongTypeError = Hocon::ConfigError::ConfigWrongTypeError

  # List of valid subcommands
  SUBCOMMANDS = ['get', 'set', 'unset']

  # For when a path can't be found in a hocon config
  class MissingPathError < StandardError
  end

  # Parses the command line flags and argument
  # Returns a options hash with values for each option and argument
  def self.parse_args(args)
    options = {}
    opt_parser = OptionParser.new do |opts|
      subcommands = SUBCOMMANDS.join(',')
      opts.banner = "Usage: hocon [options] {#{subcommands}} PATH [VALUE]\n\n" +
          "Example usages:\n" +
          "  hocon -i settings.conf -o new_settings.conf set some.nested.value 42\n" +
          "  hocon -f settings.conf set some.nested.value 42\n" +
          "  cat settings.conf | hocon get some.nested.value\n\n" +
          "Subcommands:\n" +
          "  get PATH - Returns the value at the given path\n" +
          "  set PATH VALUE - Sets or adds the given value at the given path\n" +
          "  unset PATH - Removes the value at the given path"

      opts.separator('')
      opts.separator('Options:')

      in_file_description = 'HOCON file to read/modify. If omitted, STDIN assumed'
      opts.on('-i', '--in-file HOCON_FILE', in_file_description) do |in_file|
        options[:in_file] = in_file
      end

      out_file_description = 'File to be written to. If omitted, STDOUT assumed'
      opts.on('-o', '--out-file HOCON_FILE', out_file_description) do |out_file|
        options[:out_file] = out_file
      end

      file_description = 'File to read/write to. Equivalent to setting -i/-o to the same file'
      opts.on('-f', '--file HOCON_FILE', file_description) do |file|
        options[:file] = file
      end

      json_description = "Output values from the 'get' subcommand in json format"
      opts.on('-j', '--json', json_description) do |json|
        options[:json] = json
      end

      opts.on_tail('-h', '--help', 'Show this message') do
        puts opts
        exit
      end

      opts.on_tail('-v', '--version', 'Show version') do
        puts Hocon::Version::STRING
        exit
      end
    end
    # parse! returns the argument list minus all the flags it found
    remaining_args = opt_parser.parse!(args)

    # Ensure -i and -o aren't used at the same time as -f
    if (options[:in_file] || options[:out_file]) && options[:file]
      exit_with_usage_and_error(opt_parser, "--file can't be used with --in-file or --out-file")
    end

    # If --file is used, set --in/out-file to the same file
    if options[:file]
      options[:in_file] = options[:file]
      options[:out_file] = options[:file]
    end

    no_subcommand_error(opt_parser) unless remaining_args.size > 0

    # Assume the first arg is the subcommand
    subcommand = remaining_args.shift
    options[:subcommand] = subcommand

    case subcommand
      when 'set'
        subcommand_arguments_error(subcommand, opt_parser) unless remaining_args.size >= 2
        options[:path] = remaining_args.shift
        options[:new_value] = remaining_args.shift

      when 'get', 'unset'
        subcommand_arguments_error(subcommand, opt_parser) unless remaining_args.size >= 1
        options[:path] = remaining_args.shift

      else
        invalid_subcommand_error(subcommand, opt_parser)
    end

    options
  end

  # Main entry point into the script
  # Calls the appropriate subcommand and handles errors raised from the subcommands
  def self.main(opts)
    hocon_text = get_hocon_file(opts[:in_file])

    begin
      case opts[:subcommand]
        when 'get'
          puts do_get(opts, hocon_text)
        when 'set'
          print_or_write(do_set(opts, hocon_text), opts[:out_file])
        when 'unset'
          print_or_write(do_unset(opts, hocon_text), opts[:out_file])
      end

    rescue MissingPathError
      exit_with_error("Can't find the given path: '#{opts[:path]}'")
    end

    exit
  end

  # Entry point for the 'get' subcommand
  # Returns a string representation of the the value at the path given on the
  # command line
  def self.do_get(opts, hocon_text)
    config = Hocon::ConfigFactory.parse_string(hocon_text)
    unless config.has_path?(opts[:path])
      raise MissingPathError.new
    end

    value = config.get_any_ref(opts[:path])

    render_options = Hocon::ConfigRenderOptions.defaults
    # Otherwise weird comments show up in the output
    render_options.origin_comments = false
    # If json is false, the hocon format is used
    render_options.json = opts[:json]
    # Output colons between keys and values
    render_options.key_value_separator = :colon

    Hocon::ConfigValueFactory.from_any_ref(value).render(render_options)
  end

  # Entry point for the 'set' subcommand
  # Returns a string representation of the HOCON config after adding/replacing
  # the value at the given path with the given value
  def self.do_set(opts, hocon_text)
    config_doc = Hocon::Parser::ConfigDocumentFactory.parse_string(hocon_text)
    modified_config_doc = config_doc.set_value(opts[:path], opts[:new_value])

    modified_config_doc.render
  end

  # Entry point for the 'unset' subcommand
  # Returns a string representation of the HOCON config after removing the
  # value at the given path
  def self.do_unset(opts, hocon_text)
    config_doc = Hocon::Parser::ConfigDocumentFactory.parse_string(hocon_text)
    unless config_doc.has_value?(opts[:path])
      raise MissingPathError.new
    end

    modified_config_doc = config_doc.remove_value(opts[:path])

    modified_config_doc.render
  end

  # If a file is provided, return it's contents. Otherwise read from STDIN
  def self.get_hocon_file(in_file)
    if in_file
      File.read(in_file)
    else
      STDIN.read
    end
  end

  # Print an error message and exit the program
  def self.exit_with_error(message)
    STDERR.puts "Error: #{message}"
    exit(1)
  end

  # Print an error message and usage, then exit the program
  def self.exit_with_usage_and_error(opt_parser, message)
    STDERR.puts opt_parser
    exit_with_error(message)
  end

  # Exits with an error saying there aren't enough arguments found for a given
  # subcommand. Prints the usage
  def self.subcommand_arguments_error(subcommand, opt_parser)
    error_message = "Too few arguments for '#{subcommand}' subcommand"
    exit_with_usage_and_error(opt_parser, error_message)
  end

  # Exits with an error for when no subcommand is supplied on the command line.
  # Prints the usage
  def self.no_subcommand_error(opt_parser)
    error_message = "Must specify subcommand from [#{SUBCOMMANDS.join(', ')}]"
    exit_with_usage_and_error(opt_parser, error_message)
  end

  # Exits with an error for when a subcommand doesn't exist. Prints the usage
  def self.invalid_subcommand_error(subcommand, opt_parser)
    error_message = "Invalid subcommand '#{subcommand}', must be one of [#{SUBCOMMANDS.join(', ')}]"
    exit_with_usage_and_error(opt_parser, error_message)
  end

  # If out_file is not nil, write to that file. Otherwise print to STDOUT
  def self.print_or_write(string, out_file)
    if out_file
      File.open(out_file, 'w') { |file| file.write(string) }
    else
      puts string
    end
  end
end


text:
package mainpackage;

import com.badlogic.gdx.Gdx;
import mainpackage.Screens.GameScreen;
import com.badlogic.gdx.graphics.Texture;

public class SpriteClass
{
	Game game;
	GameScreen gameScreen;
	private int frameIndexP1 = 0, frameIndexP2 = 0, frameIndexGUI = 0;
	private float frameLengthP1, frameLengthP2, frameLengthGUI, f;
	private float elapsedTime, elapsedTimeP2;
	private int numOfFramesP1, numOfRowsP1, numOfFramesP2, numOfRowsP2, numOfFramesGUI, numOfRowsGUI;
	private Texture curAnimationP1, curAnimationP2, curAnimationGUI;
	//loads the textures for any GUI element sprite-sheets
	private Texture selectorTex = new Texture(Gdx.files.internal("assets/gui/selectorTex.png"));
	//loads idle textures for Ichigo
	private Texture ichigoIdleRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Standing_Right.png"));
	private Texture ichigoIdleLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Standing_Left.png"));
	//loads the running textures for Ichigo
	private Texture ichigoRunRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Running_Right.png"));
	private Texture ichigoRunLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Running_Left.png"));
	//loads the first attack textures for Ichigo
	private Texture ichigoAttackRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Attack_01_Right.png"));
	private Texture ichigoAttackLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Attack_01_Left.png"));
	//loads the ducking textures for Ichigo
	private Texture ichigoDuckRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Ducking_Right.png"));
	private Texture ichigoDuckLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Ducking_Left.png"));
	//loads the blocking textures for Ichigo
	private Texture ichigoBlockRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Blocking_Right.png"));
	private Texture ichigoBlockLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Blocking_Left.png"));
	//loads the ducking block textures for Ichigo
	private Texture ichigoDuckingBlockRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_DuckingBlock_Right.png"));
	private Texture ichigoDuckingBlockLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_DuckingBlock_Left.png"));
	//loads the ducking attack textures for Ichigo
	private Texture ichigoDuckingAttackRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_DuckingAttack_Right.png"));
	private Texture ichigoDuckingAttackLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_DuckingAttack_Left.png"));
	//loads the jumping textures for Ichigo
	private Texture ichigoJumpingRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Jumping_Right.png"));
	private Texture ichigoJumpingLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Jumping_Left.png"));
	//loads the jumping attack textures for Ichigo
	private Texture ichigoJumpingAttackRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_JumpingAttack_Right.png"));
	private Texture ichigoJumpingAttackLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_JumpingAttack_Left.png"));
	//loads the hurting textures for Ichigo
	private Texture ichigoHurtingRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Hurting_Right.png"));
	private Texture ichigoHurtingLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Ichigo/Ichigo_Hurting_Left.png"));

	//loads idle textures for Byakuya
	private Texture byakuyaIdleRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Standing_Right.png"));
	private Texture byakuyaIdleLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Standing_Left.png"));
	//loads the running textures for Byakuya
	private Texture byakuyaRunRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Running_Right.png"));
	private Texture byakuyaRunLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Running_Left.png"));
	//loads the first attack textures for Byakuya
	private Texture byakuyaAttackRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Attack_01_Right.png"));
	private Texture byakuyaAttackLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Attack_01_Left.png"));
	//loads the hurting textures for Byakuya
	private Texture byakuyaHurtingRTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Hurting_Right.png"));
	private Texture byakuyaHurtingLTex = new Texture(Gdx.files.internal("assets/sprites/spritesheets/Byakuya/Byakuya_Hurting_Left.png"));

	public SpriteClass()
	{
	}

	public void setSheetValsGUI(int guiElement, int action)
	{
		switch(guiElement)
		{
		case 0:
			numOfFramesGUI = 6;
			numOfRowsGUI = 1;
			switch(action)
			{
			case 0:
				f = 1.0f;
				curAnimationGUI = selectorTex;
				break;
			}
			break;
		}
	}

	public void setSheetValsP1(int character, int action)
	{
		//checks which character is selected
		switch(character)
		{
		//if the character is Ichigo, sets the # of frames and rows accordingly
		case 0:
			numOfFramesP1 = 6;
			numOfRowsP1 = 1;
			//checks what is Ichigo's current action
			switch(action)
			{
			case 0:
				//f represents the total time for all frames to run through once in a given animation
				f = 1.20f;
				//loads texture corresponding to current action
				curAnimationP1 = ichigoIdleRTex;
				break;
			case 1:
				f = 1.20f;
				curAnimationP1 = ichigoIdleLTex;
				break;
			case 2:
				f = 1.20f;
				curAnimationP1 = ichigoRunRTex;
				break;
			case 3:
				f = 1.20f;
				curAnimationP1 = ichigoRunLTex;
				break;
			case 4:
				f = 0.80f;
				curAnimationP1 = ichigoAttackRTex;
				break;
			case 5:
				f = 0.80f;
				curAnimationP1 = ichigoAttackLTex;
				break;
			case 6:
				f = 1.20f;
				curAnimationP1 = ichigoDuckRTex;
				break;
			case 7:
				f = 1.20f;
				curAnimationP1 = ichigoDuckLTex;
				break;
			case 8:
				f = 1.20f;
				curAnimationP1 = ichigoBlockRTex;
				break;
			case 9:
				f = 1.20f;
				curAnimationP1 = ichigoBlockLTex;
				break;
			case 10:
				f = 1.20f;
				curAnimationP1 = ichigoDuckingBlockRTex;
				break;
			case 11:
				f = 1.20f;
				curAnimationP1 = ichigoDuckingBlockLTex;
				break;
			case 12:
				f = 0.80f;
				curAnimationP1 = ichigoDuckingAttackRTex;
				break;
			case 13:
				f = 0.80f;
				curAnimationP1 = ichigoDuckingAttackLTex;
				break;
			case 14:
				f = 1.20f;
				curAnimationP1 = ichigoJumpingRTex;
				break;
			case 15:
				f = 1.20f;
				curAnimationP1 = ichigoJumpingLTex;
				break;
			case 16:
				f = 0.80f;
				curAnimationP1 = ichigoJumpingAttackRTex;
				break;
			case 17:
				f = 0.80f;
				curAnimationP1 = ichigoJumpingAttackLTex;
				break;
			case 18:
				f = 0.80f;
				curAnimationP1 = ichigoHurtingRTex;
				break;
			case 19:
				f = 0.80f;
				curAnimationP1 = ichigoHurtingLTex;
				break;
			}
			break;
		case 1:
			//if the character is Byakuya, sets the # of frames and rows accordingly
			numOfFramesP1 = 4;
			numOfRowsP1 = 1;
			//checks what is Byakuya's current action
			switch(action)
			{
			case 0:
				//f represents the total time for all frames to run through once in a given animation
				f = 0.4f;
				//loads texture corresponding to current action
				curAnimationP1 = byakuyaIdleRTex;
				break;
			case 1:
				f = 0.4f;
				curAnimationP1 = byakuyaIdleLTex;
				break;
			case 2:
				f = 0.4f;
				curAnimationP1 = byakuyaRunRTex;
				break;
			case 3:
				f = 0.4f;
				curAnimationP1 = byakuyaRunLTex;
				break;
			case 4:
				f = 0.80f;
				curAnimationP1 = byakuyaAttackRTex;
				break;
			case 5:
				f = 0.80f;
				curAnimationP1 = byakuyaAttackLTex;
				break;
			case 6:
				f = 0.80f;
				curAnimationP1 = byakuyaHurtingRTex;
				break;
			case 7:
				f = 0.80f;
				curAnimationP1 = byakuyaHurtingLTex;
				break;
			}
			break;
		}
	}

	public void setSheetValsP2(int character, int action)
	{
		//checks which character is selected
		switch(character)
		{
		//if the character is Ichigo, sets the # of frames and rows accordingly
		case 0:
			numOfFramesP2 = 6;
			numOfRowsP2 = 1;
			//checks what is Ichigo's current action
			switch(action)
			{
			case 0:
				//f represents the total time for all frames to run through once in a given animation
				f = 0.4f;
				//loads texture corresponding to current action
				curAnimationP2 = ichigoIdleRTex;
				break;
			case 1:
				f = 0.4f;
				curAnimationP2 = ichigoIdleLTex;
				break;
			case 2:
				f = 0.4f;
				curAnimationP2 = ichigoRunRTex;
				break;
			case 3:
				f = 0.4f;
				curAnimationP2 = ichigoRunLTex;
				break;
			case 4:
				f = 0.80f;
				curAnimationP2 = ichigoAttackRTex;
				break;
			case 5:
				f = 0.80f;
				curAnimationP2 = ichigoAttackLTex;
				break;
			case 6:
				f = 0.4f;
				curAnimationP2 = ichigoDuckRTex;
				break;
			case 7:
				f = 0.4f;
				curAnimationP2 = ichigoDuckLTex;
				break;
			case 8:
				f = 0.4f;
				curAnimationP2 = ichigoBlockRTex;
				break;
			case 9:
				f = 0.4f;
				curAnimationP2 = ichigoBlockLTex;
				break;
			case 10:
				f = 0.4f;
				curAnimationP2 = ichigoDuckingBlockRTex;
				break;
			case 11:
				f = 0.4f;
				curAnimationP2 = ichigoDuckingBlockLTex;
				break;
			case 12:
				f = 0.80f;
				curAnimationP2 = ichigoDuckingAttackRTex;
				break;
			case 13:
				f = 0.80f;
				curAnimationP2 = ichigoDuckingAttackLTex;
				break;
			case 14:
				f = 0.80f;
				curAnimationP2 = ichigoJumpingRTex;
				break;
			case 15:
				f = 0.80f;
				curAnimationP2 = ichigoJumpingLTex;
				break;
			case 16:
				f = 0.40f;
				curAnimationP2 = ichigoJumpingAttackRTex;
				break;
			case 17:
				f = 0.40f;
				curAnimationP2 = ichigoJumpingAttackLTex;
				break;
			case 18:
				f = 0.80f;
				curAnimationP2 = ichigoHurtingRTex;
				break;
			case 19:
				f = 0.80f;
				curAnimationP2 = ichigoHurtingLTex;
				break;
			}
			break;
		case 1:
			//if the character is Byakuya, sets the # of frames and rows accordingly
			numOfFramesP2 = 4;
			numOfRowsP2 = 1;
			//checks what is Byakuya's current action
			switch(action)
			{
			case 0:
				//f represents the total time for all frames to run through once in a given animation
				f = 0.4f;
				//loads texture corresponding to current action
				curAnimationP2 = byakuyaIdleRTex;
				break;
			case 1:
				f = 0.4f;
				curAnimationP2 = byakuyaIdleLTex;
				break;
			case 2:
				f =0.4f;
				curAnimationP2 = byakuyaRunRTex;
				break;
			case 3:
				f = 0.4f;
				curAnimationP2 = byakuyaRunLTex;
				break;
			case 4:
				f = 0.4f;
				curAnimationP2 = byakuyaAttackRTex;
				break;
			case 5:
				f = 0.4f;
				curAnimationP2 = byakuyaAttackLTex;
				break;
			case 6:
				f = 0.80f;
				curAnimationP2 = byakuyaHurtingRTex;
				break;
			case 7:
				f = 0.80f;
				curAnimationP2 = byakuyaHurtingLTex;
				break;
			}
			break;
		}
	}

	//called to send which gui element texture to draw
	public Texture setAnimationGUI()
	{
		return curAnimationGUI;
	}

	//called in GameScreen class to tell it which texture to draw for P1
	public Texture setAnimationP1()
	{
		return curAnimationP1;
	}

	//called in GameScreen class to tell it which texture to draw for P2
	public Texture setAnimationP2()
	{
		return curAnimationP2;
	}

	//called to reset the frameIndex to 0 for player 1
	public void resetFrameIndexP1()
	{
		frameIndexP1 = 0;
	}

	//called to reset the frameIndex to 0 for player 2
	public void resetFrameIndexP2()
	{
		frameIndexP2 = 0;
	}

	//called to acquire the # of frames in a single row for player 1
	public int getNumOfFramesP1()
	{
		return numOfFramesP1;
	}

	//called to acquire the # of frames in a single row for player 2
	public int getNumOfFramesP2()
	{
		return numOfFramesP2;
	}

	//called to acquire the # of frames in a single row for a gui element
	public int getNumOfFramesGUI()
	{
		return numOfFramesGUI;
	}

	//called the get the current frame # for the gui element
	public int getFrameIndexGUI()
	{
		//sets frame length based on total number of frames in current action sprite-sheet
		frameLengthGUI = f / (numOfFramesGUI * numOfRowsGUI);

		//updates how much time has passed
		elapsedTime += Gdx.graphics.getDeltaTime();
		//checks if the amount of time passed has gone over the time length of a single frame
		if(elapsedTime > frameLengthGUI)
		{
			//goes to next frame
			frameIndexGUI++;
			//resets elapsedTime so that it is once again less than the time length of a single frame
			elapsedTime = 0;
			//checks if the frame index has reached last frame
			if(frameIndexGUI > numOfFramesGUI - 1)
			{
				//resets to first frame
				frameIndexGUI = 0;
			}
		}
		return frameIndexGUI;
	}

	//called the get the current frame # for player 1
	public int getFrameIndexP1()
	{
		//sets frame length based on total number of frames in current action sprite-sheet
		frameLengthP1 = f / (numOfFramesP1 * numOfRowsP1);

		//updates how much time has passed
		elapsedTime += Gdx.graphics.getDeltaTime();
		//checks if the amount of time passed has gone over the time length of a single frame
		if(elapsedTime > frameLengthP1)
		{
			if(!Player.getPausedState())
			{
				//goes to next frame
				frameIndexP1++;
			}
			//resets elapsedTime so that it is once again less than the time length of a single frame
			elapsedTime = 0;
			//checks if the frame index has reached last frame
			if(frameIndexP1 > numOfFramesP1 - 1)
			{
				//resets to first frame
				frameIndexP1 = 0;
			}
		}
		return frameIndexP1;
	}

	//called the get the current frame # for player 2
	public int getFrameIndexP2()
	{
		//sets frame length based on total number of frames in current action sprite-sheet
		frameLengthP2 = f / (numOfFramesP2 * numOfRowsP2);

		//updates how much time has passed
		elapsedTimeP2 += Gdx.graphics.getDeltaTime();
		//checks if the amount of time passed has gone over the time length of a single frame
		if(elapsedTimeP2 > frameLengthP2)
		{
			if(!Player.getPausedState())
			{
				//goes to next frame
				frameIndexP2++;
			}
			//resets elapsedTime so that it is once again less than the time length of a single frame
				elapsedTimeP2 = 0;
			//checks if the frame index has reached last frame
			if(frameIndexP2 > numOfFramesP2 - 1)
			{
				//resets to first frame
				frameIndexP2 = 0;
			}
		}
		return frameIndexP2;
	}
}