text:
package ow.routing.impl;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;

import ow.id.ID;
import ow.id.IDAddressPair;
import ow.messaging.Message;
import ow.messaging.MessageHandler;
import ow.messaging.MessagingAddress;
import ow.messaging.MessagingConfiguration;
import ow.messaging.MessagingProvider;
import ow.routing.RoutingAlgorithmConfiguration;
import ow.routing.RoutingAlgorithmProvider;
import ow.routing.RoutingContext;
import ow.routing.RoutingException;
import ow.routing.RoutingHop;
import ow.routing.RoutingResult;
import ow.routing.RoutingServiceConfiguration;
import ow.routing.impl.message.AbstractIteRouteMessage;
import ow.routing.impl.message.IteReplyMessage;
import ow.routing.impl.message.IteRouteInvokeMessage;
import ow.routing.impl.message.IteRouteJoinMessage;
import ow.routing.impl.message.IteRouteNoneMessage;
import ow.stat.MessagingReporter;
import ow.util.concurrent.ExecutorBlockingMode;
import ow.util.concurrent.SingletonThreadPoolExecutors;

/**
 * A routing driver which performs iterative forwarding/routing/lookup.
 *
 * @see ow.routing.RoutingServiceProvider#getService(RoutingServiceConfiguration, MessagingProvider, ID, int, long)
 * @see ow.routing.impl.RecursiveRoutingDriver
 */
public final class IterativeRoutingDriver extends AbstractRoutingDriver {
	protected IterativeRoutingDriver(RoutingServiceConfiguration conf,
			MessagingProvider msgProvider, MessagingConfiguration msgConfig, int port, int portRange,
			RoutingAlgorithmProvider algoProvider, RoutingAlgorithmConfiguration algoConfig,
			ID selfID)
				throws IOException {
		super(conf, msgProvider, msgConfig, port, portRange, algoProvider, algoConfig, selfID);

		// register message handlers
		prepareHandlers();
	}

	public RoutingResult[] route(ID[] targets, int numResponsibleNodeCands) {
		return route(targets, null, numResponsibleNodeCands);
	}

	public RoutingResult[] route(ID[] targets, RoutingContext[] initialRoutingContexts, int numResponsibleNodeCands) {
		return route0(IteRouteNoneMessage.class,
				targets, initialRoutingContexts, numResponsibleNodeCands,
				null, -1, null, null);
	}

	public RoutingResult[] invokeCallbacksOnRoute(ID[] target, int numResponsibleNodeCands,
			Serializable[][] returnedValue,
			int tag, Serializable[][] args) {
		return route0(IteRouteInvokeMessage.class,
				target, null, numResponsibleNodeCands,
				returnedValue, tag, args, null);
	}

	public RoutingResult join(MessagingAddress initialContact)
			throws RoutingException{
		ID[] target = { this.getSelfIDAddressPair().getID() };

		RoutingResult[] res = route0(IteRouteJoinMessage.class,
				target, null, this.config.getNumOfResponsibleNodeCandidatesRequestedWhenJoining(),
				null, -1, null, initialContact);

		if (res == null || res[0] == null)
			throw new RoutingException();

		algorithm.join(res[0].getResponsibleNodeCandidates());
			// the algorithm instance performs the joining process

		return res[0];
	}

	private RoutingResult[] route0(
			Class<? extends Message> msgClass,
			ID[] target, RoutingContext[] routingContexts, int numResponsibleNodeCands,
			Serializable[][] resultingCallbackResult,
			int callbackTag, Serializable[][] callbackArgs, MessagingAddress joinInitialContact) {
//System.out.print("route:");
//System.out.println("  msg: " + Tag.getNameByNumber(msgType.getNumber()));
//for (ID t: target) System.out.print(" " + t.toString().substring(0, 4) + "..");
//System.out.println();
//System.out.flush();
		if (numResponsibleNodeCands < 1) numResponsibleNodeCands = 1;

		if (routingContexts == null) routingContexts = new RoutingContext[target.length];
		if (!msgClass.equals(IteRouteJoinMessage.class)) {
			for (int i = 0; i < target.length; i++) {
				if (routingContexts[i] == null)
					routingContexts[i] = algorithm.initialRoutingContext(target[i]);
			}
		}

		// calculate query concurrency
//		int queryConcurrency = this.config.getQueryConcurrency();
//		if ((!this.queryToAllContacts)
//				|| (msgType == Tag.ITE_ROUTE_JOIN)
//				|| (queryConcurrency <= 0)) {
//			queryConcurrency = 1;
//		}

		// initialize route
		List<RoutingHop>[] route = new List/*<RoutingHop>*/[target.length];
		for (int i = 0; i < target.length; i++) {
			route[i] = new ArrayList<RoutingHop>();
//			if (queryConcurrency > 2) {
//				route[i] = Collections.synchronizedList(route[i]);
//			}

			route[i].add(RoutingHop.newInstance(getSelfIDAddressPair()));
		}
		Set<MessagingAddress> blackList =
			Collections.synchronizedSet(new HashSet<MessagingAddress>());

		// notify messaging visualizer
		if (!msgClass.equals(IteRouteJoinMessage.class)) {
			MessagingReporter msgReporter = receiver.getMessagingReporter();

			msgReporter.notifyStatCollectorOfEmphasizeNode(getSelfIDAddressPair().getID());
			msgReporter.notifyStatCollectorOfMarkedID(target, 0);
		}

		// initialize contact list
		ContactList[] contactList = new ContactList[target.length];
		for (int i = 0; i < target.length; i++) {
			contactList[i] = (this.queryToAllContacts ?
				new SortedContactList(target[i], algorithm, config.getNumOfNodesMaintained()) :
				new InsertedOrderContactList());
		}

		// initial set of nodes
		if (msgClass.equals(IteRouteJoinMessage.class)) {
			contactList[0].add(IDAddressPair.getIDAddressPair(
								getSelfIDAddressPair().getID(), // temporary, cannot be null
								joinInitialContact));
		}
		else {
			for (int i = 0; i < target.length; i++) {
				IDAddressPair[] nextHopCands =
					algorithm.nextHopCandidates(target[i], null, false, config.getNumOfNextHopCandidatesRequested(), routingContexts[i]);
						// updates routingContexts[i]

				for (IDAddressPair elem: nextHopCands) {
					if (elem == null) continue;

					contactList[i].add(elem);
				}
			}
		}

		// refine contact list iteratively

		// query
		RoutingResultTable<IDAddressPair[]> responsibleNodeCandsTable =
			new RoutingResultTable<IDAddressPair[]>();
		RoutingResultTable<Serializable> callbackResultTable = null;
		if (msgClass.equals(IteRouteInvokeMessage.class))
			callbackResultTable = new RoutingResultTable<Serializable>();

//		if (queryConcurrency <= 1) {
		if (true) {
			// serial query
			Querier querier = new Querier(msgClass,
					target, routingContexts, numResponsibleNodeCands,
					config.getTTL(), route,
					contactList, null, blackList, joinInitialContact,
					callbackTag,
					callbackArgs, responsibleNodeCandsTable,
					callbackResultTable);

			Future<Boolean> f = null;
			Thread t = null;
			boolean timeout = false;

			try {
				// invoke a Thread to timeout
				if (config.getUseThreadPool()) {
					ExecutorService ex = SingletonThreadPoolExecutors.getThreadPool(
							ExecutorBlockingMode.CONCURRENT_NON_BLOCKING, Thread.currentThread().isDaemon());
					f = ex.submit((Callable<Boolean>)querier);

					f.get(config.getRoutingTimeout(), TimeUnit.MILLISECONDS);
				}
				else {
					t = new Thread(querier);
					t.setName("Querier");
					t.setDaemon(Thread.currentThread().isDaemon());
					t.start();

					t.join(config.getRoutingTimeout());	// does not throw TimeoutException

					if (t.isAlive()) {
						// timed out
						timeout = true;
					}
				}
			}
			catch (ExecutionException e) {
				Throwable cause = e.getCause();
				logger.log(Level.WARNING, "A Querier threw an Exception.", (cause != null ? cause : e));
			}
			catch (InterruptedException e) {
				logger.log(Level.WARNING, "Querier#call() interrupted on " + getSelfIDAddressPair().getAddress());
			}
			catch (TimeoutException e) {	// timed out
				logger.log(Level.WARNING, "Routing timeout on " + getSelfIDAddressPair().getAddress());
				timeout = true;
			}
			catch (OutOfMemoryError e) {
				logger.log(Level.SEVERE, "# of threads: " + Thread.activeCount(), e);
				throw e;
			}

			if (timeout) {
				// interrupt a Querier
				if (f != null)
					f.cancel(true);
				else if (t != null)
					t.interrupt();

				responsibleNodeCandsTable.clear();
			}

			for (int i = 0; i < target.length; i++) {
				IDAddressPair contact = contactList[i].first();

				if (msgClass.equals(IteRouteJoinMessage.class)) {
					while (contact != null && getSelfIDAddressPair().equals(contact)) {
						// joining and destination is this node itself
						// it happens in case that this.queryToAllContacts is true.
						contactList[i].remove(contact);
						contact = contactList[i].first();
					}
				}
			}
		}
// concurrent queries disabled to implement collective routing (April 17, 2008)
//		else {
//			// concurrent queries
//			...
//		}	// if (queryConcurrency <= 1)

		// return
		RoutingResult[] ret = new RoutingResult[target.length];
		for (int i = 0; i < target.length; i++) {
			IDAddressPair goal;
			if (this.queryToAllContacts)
				goal = contactList[i].first();	// required for Kademlia
			else
				goal = route[i].get(route[i].size() - 1).getIDAddressPair();

			// message dependent processes
			boolean isFinalNode = getSelfIDAddressPair().equals(goal);

			if (msgClass.equals(IteRouteInvokeMessage.class)) {
				Serializable res =
					invokeCallbacks(target[i], callbackTag, callbackArgs[i], null, isFinalNode);

				callbackResultTable.put(target[i], getSelfIDAddressPair(), res);
			}
			else if (msgClass.equals(IteRouteJoinMessage.class)) {
				algorithm.join(this.getSelfIDAddressPair(), null, isFinalNode);
			}

			// prepare RoutingResult and callback results
			IDAddressPair[] respCands = responsibleNodeCandsTable.get(target[i], goal);
			if (respCands != null) {
				RoutingHop[] routeArray = new RoutingHop[route[i].size()];
				route[i].toArray(routeArray);

				ret[i] = new RoutingResult(routeArray, respCands);

				if (callbackResultTable != null
						&& resultingCallbackResult != null && resultingCallbackResult[i] != null) {
					resultingCallbackResult[i][0] = callbackResultTable.get(target[i], goal);
				}
			}
		}

		return ret;
	}

	private final class Querier implements Runnable, Callable<Boolean> {
		private final Class<? extends Message> msgClass;
		private ID[] target;
		private RoutingContext[] routingContexts;
		private final int numResponsibleNodeCands;

		private int ttl;

		private final List<RoutingHop>[] route;
		private ContactList[] contactList;
		private IDAddressPair[] lastContacts;
		private final Set<MessagingAddress> blackList;

		// for ITE_ROUTE_JOIN
		private final MessagingAddress joinInitialContact;

		// for ITE_ROUTE_INVOKE
		private final int callbackTag;
		private final Serializable[][] callbackArgs;

		// routing results tables
		private final RoutingResultTable<IDAddressPair[]> respCandsTable;
		private final RoutingResultTable<Serializable> callbackResultTable;

		Querier(Class<? extends Message> msgClass,
				ID[] target, RoutingContext[] routingContexts, int numResponsibleNodeCands,
				int ttl, List<RoutingHop>[] route,
				ContactList[] contactList, IDAddressPair[] lastContacts, Set<MessagingAddress> blackList, MessagingAddress joinInitialContact,
				int callbackTag,
				Serializable[][] callbackArgs, RoutingResultTable<IDAddressPair[]> responsibleNodeCandsTable,
				RoutingResultTable<Serializable> callbackResultTable) {
			this.msgClass = msgClass;
			this.target = target;
			this.routingContexts = routingContexts;
			this.numResponsibleNodeCands = numResponsibleNodeCands;

			this.ttl = ttl;

			this.route = route;
			this.contactList = contactList;
			this.lastContacts = lastContacts;
			this.blackList = blackList;

			this.joinInitialContact = joinInitialContact;

			this.callbackTag = callbackTag;
			this.callbackArgs = callbackArgs;

			this.respCandsTable = responsibleNodeCandsTable;
			this.callbackResultTable = callbackResultTable;
		}

		public void run() {
			try {
				this.call();
			}
			catch (Exception e) {
				logger.log(Level.SEVERE, "A Querier threw an exception.", e);
			}
		}

		public Boolean call() {
//System.out.println("Querier#call on " + getSelfIDAddressPair().getAddress());
			boolean succeed = true;

			IDAddressPair[] contacts = new IDAddressPair[this.target.length];
			IDAddressPair[] lastContacts = this.lastContacts;
			RoutingContext[] lastRoutingContexts = new RoutingContext[this.target.length];
			int ttl = this.ttl;

			if (lastContacts == null) lastContacts = new IDAddressPair[this.target.length];

			// iterative routing
			iterativeRouting:
			while (true) {
				IDAddressPair[][] nextHopCands = null;

				// TTL check
				if (ttl <= 0) {
					StringBuilder sb = new StringBuilder();
					sb.append("TTL expired (target");
					for (ID t: this.target) { sb.append(" ").append(t.toString(-1)); }
					sb.append("):");
					for (RoutingHop n: this.route[0]) {
						sb.append(" ");
						sb.append(n.getIDAddressPair().toString(-1));
					}

					logger.log(Level.WARNING, sb.toString(), new Throwable());

					if (!this.msgClass.equals(IteRouteJoinMessage.class)) { // allow joining node to succeed
						succeed = false;

						for (int i = 0; i < target.length; i++) {
							this.respCandsTable.clear(target[i]);

							if (this.callbackResultTable != null)
								this.callbackResultTable.clear(target[i]);
						}
					}

					break iterativeRouting;
				}

				ttl--;

				// preserve last contacts and last routing contexts
				for (int i = 0; i < target.length; i++) {
					lastContacts[i] = contacts[i];
				}

				// query
				Message replyMsg = null;
				do {	// while (replyMsg == null)
					Set<IDAddressPair> contactSet = new HashSet<IDAddressPair>();
					boolean allContactsAreNull = true;
					boolean aContactIsNull = false;

					for (int i = 0; i < this.target.length; i++) {
						contacts[i] = (IterativeRoutingDriver.this.queryToAllContacts ?
								this.contactList[i].inspectExceptContactedNode() :
								this.contactList[i].inspect());

						if (contacts[i] != null) {
//StringBuilder sb = new StringBuilder();
//sb.append("judge to terminate[" + i + "]:\n");
//sb.append("  contacts:     " + (contacts[i] != null ? contacts[i].toString(-1) : "null") + "\n");
//sb.append("  lastContacts: " + (lastContacts[i] != null ? lastContacts[i].toString(-1) : "null") + "\n");
//sb.append("  context:      " + (this.routingContexts[i] != null ? this.routingContexts[i].toString(-1) : "null") + "\n");
//sb.append("  lastContext:  " + (lastRoutingContexts[i] != null ? lastRoutingContexts[i].toString(-1) : "null") + "\n");
							if (contacts[i].equals(lastContacts[i]) &&
									(this.routingContexts[i] == null ||
									 this.routingContexts[i].equals(lastRoutingContexts[i]))) {
//sb.append("    terminate.\n");
								contacts[i] = null;
							}
							else if (blackList.contains(contacts[i].getAddress())) {
								contactList[i].remove(contacts[i]);
								continue;
							}
//System.out.print(sb.toString());
						}

						if (contacts[i] != null) {
							contactSet.add(contacts[i]);
							allContactsAreNull = false;
						}
						else {
							contactSet.add(null);
							aContactIsNull = true;
						}

						// initialize lastContact
						if (lastContacts[i] == null) lastContacts[i] = getSelfIDAddressPair();
					}

					if (allContactsAreNull) break iterativeRouting;	// finish

					// fork
					if (contactSet.size() > 1 || aContactIsNull) {
						Map<IDAddressPair,Querier> forkedQueriers =
							new HashMap<IDAddressPair,Querier>();

						List<Integer> contactIndexList = new ArrayList<Integer>();

						for (IDAddressPair c: contactSet) {
							contactIndexList.clear();

							for (int i = 0; i < this.target.length; i++) {
								if (c == null) {
									if (contacts[i] == null) {
										contactIndexList.add(i);
									}
								}
								else if (c.equals(contacts[i])) {
									contactIndexList.add(i);
								}
							}

							int nTgts = contactIndexList.size();
							ID[] forkedTarget = new ID[nTgts];
							RoutingContext[] forkedRoutingContext = new RoutingContext[nTgts];
							List<RoutingHop>[] forkedRoute = new List/*<RoutingHop>*/[nTgts];
							ContactList[] forkedContactList = new ContactList[nTgts];
							IDAddressPair[] forkedLastContact = new IDAddressPair[nTgts];
							for (int i = 0; i < nTgts; i++) {
								int index = contactIndexList.get(i);
								forkedTarget[i] = this.target[index];
								if (this.routingContexts[index] != null)
									forkedRoutingContext[i] = this.routingContexts[index].clone();
								forkedRoute[i] = this.route[index];
								forkedContactList[i] = this.contactList[index];
								forkedLastContact[i] = lastContacts[index];
							}
							Serializable[][] forkedCallbackArgs = null;
							if (callbackArgs != null) {
								forkedCallbackArgs = new Serializable[nTgts][];
								for (int i = 0; i < nTgts; i++) {
									int index = contactIndexList.get(i);
									forkedCallbackArgs[i] = callbackArgs[index];
								}
							}

							Querier q = new Querier(this.msgClass,
									forkedTarget, forkedRoutingContext, this.numResponsibleNodeCands,
									this.ttl, forkedRoute,
									forkedContactList, forkedLastContact, this.blackList, this.joinInitialContact,
									this.callbackTag,
									forkedCallbackArgs, this.respCandsTable,
									this.callbackResultTable);
							forkedQueriers.put(c, q);
						}

						// execute
						boolean querierResult = true;
						Set<Future<Boolean>> fSet = null;
						Set<Thread> tSet = null;

						try {
							if (config.getUseThreadPool()) {
								fSet = new HashSet<Future<Boolean>>();
								Querier firstQuerier = null;

								ExecutorService ex = SingletonThreadPoolExecutors.getThreadPool(
										ExecutorBlockingMode.CONCURRENT_REJECTING, Thread.currentThread().isDaemon());

								for (Querier q: forkedQueriers.values()) {
									if (firstQuerier == null) { firstQuerier = q; continue; }

									try {
										Future<Boolean> f = ex.submit((Callable<Boolean>)q);
										fSet.add(f);
									}
									catch (RejectedExecutionException e) {
										// invoke directly if rejected
										// Note that this is required to avoid deadlocks
										querierResult &= firstQuerier.call();
									}
								}

								querierResult &= firstQuerier.call();	// direct invocation (an optimization)

								for (Future<Boolean> f: fSet) {
									querierResult &= f.get();
								}
								// Note that this Querier can be blocked here
								// in case that the number of threads is limited.
								// Above ...submit()s consume a thread and this Querier own also keeps a thread.
								// If threads runs out, a submitted Querier cannot run and f.get() is blocked.
							}
							else {
								tSet = new HashSet<Thread>();
								Querier firstQuerier = null;

								for (Querier q: forkedQueriers.values()) {
									if (firstQuerier == null) { firstQuerier = q; continue; }

									Thread t = new Thread(q);
									t.setName("Querier");
									t.setDaemon(Thread.currentThread().isDaemon());
									tSet.add(t);
									t.start();
								}

								firstQuerier.call();	// direct invocation (an optimization)

								for (Thread t: tSet) t.join();
							}
						}
						catch (ExecutionException e) {
							Throwable cause = e.getCause();
							logger.log(Level.WARNING, "A Querier threw an Exception.", (cause != null ? cause : e));
							querierResult = false;
						}
						catch (InterruptedException e) {
							logger.log(Level.WARNING, "Querier#call() interrupted on " + getSelfIDAddressPair().getAddress());
							querierResult = false;

							// interrupt sub Queriers
							if (fSet != null)
								for (Future<Boolean> f: fSet) f.cancel(true);
							else if (tSet != null)
								for (Thread t: tSet) t.interrupt();
						}
						catch (OutOfMemoryError e) {
							logger.log(Level.SEVERE, "# of threads: " + Thread.activeCount(), e);
							throw e;
						}

						return querierResult;
					}	// if (contactSet.size() > 1)	// fork

					// preserve last routing contexts
					for (int i = 0; i < target.length; i++) {
						if (this.routingContexts[i] != null)
							lastRoutingContexts[i] = this.routingContexts[i].clone();
						else
							lastRoutingContexts[i] = null;
					}

					// update contact
					for (int i = 0; i < this.target.length; i++) {
						contacts[i] = (IterativeRoutingDriver.this.queryToAllContacts ?
								this.contactList[i].firstExceptContactedNode() :
								this.contactList[i].first());
					}

					// in case of join,
					// skip the next hop if it is the destination (this node itself)
					if (this.msgClass.equals(IteRouteJoinMessage.class)
							&& getSelfIDAddressPair().getAddress().equals(contacts[0].getAddress())) {
						// remove
						contactList[0].remove(contacts[0]);

						// update next contact
						contacts[0] = (IterativeRoutingDriver.this.queryToAllContacts ?
								this.contactList[0].inspectExceptContactedNode() :
								this.contactList[0].inspect());

						if (contacts[0].equals(lastContacts[0]) &&
								(this.routingContexts[0] == null ||
								 this.routingContexts[0].equals(lastRoutingContexts[0])))
							contacts[0] = null;

						if (contacts[0] == null)
							break iterativeRouting;

						continue;
					}

					// send a query and receive a reply
					Message requestMsg = null;
					if (this.msgClass.equals(IteRouteNoneMessage.class)) {
						requestMsg = new IteRouteNoneMessage(
								this.target, this.routingContexts, lastContacts, config.getNumOfNextHopCandidatesRequested(), numResponsibleNodeCands);
					}
					else if (this.msgClass.equals(IteRouteInvokeMessage.class)) {
						requestMsg = new IteRouteInvokeMessage(
								this.target, this.routingContexts, lastContacts, config.getNumOfNextHopCandidatesRequested(), numResponsibleNodeCands,
								this.callbackTag, this.callbackArgs);
					}
					else {	// ITE_ROUTE_JOIN
						requestMsg = new IteRouteJoinMessage(
								this.target, this.routingContexts, lastContacts, config.getNumOfNextHopCandidatesRequested(), numResponsibleNodeCands);
					}

					replyMsg = null;
					try {
						replyMsg = sender.sendAndReceive(contacts[0].getAddress(), requestMsg);
										// throws IOException
					}
					catch (IOException e) {
						logger.log(Level.WARNING, "Sending or receiving failed: "
								+ contacts[0].getAddress()
								+ " on " + getSelfIDAddressPair().getAddress());
					}

					if (replyMsg != null) {
						// fill ID of contact
						for (int i = 0; i < target.length; i++){
							synchronized (contacts[i]) {
								if (getSelfIDAddressPair().getID().equals(contacts[i].getID()) &&
									!getSelfIDAddressPair().getAddress().equals(contacts[i].getAddress())) {
									// this is the case in the first iteration of joining
									contacts[i].setID(((IDAddressPair)replyMsg.getSource()).getID());

									contactList[i].addAsContacted(contacts[i]);
								}
							}
						}

						// notify the routing algorithm
						algorithm.touch((IDAddressPair)replyMsg.getSource());
							// should be lazy (delayed and/or unified)?

						if (!(replyMsg instanceof IteReplyMessage)) {
							logger.log(Level.SEVERE, "Received message is not ITE_REPLY: " + replyMsg.getName());

							replyMsg = null;
							break;
						}

						// parse the reply
						nextHopCands = ((IteReplyMessage)replyMsg).nextHopCandidates;
						IDAddressPair[][] respCands = ((IteReplyMessage)replyMsg).responsibleNodeCands;
						routingContexts = ((IteReplyMessage)replyMsg).routingContexts;
						Serializable[] callbackResult = ((IteReplyMessage)replyMsg).callbackResult;

						for (int i = 0; i < target.length; i++) {
							this.respCandsTable.put(target[i], (IDAddressPair)replyMsg.getSource(), respCands[i]);

							if (this.callbackResultTable != null)
								this.callbackResultTable.put(target[i], (IDAddressPair)replyMsg.getSource(), callbackResult[i]);
						}

						break;
					}
					else {
						// communication failure
						if (contacts[0].getID() != null) { // In an initial join iteration, ID is null.
							IterativeRoutingDriver.super.fail(contacts[0]);
								// tell the algorithm of a failure of the best node

							this.blackList.add(contacts[0].getAddress());
						}

						for (int i = 0; i < target.length; i++) {
							synchronized (this.contactList[i]) {
								this.contactList[i].remove(contacts[i]);
							}
						}
					}
				} while (replyMsg == null);	// query

				for (int i = 0; i < target.length; i++) {
					this.route[i].add(RoutingHop.newInstance(contacts[0]));
				}

				// add the nodes in the reply to contact list
				for (int i = 0; i < target.length; i++) {
					if (nextHopCands[i] != null) {
						synchronized (this.contactList[i]) {
							if (!IterativeRoutingDriver.this.queryToAllContacts) {
								// refresh contact list
								this.contactList[i].clear();
							}

							for (IDAddressPair p: nextHopCands[i]) {
								if (p == null || this.blackList.contains(p.getAddress())
									|| this.msgClass.equals(IteRouteJoinMessage.class) && getSelfIDAddressPair().equals(p)) continue;

								this.contactList[i].add(p);
							}
						}
					}
				}
			}	// iterativeRouting: while

			return succeed;
		}
	}

	private final static class RoutingResultTable<V> {
		private final class Entry {
			private final ID target; private final IDAddressPair node;
			Entry(ID target, IDAddressPair node) { this.target = target; this.node = node; }
			public int hashCode() { return this.target.hashCode() ^ this.node.hashCode(); }
			public boolean equals(Object o) {
				if (o == null || !(o instanceof RoutingResultTable<?>.Entry)) return false;
				Entry ent = (Entry)o;
				return this.target.equals(ent.target) && this.node.equals(ent.node);
			}
		}

		private Map<Entry,V> table = new HashMap<Entry,V>();

		public synchronized void put(ID target, IDAddressPair node, V v) {
			this.table.put(new Entry(target, node), v);
		}

		public synchronized V get(ID target, IDAddressPair node) {
			return this.table.get(new Entry(target, node));
		}

		public synchronized void clear(ID target) {
			Set<Entry> keySet = this.table.keySet();
			Entry[] keyArray = new RoutingResultTable/*<V>*/.Entry[keySet.size()];
			this.table.keySet().toArray(keyArray);

			for (Entry e: keyArray) {
				if (target.equals(e.target)) {
					this.table.remove(e);
				}
			}
		}

		public synchronized void clear() { this.table.clear(); }
	}

	/**
	 * Prepare message handlers for received messages.
	 */
	private void prepareHandlers() {
		MessageHandler handler;

		// ITE_ROUTE_{NONE,INVOKE,JOIN}
		handler = new MessageHandler() {
			public Message process(final Message msg) {
				// parse the Message
				final ID[] targets;
				RoutingContext[] routingContexts = null;
				IDAddressPair[] lastHops = null;
				int numNextHopCands = 1, numResponsibleNodeCands = 1;
				int tag = -1;
				Serializable[][] args = null;
				IDAddressPair joiningNode = (IDAddressPair)msg.getSource();

				targets = ((AbstractIteRouteMessage)msg).target;
				routingContexts = ((AbstractIteRouteMessage)msg).cxt;
				lastHops = ((AbstractIteRouteMessage)msg).lastHop;
				numNextHopCands = ((AbstractIteRouteMessage)msg).numNextHopCandidates;
				numResponsibleNodeCands = ((AbstractIteRouteMessage)msg).numRespNodeCands;
				if (msg instanceof IteRouteInvokeMessage) {
					tag = ((IteRouteInvokeMessage)msg).callbackTag;
					args = ((IteRouteInvokeMessage)msg).callbackArgs;
				}

				for (int i = 0; i < targets.length; i++) {
					if (routingContexts[i] == null)
						routingContexts[i] = algorithm.initialRoutingContext(targets[i]);
						// In case of joining, routing contexts are initialized here.
				}

				// routing
				boolean[] isFinalNode = new boolean[targets.length];

				IDAddressPair[][] nextHopCands = new IDAddressPair[targets.length][];

				boolean joining = (msg instanceof IteRouteJoinMessage);

				for (int i = 0; i < targets.length; i++) {
					RoutingContext lastContext = null;
					if (routingContexts[i] != null)
						lastContext = routingContexts[i].clone();	// preserve to compare later

					nextHopCands[i] = algorithm.nextHopCandidates(targets[i],
							(lastHops[i] != null ? lastHops[i].getID() : null),
							joining, numNextHopCands, routingContexts[i]);
						// updates routingContexts[i]

					isFinalNode[i] =
						(nextHopCands[i] == null ||
						 nextHopCands[i].length <= 0 ||
						 nextHopCands[i][0] == null ||
						 nextHopCands[i][0].equals(getSelfIDAddressPair())) &&
						(routingContexts[i] == null ||
						 routingContexts[i].equals(lastContext));
//System.out.println("isFinalNode: " + isFinalNode[i]);
//System.out.println("  self   : " + getSelfIDAddressPair());
//for (int j = 0; j < nextHopCands[i].length; j++) {
//	if (nextHopCands[i][j] != null)
//		System.out.println("  nextHop[" + j + "]: " + nextHopCands[i][i]);
//}
				}	// for (int i = 0; i < target.length; i++)

				// notify the routing algorithm
				// but, do not touch the message sender while it is joining
				if (IterativeRoutingDriver.this.insertJoiningNodeIntoRoutingTables || !joining) {
					algorithm.touch((IDAddressPair)msg.getSource());
				}
				if (lastHops != null) {
					for (IDAddressPair p: lastHops) {
						if (p == null || p.equals(getSelfIDAddressPair()) ||
							(!IterativeRoutingDriver.this.insertJoiningNodeIntoRoutingTables && joining && p.equals((IDAddressPair)msg.getSource()))) continue;
						algorithm.touch(p);
					}
				}

				// message type specific process
				Serializable[] callbackResult = new Serializable[targets.length];
				if (msg instanceof IteRouteInvokeMessage) {
					// invoke callbacks
					for (int i = 0; i < targets.length; i++) {
						callbackResult[i] = invokeCallbacks(targets[i], tag, args[i], lastHops[i], isFinalNode[i]);
						if (callbackResult[i] != null) {
							logger.log(Level.INFO, "A callback returned non-null object: " + callbackResult);
						}
					}
				}
				else if (msg instanceof IteRouteJoinMessage) {
					final IDAddressPair copiedJoiningNode = joiningNode;
					final IDAddressPair[] copiedLastHop = new IDAddressPair[lastHops.length];
					System.arraycopy(lastHops, 0, copiedLastHop, 0, lastHops.length);
					final boolean[] copiedIsFinalNode = isFinalNode;
					Runnable r = new Runnable() {
						public void run() {
							for (int i = 0; i < copiedLastHop.length; i++) {
								algorithm.join(copiedJoiningNode, copiedLastHop[i], copiedIsFinalNode[i]);
							}
						}
					};

					try {
						if (config.getUseThreadPool()) {
							ExecutorService ex = SingletonThreadPoolExecutors.getThreadPool(
									ExecutorBlockingMode.CONCURRENT_NON_BLOCKING, Thread.currentThread().isDaemon());
							ex.submit(r);
						}
						else {
							Thread t = new Thread(r);
							t.setName("Message type specific processes");
							t.setDaemon(Thread.currentThread().isDaemon());
							t.start();
						}
					}
					catch (OutOfMemoryError e) {
						logger.log(Level.SEVERE, "# of threads: " + Thread.activeCount(), e);

//						Thread[] tarray = new Thread[Thread.activeCount()];
//						Thread.enumerate(tarray);
//						for (Thread t: tarray) System.out.println("Th: " + t.getName());
//						System.out.flush();

						throw e;
					}
				}

				// get responsible node candidates
				IDAddressPair[][] responsibleNodeCands = new IDAddressPair[targets.length][];
				for (int i = 0; i < targets.length; i++)
					responsibleNodeCands[i] = algorithm.responsibleNodeCandidates(targets[i], numResponsibleNodeCands);

				return new IteReplyMessage(nextHopCands, responsibleNodeCands, routingContexts, callbackResult);
			}
		};
		addMessageHandler(IteRouteNoneMessage.class, handler);
		addMessageHandler(IteRouteInvokeMessage.class, handler);
		addMessageHandler(IteRouteJoinMessage.class, handler);
	}
}


text:
// Generated by CoffeeScript 1.9.3

(function() {
  cs.music_settings = (function() {
    var fn, i, len, option, public_settings, ref, settings;
    settings = localStorage.settings;
    settings = settings ? JSON.parse(settings) : {
      repeat: 'all',
      shuffle: false,
      equalizer_gain_levels: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      reverb_mode: '',
      low_performance: null
    };
    public_settings = {};
    ref = ['repeat', 'shuffle', 'equalizer_gain_levels', 'reverb_mode', 'low_performance'];
    fn = function(option) {
      return Object.defineProperty(public_settings, option, {
        get: function() {
          return settings[option];
        },
        set: function(value) {
          settings[option] = value;
          return localStorage.settings = JSON.stringify(settings);
        }
      });
    };
    for (i = 0, len = ref.length; i < len; i++) {
      option = ref[i];
      fn(option);
    }
    if (public_settings.low_performance === null) {
      document.webL10n.ready(function() {
        //public_settings.low_performance = confirm(_('low-performance-mode-details'));
        public_settings.low_performance = true;
		  var music_storag = navigator.getDeviceStorage('music');
		 var cursor = music_storag.enumerate();
		 confirm(_('low-performance-mode-details'));
        return location.reload();
      });
    }
    if (public_settings.low_performance) {
      $(function() {
        return $('body').addClass('low-performance');
      });
    }
    return public_settings;
  })();

}).call(this);

redpajama_set_name: RedPajamaGithub


text:
package com.hankcs.lucene;

import com.hankcs.hanlp.HanLP;
import junit.framework.TestCase;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

public class HanLPTokenizerTest extends TestCase
{
    Tokenizer tokenizer;

    @Override
    public void setUp() throws Exception
    {
        tokenizer = new HanLPTokenizer(HanLP.newSegment()
                                               .enableJapaneseNameRecognize(true)
                                               .enableIndexMode(true), null, false);
        tokenizer.setReader(new StringReader("林志玲亮相网友:确定不是波多野结衣?"));
        tokenizer.reset();
    }

    public void testIncrementToken() throws Exception
    {
        while (tokenizer.incrementToken())
        {
            CharTermAttribute attribute = tokenizer.getAttribute(CharTermAttribute.class);
            // 偏移量
            OffsetAttribute offsetAtt = tokenizer.getAttribute(OffsetAttribute.class);
            // 距离
            PositionIncrementAttribute positionAttr = tokenizer.getAttribute(PositionIncrementAttribute.class);
            // 词性
            TypeAttribute typeAttr = tokenizer.getAttribute(TypeAttribute.class);
            System.out.printf("[%d:%d %d] %s/%s\n", offsetAtt.startOffset(), offsetAtt.endOffset(), positionAttr.getPositionIncrement(), attribute, typeAttr.type());
        }
    }

    public void testMultiText() throws Exception
    {
        String[] sentences = new String[]{
                "中华人民共和国",
                "地大物博"
        };
        tokenizer = new HanLPTokenizer(HanLP.newSegment()
                                               .enableJapaneseNameRecognize(true)
                                               .enableIndexMode(true), null, false);
        for (String sentence : sentences)
        {
            tokenizer.setReader(new StringReader(sentence));
            tokenizer.reset();
            testIncrementToken();
            tokenizer.close();
        }
    }

    public void testPinyinTokenFilter() throws Exception
    {
        Map<String, String> args = new HashMap<>();
        args.put("original", "true");
        args.put("pinyin", "false");
        args.put("pinyinFirstChar", "true");
        HanLPPinyinTokenFilterFactory factory = new HanLPPinyinTokenFilterFactory(args);
        TokenStream tokenStream = factory.create(tokenizer);
        while (tokenStream.incrementToken())
        {
            CharTermAttribute attribute = tokenizer.getAttribute(CharTermAttribute.class);
            // 偏移量
            OffsetAttribute offsetAtt = tokenizer.getAttribute(OffsetAttribute.class);
            // 距离
            PositionIncrementAttribute positionAttr = tokenizer.getAttribute(PositionIncrementAttribute.class);
            // 词性
            TypeAttribute typeAttr = tokenizer.getAttribute(TypeAttribute.class);
            System.out.printf("[%d:%d %d] %s/%s\n", offsetAtt.startOffset(), offsetAtt.endOffset(), positionAttr.getPositionIncrement(), attribute, typeAttr.type());
        }
    }
}


text:
package org.bouncycastle.jsse;

import javax.net.ssl.SSLEngine;

/**
 * A BCJSSE-specific interface to expose extended functionality on {@link javax.net.ssl.SSLEngine}
 * implementations.
 */
public interface BCSSLEngine
{
    String getApplicationProtocol();

    BCApplicationProtocolSelector<SSLEngine> getBCHandshakeApplicationProtocolSelector();

    void setBCHandshakeApplicationProtocolSelector(BCApplicationProtocolSelector<SSLEngine> selector);

    void setBCSessionToResume(BCExtendedSSLSession session);

    BCExtendedSSLSession getBCHandshakeSession();

    BCExtendedSSLSession getBCSession();

    /**
     * Returns an accessor for extended SSL connection data. Unlike
     * {@link BCSSLSocket#getConnection} this method does not block until handshaking is complete.
     * Until the initial handshake has completed, this method returns null.
     *
     * @return A {@link BCSSLConnection} instance.
     */
    BCSSLConnection getConnection();

    String getHandshakeApplicationProtocol();

    /**
     * Returns a {@link BCSSLParameters} with properties reflecting the current configuration.
     * @return the current {@link BCSSLParameters parameters}
     */
    BCSSLParameters getParameters();

    /**
     * Sets parameters according to the properties in a {@link BCSSLParameters}.
     *

     * Note that any properties set to null will be ignored, which will leave the corresponding
     * settings unchanged.
     *

     *
     * @param parameters
     *            the {@link BCSSLParameters parameters} to set
     * @throws IllegalArgumentException
     *             if the cipherSuites or protocols properties contain unsupported values
     */
    void setParameters(BCSSLParameters parameters);
}


text:
/*
 * Purpose: Test we can cancel a query inside message handler
 * Some server some additional tokens which can prevent second query to work
 * correctly.
 */

#include "common.h"

static int
cancel_msg_handler(DBPROCESS * dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
{
	dbcancel(dbproc);
	return 0;
}

int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	DBINT testint = -1;

	read_login_info(argc, argv);

	printf("Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "cancel");

	printf("About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	/* first query, select with error  */
	dbmsghandle(cancel_msg_handler);
	sql_cmd(dbproc);
	dbsqlexec(dbproc);

	dbmsghandle(syb_msg_handler);

	/* second query, select */
	printf("second select\n");

	if (SUCCEED != sql_cmd(dbproc) || SUCCEED != dbsqlexec(dbproc)) {
		fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__);
		exit(1);
	}

	if (dbresults(dbproc) != SUCCEED) {
		fprintf(stderr, "Was expecting a result set.");
		exit(1);
	}

	for (i = 1; i <= dbnumcols(dbproc); i++)
		printf("col %d is %s\n", i, dbcolname(dbproc, i));

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);

	if (REG_ROW != dbnextrow(dbproc)) {
		fprintf(stderr, "Failed.  Expected a row\n");
		exit(1);
	}
	if (testint != 1) {
		fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
		exit(1);
	}
	if (dbnextrow(dbproc) != NO_MORE_ROWS) {
		fprintf(stderr, "No other rows expected\n");
	}

	dbexit();

	printf("ok\n");
	return 0;
}


text:
class Substitution(object):
    """A string substitution to be applied to the text and HTML contents of
    the body of your email, as well as in the Subject and Reply-To parameters.
    """

    def __init__(self, key=None, value=None):
        """Create a Substitution with the given key and value.

        :param key: Text to be replaced with "value" param
        :type key: string, optional
        :param value: Value to substitute into email
        :type value: string, optional
        """
        self.key = key
        self.value = value

    @property
    def key(self):
        return self._key

    @key.setter
    def key(self, value):
        self._key = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value

    def get(self):
        """
        Get a JSON-ready representation of this Substitution.

        :returns: This Substitution, ready for use in a request body.
        :rtype: dict
        """
        substitution = {}
        if self.key is not None and self.value is not None:
            substitution[self.key] = self.value
        return substitution


text:
var request = require('request');

describe('server', () => {
  it('requires a master key and app id', done => {
    expect(setServerConfiguration.bind(undefined, {  })).toThrow('You must provide an appId!');
    expect(setServerConfiguration.bind(undefined, { appId: 'myId' })).toThrow('You must provide a masterKey!');
    expect(setServerConfiguration.bind(undefined, { appId: 'myId', masterKey: 'mk' })).toThrow('You must provide a serverURL!');
    done();
  });

  it('fails if database is unreachable', done => {
    setServerConfiguration({
      databaseURI: 'mongodb://fake:fake@ds043605.mongolab.com:43605/drew3',
      serverURL: 'http://localhost:8378/1',
      appId: 'test',
      javascriptKey: 'test',
      dotNetKey: 'windows',
      clientKey: 'client',
      restAPIKey: 'rest',
      masterKey: 'test',
      collectionPrefix: 'test_',
      fileKey: 'test',
    });
    //Need to use rest api because saving via JS SDK results in fail() not getting called
    request.post({
      url: 'http://localhost:8378/1/classes/NewClass',
      headers: {
        'X-Parse-Application-Id': 'test',
        'X-Parse-REST-API-Key': 'rest',
      },
      body: {},
      json: true,
    }, (error, response, body) => {
      expect(response.statusCode).toEqual(500);
      expect(body.code).toEqual(1);
      expect(body.message).toEqual('Internal server error.');
      done();
    });
  });
});


text:
package joshie.harvest.mining.render;

public class SpecialRendererElevator {
}


text:
package com.strobel.assembler.metadata.signatures;

public final class LongSignature implements BaseType {
    private static final LongSignature _singleton = new LongSignature();

    private LongSignature() {
    }

    public static LongSignature make() {
        return _singleton;
    }

    public void accept(final TypeTreeVisitor<?> v) {
        v.visitLongSignature(this);
    }
}


text:
package org.simpleds.metadata;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.simpleds.annotations.Property;
import org.simpleds.converter.Converter;
import org.simpleds.converter.NullConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertyMetadataFactory {

	private static Logger log = LoggerFactory.getLogger(PropertyMetadataFactory.class);

	@SuppressWarnings("unchecked")
	public static <J, D> SinglePropertyMetadata<J, D> create(String name, Field field, Method getter, Method setter) {
		try {
			log.debug("Processing property " + name);
			if (field == null && getter == null) {
				throw new IllegalArgumentException("Either supply field or getter");
			}
			SinglePropertyMetadata<J, D> metadata = new SinglePropertyMetadata<J, D>();
			metadata.setGetter(getter);
			metadata.setSetter(setter);
			metadata.setField(field);

			// @Property
			Property propertyAnn = metadata.getAnnotation(Property.class);
			if (propertyAnn != null) {
				metadata.setIndexed(!propertyAnn.unindexed());
				if (propertyAnn.value().length() > 0) {
					name = propertyAnn.value();
				}
				if (propertyAnn.converter() != NullConverter.class) {
					metadata.setConverter((Converter<J, D>) propertyAnn.converter().newInstance());
				}
			}

			metadata.setName(name);

			// calculate the property type
			Class<J> propertyType = (Class<J>) (getter == null? field.getType() : getter.getReturnType());
			metadata.setPropertyType(propertyType);

			// no setter specified, we will set the field directly
			if (setter == null) {
				field.setAccessible(true);
			}
			return metadata;
		} catch (RuntimeException e) {
			throw new RuntimeException("Cannot process property '" + name + "': " + e.getMessage(), e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

}


text:
package org.apache.jackrabbit.spi.commons.batch;

import javax.jcr.RepositoryException;

import org.apache.jackrabbit.spi.Batch;

/**
 * An Operation represents a method call on a {@link Batch}.
 */
public interface Operation {

    /**
     * Apply this operation to the given {@link Batch}
     * @param batch
     * @throws RepositoryException
     */
    public void apply(Batch batch) throws RepositoryException;
}


text:
<?xml version="1.0"?>

<!DOCTYPE chapter SYSTEM "cruise_help.dtd">
<chapter title="Value Stream Map">

Value Stream Map helps you visualize your CI/CD workflow. With a single click, it allows you to trace a commit from when it is checked in up to when it is deployed.

           A value stream map can be drawn for every instance of a pipeline. It provides you with the ability to:
           <bullets>
               <item>See what caused the current pipeline to be triggered.</item>
               <item>See what downstream pipelines were triggered by the current pipeline.</item>
               <item>See the status of the current pipeline and all its upstream and downstream dependencies.</item>
               <item>See changes in dependencies of the pipeline across different runs of it.</item>
           </bullets>

            Along with all this, it also allows you to easily debug problems when a dependency/configuration change caused your build-test-release setup to break.

The Value Stream Map is laid out as an end-to-end dependency graph. The graph originates from source control materials and flows from left to right.

The pipeline instance for which the Value Stream Map is being viewed is the main pipeline and is highlighted.
            Everything to the left of this pipeline are its upstream dependencies, ie all the materials that have contributed to this instance.
            Everything to the right are its downstream dependencies, ie, all the pipelines that it can potentially trigger or contribute to.

The upstream dependencies of the main pipeline are taken from history and show all the source control and pipeline dependency materials that have contributed to the main pipeline.
                Even when the Go Configuration changes after a certain instance of a pipeline, its upstream dependency graph will continue to reflect the older configuration with which it was run.
                This also means that it would display pipelines that do not exist in the configuration any more.

Let us assume that instance '1' of pipeline 'Build' is as below

If the configuration changes to replace the pipeline 'Services' with 2 pipelines - 'Service-1' and 'Service-2', the next instance of pipeline 'Build' would reflect the change.

Value Stream Map of pipeline 'Build' with counter '1' would look as below

The downstream dependencies of the main pipeline instance indicate what can happen with it. This information is always taken from the latest configuration. Pipelines that have not run yet are also shown

If Environment-1 is removed from the configuration, the Value Stream Map for the same instance of 'Build' would look as below.

A pipeline could be re-triggered multiple times with the same revision. In such cases, all the instances are shown in descending order against that pipeline.
                In the below example, 'Deploy' has been triggered thrice with counter '2' of pipeline 'FunctionalTests'.

Every pipeline label in Go directs you to the value stream map of that instance of the pipeline.

The permissions required to view a value stream map are as follows:
                <bullets>
                    <item>Go Administrators have access to the value stream maps of all the pipelines that are configured.</item>
                    <item>Users with view permissions for a pipeline will be able to view the value stream map for all instances of that pipeline.</item>
                </bullets>

However, there is one special case to be noted where the pipeline details might not be shown completely.
                    If the user does not have view permissions for a pipeline in the Value Stream Map, its details, like the stages and instances run will not be shown.

        <note>If you are using Internet Explorer as your browser please note that Value Stream Map is supported with only versions 9 and above.</note>

</chapter>


text:
package task

import (
	flatbuffers "github.com/google/flatbuffers/go"
)
type Query struct {
	_tab flatbuffers.Table
}

func (rcv *Query) Init(buf []byte, i flatbuffers.UOffsetT) {
	rcv._tab.Bytes = buf
	rcv._tab.Pos = i
}

func (rcv *Query) Attr() []byte {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
	if o != 0 {
		return rcv._tab.ByteVector(o + rcv._tab.Pos)
	}
	return nil
}

func (rcv *Query) Uids(j int) uint64 {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
	if o != 0 {
		a := rcv._tab.Vector(o)
		return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j * 8))
	}
	return 0
}

func (rcv *Query) UidsLength() int {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
	if o != 0 {
		return rcv._tab.VectorLen(o)
	}
	return 0
}

func QueryStart(builder *flatbuffers.Builder) { builder.StartObject(2) }
func QueryAddAttr(builder *flatbuffers.Builder, attr flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(attr), 0) }
func QueryAddUids(builder *flatbuffers.Builder, uids flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(uids), 0) }
func QueryStartUidsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 8)
}
func QueryEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { return builder.EndObject() }


text:
<!DOCTYPE html>

    <title>Table generation</title>


text:
package org.apache.ambari.server.state.stack.upgrade;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.google.common.base.Objects;

/**
 * Aggregates all upgrade tasks for a HostComponent into one wrapper.
 */
public class TaskWrapper {

  private String service;
  private String component;
  private Set<String> hosts; // all the hosts that all the tasks must run
  private Map<String, String> params;
  /* FIXME a TaskWrapper really should be wrapping ONLY ONE task */
  private List<Task> tasks; // all the tasks defined for the hostcomponent
  private Set<String> timeoutKeys = new HashSet<>();

  /**
   * @param s the service name for the tasks
   * @param c the component name for the tasks
   * @param hosts the set of hosts that the tasks are for
   * @param tasks an array of tasks as a convenience
   */
  public TaskWrapper(String s, String c, Set<String> hosts, Task task) {
    this(s, c, hosts, null, task);
  }

  /**
   * @param s the service name for the tasks
   * @param c the component name for the tasks
   * @param hosts the set of hosts that the tasks are for
   * @param params additional command parameters
   * @param tasks an array of tasks as a convenience
   */
  public TaskWrapper(String s, String c, Set<String> hosts, Map<String, String> params, Task... tasks) {
    this(s, c, hosts, params, Arrays.asList(tasks));
  }

  /**
   * @param s the service name for the tasks
   * @param c the component name for the tasks
   * @param hosts the set of hosts for the
   * @param tasks the list of tasks
   */
  public TaskWrapper(String s, String c, Set<String> hosts, Map<String, String> params, List<Task> tasks) {
    service = s;
    component = c;

    this.hosts = hosts;
    this.params = (params == null) ? new HashMap<String, String>() : params;
    this.tasks = tasks;

    // !!! FIXME there should only be one task
    for (Task task : tasks) {
      if (StringUtils.isNotBlank(task.timeoutConfig)) {
        timeoutKeys.add(task.timeoutConfig);
      }
    }
  }

  /**
   * @return the additional command parameters.
   */
  public Map<String, String> getParams() {
    return params;
  }

  /**
   * @return the tasks associated with this wrapper
   */
  public List<Task> getTasks() {
    return tasks;
  }

  /**
   * @return the hosts associated with this wrapper
   */
  public Set<String> getHosts() {
    return hosts;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {
    return Objects.toStringHelper(this).add("service", service)
        .add("component", component)
        .add("tasks", tasks)
        .add("hosts", hosts)
        .omitNullValues().toString();
  }

  /**
   * @return the service name
   */
  public String getService() {
    return service;
  }

  /**
   * @return the component name
   */
  public String getComponent() {
    return component;
  }

  /**
   * @return true if any task is sequential, otherwise, return false.
   */
  public boolean isAnyTaskSequential() {
    for (Task t : getTasks()) {
      if (t.isSequential) {
        return true;
      }
    }

    return false;
  }

  /**
   * @return the timeout keys for all the tasks in this wrapper.
   */
  public Set<String> getTimeoutKeys() {
    return timeoutKeys;
  }

}


text:
Rocksmith
=========

Custom Rocksmith DLC

Resources:

* How To: http://rocksmithcustoms.wikispaces.com/
* Song BPM: http://songbpm.com/
* Guitar Tabs: http://www.ultimate-guitar.com/


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 89(2): 401 (2004)

#### Original name
Marasmius confertus var. parvisporus Antonín

### Remarks
null


text:
package uk.joshiejack.harvestcore.network.mail;

import uk.joshiejack.harvestcore.client.mail.Inbox;
import uk.joshiejack.harvestcore.registry.letter.Letter;
import uk.joshiejack.penguinlib.network.packet.PacketSendPenguin;
import uk.joshiejack.penguinlib.util.PenguinLoader;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.relauncher.Side;

@PenguinLoader(side = Side.CLIENT)
public class PacketSendLetter extends PacketSendPenguin<Letter> {
    public PacketSendLetter() {
        super(Letter.REGISTRY);
    }
    public PacketSendLetter(Letter letter) {
        super(Letter.REGISTRY, letter);
    }

    @Override
    public void handlePacket(EntityPlayer player, Letter letter) {
        Inbox.PLAYER.add(letter);
    }
}


text:
package org.apache.flink.runtime.security;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.IllegalConfigurationException;

import org.junit.jupiter.api.Test;

import static org.apache.flink.configuration.SecurityOptions.KERBEROS_LOGIN_KEYTAB;
import static org.apache.flink.configuration.SecurityOptions.KERBEROS_LOGIN_PRINCIPAL;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

/** Tests for the {@link SecurityConfiguration}. */
class SecurityConfigurationTest {

    @Test
    public void keytabWithoutPrincipalShouldThrowException() {
        Configuration configuration = new Configuration();
        configuration.set(KERBEROS_LOGIN_KEYTAB, "keytab.file");

        IllegalConfigurationException e =
                assertThrows(
                        IllegalConfigurationException.class,
                        () -> new SecurityConfiguration(configuration));
        assertTrue(
                e.getMessage()
                        .contains("either both keytab and principal must be defined, or neither"));
    }

    @Test
    public void principalWithoutKeytabShouldThrowException() {
        Configuration configuration = new Configuration();
        configuration.set(KERBEROS_LOGIN_PRINCIPAL, "principal");

        IllegalConfigurationException e =
                assertThrows(
                        IllegalConfigurationException.class,
                        () -> new SecurityConfiguration(configuration));
        assertTrue(
                e.getMessage()
                        .contains("either both keytab and principal must be defined, or neither"));
    }

    @Test
    public void notExistingKeytabShouldThrowException() {
        Configuration configuration = new Configuration();
        configuration.set(KERBEROS_LOGIN_KEYTAB, "nonexistingkeytab.file");
        configuration.set(KERBEROS_LOGIN_PRINCIPAL, "principal");

        IllegalConfigurationException e =
                assertThrows(
                        IllegalConfigurationException.class,
                        () -> new SecurityConfiguration(configuration));
        assertTrue(e.getMessage().contains("nonexistingkeytab.file"));
        assertTrue(e.getMessage().contains("doesn't exist"));
    }
}


text:
import JasmineWebdriver from './jasmine_webdriver';

let webdriver;

export function visit(url) {
  return webdriver.driver().then(({driver}) => {
    return driver.url(url).then(() => ({page: driver}));
  });
}

export function describeWithWebdriver(name, callback, options = {}) {
  describe(name, function() {
    beforeEach(() => {
      webdriver = webdriver || new JasmineWebdriver({timeout: 5000, ...options});
    });

    afterEach.async(async function() {
      await webdriver.end();
    });

    callback();
  });
}


text:
<?php
/**
 * Backup
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @category Backup
 * @package  Backup
 * @author   Adam Brett <adam@adambrett.co.uk>
 * @license  New BSD LICENSE
 * @version  0.1
 * @link     http://github.com/adambrett/php-backup
 */

namespace BackupTests\Source;

use Faker\Factory as Faker;
use Mockery;

use Backup;

/**
 * FTP Source
 *
 * @category Tests
 * @package  Backup
 * @author   Adam Brett <adam@adambrett.co.uk>
 * @license  New BSD LICENSE
 * @link     https://github.com/adambrett/php-backup
 */
class FtpTest extends \PHPUnit_Framework_TestCase
{
    static $faker;
    static $fixtures;
    static $fixturePath;

    static $server;
    static $pipes;

    protected $ftp;

    /**
     * SetUp Before Class
     *
     * Run test ftp server and create some dummy files.  We can use
     * the same dummy server for all tests safely as we're only making
     * reads and not writes.
     *
     * @return void
     */
    public static function setUpBeforeClass()
    {
        self::$faker = Faker::create();

        self::$fixturePath = realpath(__DIR__) . '/fixtures/' . self::$faker->word . '/';

        if (!file_exists(self::$fixturePath)) {
            mkdir(self::$fixturePath, 0777, true);
        }

        for ($i = 0; $i < 5; $i++) {
            $filename = self::$fixturePath . self::$faker->word . '.txt';
            $contents = implode("\n\n", self::$faker->paragraphs());

            file_put_contents($filename, $contents);
            self::$fixtures[$filename] = $contents;
        }

        // server will return files in alpha order
        // but faker will generate in a random order
        ksort(self::$fixtures);

        self::$server = proc_open(
            'python ' . realpath(
                __DIR__ . '/../../../vendor/basic_ftpd.py'
            ),
            array(
                array('pipe', 'r'),
                array('pipe', 'w'),
                array('pipe', 'w')
            ),
            self::$pipes,
            self::$fixturePath
        );

        // wait 1 second for the server to start otherwise we'll
        // get an unable to connect error on the first test
        sleep(1);
    }

    /**
     * TearDown
     *
     * Executed after every test, shuts down the python ftp server
     *
     * @return void
     */
    public static function tearDownAfterClass()
    {
        proc_terminate(self::$server);

        foreach (scandir(self::$fixturePath) as $file) {
            if (in_array($file, array('.', '..'))) continue;

            unlink(self::$fixturePath . $file);
        }

        rmdir(self::$fixturePath);
        rmdir(dirname(self::$fixturePath));
    }

    /**
     * SetUp
     *
     * Run before every test
     *
     * @return void
     */
    public function setUp()
    {
        $this->ftp = new Backup\Source\Ftp(
            'localhost',
            'user',
            '12345',
            3334
        );
    }

    public function testImplementsInterface()
    {
        $this->assertInstanceOf('\\Backup\\Source\\SourceInterface', $this->ftp);
    }

    public function testDirectoryList()
    {
        $listing = $this->ftp->directoryList('/');

        $this->assertCount(count(self::$fixtures), $listing);

        $filenames = array_keys(self::$fixtures);
        foreach ($listing as $index => $file) {
            $this->assertEquals(basename($filenames[$index]), basename($file));
        }
    }

    public function testGetFileContents()
    {
        foreach (self::$fixtures as $filename => $contents) {
            $remoteContent = $this->ftp->getFileContents(basename($filename));
            $this->assertEquals($contents, $remoteContent);
        }
    }

    public function testIsDirectory()
    {
        $dirname = self::$faker->word . '/';
        mkdir(self::$fixturePath . $dirname, 0777, true);

        $this->assertTrue($this->ftp->isDirectory($dirname));

        $file = $dirname . self::$faker->word . '.txt';
        file_put_contents(
            self::$fixturePath . $file,
            implode("\n\n", self::$faker->paragraphs())
        );

        $this->assertFalse($this->ftp->isDirectory($file));

        unlink(self::$fixturePath . $file);
        rmdir(self::$fixturePath . $dirname);
    }
}


text:
robot-x-vehicle-sim
===================

Simulator of the vehicle for the OCS team.


text:
"use strict";

const giveUniqueId     = require("give-unique-id"),
      opponentNeedsCar = require("./mixins/opponent-needs-car");

function Attack(attackType) {
  giveUniqueId(this);

  function play(gameData, choiceProvider, player) {
    return choiceProvider.chooseOpponentCar(gameData, player)
      .then(tryAttack.bind(null, player, gameData, choiceProvider));
  }
  this.play = play;

  function tryAttack(attacker, gameData, choiceProvider, car) {
    return choiceProvider.allowBlockAttack(gameData, attackType, car)
      .then(function(blockAttack) {
        if(!blockAttack) attack(car, gameData);
        else penalize(attacker, car, gameData);
      });
  }

  function attack(car, gameData) {
    gameData.getPlayerWithCar(car).discardCar(car);
  }

  function penalize(attacker, car, gameData) {
    let victim = gameData.getPlayerWithCar(car);
    victim.credit(car.listPrice);
    attacker.debit(car.listPrice);
  }

  this.canPlay = opponentNeedsCar;
}

Attack.attackTypes = {
  fire: 1,
  theft: 2,
  collision: 3,
  rancidPopcorn: 4
};

module.exports = Attack;


text:
module Dyndnsd
  module Updater
    class Dummy
      def update(zone)
        # nothing
      end
    end
  end
end


text:
package stroom.search.solr.shared;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

@JsonInclude(Include.NON_NULL)
public class SolrSynchState {

    @JsonProperty
    private final Long lastSynchronized;
    @JsonProperty
    private final List<String> messages;

    @JsonCreator
    public SolrSynchState(@JsonProperty("lastSynchronized") final Long lastSynchronized,
                          @JsonProperty("messages") final List<String> messages) {
        this.lastSynchronized = lastSynchronized;
        this.messages = messages;
    }

    public Long getLastSynchronized() {
        return lastSynchronized;
    }

    public List<String> getMessages() {
        return messages;
    }
}


text:
package org.mcupdater.instance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Instance {
	private String mcversion;
	private String revision;
	private List<FileInfo> instanceFiles = new ArrayList<FileInfo>();
	private List<FileInfo> jarMods = new ArrayList<FileInfo>();
	private Map<String, Boolean> optionalMods = new HashMap<String, Boolean>();

	public List<FileInfo> getInstanceFiles() {
		return instanceFiles;
	}

	public void setInstanceFiles(List<FileInfo> instanceFiles) {
		this.instanceFiles = instanceFiles;
	}

	public Map<String, Boolean> getOptionalMods() {
		return this.optionalMods;
	}

	public Boolean getModStatus(String key) {
		return this.optionalMods.get(key);
	}

	public void setModStatus(String key, Boolean value) {
		this.optionalMods.put(key, value);
	}

	public String getMCVersion() {
		return mcversion;
	}

	public void setMCVersion(String mcversion) {
		this.mcversion = mcversion;
	}

	public String getRevision() {
		return revision;
	}

	public void setRevision(String revision) {
		this.revision = revision;
	}

	public List<FileInfo> getJarMods() {
		return jarMods;
	}

	public void setJarMods(List<FileInfo> jarMods) {
		this.jarMods = jarMods;
	}

	public FileInfo findJarMod(String id) {
		Iterator<FileInfo> it = this.jarMods.iterator();
		while (it.hasNext()) {
			FileInfo entry = it.next();
			if (entry.getModId().equals(id)) {
				return entry;
			}
		}
		return null;
	}

	public void addJarMod(String id, String md5) {
		FileInfo entry = new FileInfo();
		entry.setModId(id);
		entry.setMD5(md5);
		this.jarMods.add(entry);
	}

	public void addMod(String id, String md5, String filename) {
		FileInfo entry = new FileInfo();
		entry.setModId(id);
		entry.setMD5(md5);
		entry.setFilename(filename);
		this.instanceFiles.add(entry);
	}
}


text:
/*************************************************************************/
/*  physics_2d_server_sw.h                                               */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef PHYSICS_2D_SERVER_SW
#define PHYSICS_2D_SERVER_SW

#include "servers/physics_2d_server.h"
#include "shape_2d_sw.h"
#include "space_2d_sw.h"
#include "step_2d_sw.h"
#include "joints_2d_sw.h"

class Physics2DServerSW : public Physics2DServer {

	OBJ_TYPE( Physics2DServerSW, Physics2DServer );

friend class Physics2DDirectSpaceStateSW;
friend class Physics2DDirectBodyStateSW;
	bool active;
	int iterations;
	bool doing_sync;
	real_t last_step;

	int island_count;
	int active_objects;
	int collision_pairs;

	bool using_threads;

	Step2DSW *stepper;
	Set<const Space2DSW*> active_spaces;

	Physics2DDirectBodyStateSW *direct_state;

	mutable RID_Owner<Shape2DSW> shape_owner;
	mutable RID_Owner<Space2DSW> space_owner;
	mutable RID_Owner<Area2DSW> area_owner;
	mutable RID_Owner<Body2DSW> body_owner;
	mutable RID_Owner<Joint2DSW> joint_owner;

	static Physics2DServerSW *singletonsw;

//	void _clear_query(Query2DSW *p_query);
public:

	struct CollCbkData {

		Vector2 valid_dir;
		float valid_depth;
		int max;
		int amount;
		Vector2 *ptr;
	};

	static void _shape_col_cbk(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata);

	virtual RID shape_create(ShapeType p_shape);
	virtual void shape_set_data(RID p_shape, const Variant& p_data);
	virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias);

	virtual ShapeType shape_get_type(RID p_shape) const;
	virtual Variant shape_get_data(RID p_shape) const;
	virtual real_t shape_get_custom_solver_bias(RID p_shape) const;

	virtual bool shape_collide(RID p_shape_A, const Matrix32& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Matrix32& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count);

	/* SPACE API */

	virtual RID space_create();
	virtual void space_set_active(RID p_space,bool p_active);
	virtual bool space_is_active(RID p_space) const;

	virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value);
	virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const;

	virtual void space_set_debug_contacts(RID p_space,int p_max_contacts);
	virtual Vector<Vector2> space_get_contacts(RID p_space) const;
	virtual int space_get_contact_count(RID p_space) const;

	// this function only works on fixed process, errors and returns null otherwise
	virtual Physics2DDirectSpaceState* space_get_direct_state(RID p_space);

	/* AREA API */

	virtual RID area_create();

	virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode);
	virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const;

	virtual void area_set_space(RID p_area, RID p_space);
	virtual RID area_get_space(RID p_area) const;

	virtual void area_add_shape(RID p_area, RID p_shape, const Matrix32& p_transform=Matrix32());
	virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape);
	virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Matrix32& p_transform);

	virtual int area_get_shape_count(RID p_area) const;
	virtual RID area_get_shape(RID p_area, int p_shape_idx) const;
	virtual Matrix32 area_get_shape_transform(RID p_area, int p_shape_idx) const;

	virtual void area_remove_shape(RID p_area, int p_shape_idx);
	virtual void area_clear_shapes(RID p_area);

	virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID);
	virtual ObjectID area_get_object_instance_ID(RID p_area) const;

	virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value);
	virtual void area_set_transform(RID p_area, const Matrix32& p_transform);

	virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const;
	virtual Matrix32 area_get_transform(RID p_area) const;
	virtual void area_set_monitorable(RID p_area,bool p_monitorable);
	virtual void area_set_collision_mask(RID p_area,uint32_t p_mask);
	virtual void area_set_layer_mask(RID p_area,uint32_t p_mask);

	virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method);
	virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method);

	virtual void area_set_pickable(RID p_area,bool p_pickable);

	/* BODY API */

	// create a body of a given type
	virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false);

	virtual void body_set_space(RID p_body, RID p_space);
	virtual RID body_get_space(RID p_body) const;

	virtual void body_set_mode(RID p_body, BodyMode p_mode);
	virtual BodyMode body_get_mode(RID p_body) const;

	virtual void body_add_shape(RID p_body, RID p_shape, const Matrix32& p_transform=Matrix32());
	virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape);
	virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Matrix32& p_transform);
	virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata);

	virtual int body_get_shape_count(RID p_body) const;
	virtual RID body_get_shape(RID p_body, int p_shape_idx) const;
	virtual Matrix32 body_get_shape_transform(RID p_body, int p_shape_idx) const;
	virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const;

	virtual void body_remove_shape(RID p_body, int p_shape_idx);
	virtual void body_clear_shapes(RID p_body);

	virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable);
	virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const;

	virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID);
	virtual uint32_t body_get_object_instance_ID(RID p_body) const;

	virtual void body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode);
	virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const;

	virtual void body_set_layer_mask(RID p_body, uint32_t p_mask);
	virtual uint32_t body_get_layer_mask(RID p_body) const;

	virtual void body_set_collision_mask(RID p_body, uint32_t p_mask);
	virtual uint32_t body_get_collision_mask(RID p_) const;

	virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value);
	virtual float body_get_param(RID p_body, BodyParameter p_param) const;

	virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant);
	virtual Variant body_get_state(RID p_body, BodyState p_state) const;

	virtual void body_set_applied_force(RID p_body, const Vector2& p_force);
	virtual Vector2 body_get_applied_force(RID p_body) const;

	virtual void body_set_applied_torque(RID p_body, float p_torque);
	virtual float body_get_applied_torque(RID p_body) const;

	virtual void body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force);

	virtual void body_apply_impulse(RID p_body, const Vector2& p_pos, const Vector2& p_impulse);
	virtual void body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity);

	virtual void body_add_collision_exception(RID p_body, RID p_body_b);
	virtual void body_remove_collision_exception(RID p_body, RID p_body_b);
	virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions);

	virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold);
	virtual float body_get_contacts_reported_depth_treshold(RID p_body) const;

	virtual void body_set_omit_force_integration(RID p_body,bool p_omit);
	virtual bool body_is_omitting_force_integration(RID p_body) const;

	virtual void body_set_max_contacts_reported(RID p_body, int p_contacts);
	virtual int body_get_max_contacts_reported(RID p_body) const;

	virtual void body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction);
	virtual Vector2 body_get_one_way_collision_direction(RID p_body) const;

	virtual void body_set_one_way_collision_max_depth(RID p_body,float p_max_depth);
	virtual float body_get_one_way_collision_max_depth(RID p_body) const;

	virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant());
	virtual bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Matrix32& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count);

	virtual void body_set_pickable(RID p_body,bool p_pickable);

	virtual bool body_test_motion(RID p_body,const Vector2& p_motion,float p_margin=0.001,MotionResult *r_result=NULL);

	/* JOINT API */

	virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value);
	virtual real_t joint_get_param(RID p_joint,JointParam p_param) const;

	virtual RID pin_joint_create(const Vector2& p_pos,RID p_body_a,RID p_body_b=RID());
	virtual RID groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b);
	virtual RID damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b=RID());
	virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value);
	virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const;
	virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value);
	virtual real_t damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const;

	virtual JointType joint_get_type(RID p_joint) const;

	/* MISC */

	virtual void free(RID p_rid);

	virtual void set_active(bool p_active);
	virtual void init();
	virtual void step(float p_step);
	virtual void sync();
	virtual void flush_queries();
	virtual void end_sync();
	virtual void finish();

	int get_process_info(ProcessInfo p_info);

	Physics2DServerSW();
	~Physics2DServerSW();

};

#endif


text:
var jwt = require('jwt-simple'),
    env = process.env.NODE_ENV || 'development',
    config = require('../../config/config')[env];

module.exports = function(){
    return function(req,res,next){
        var property = req._passport.instance._userProperty || 'user';
        var tokenSecret = config.jwtToken.secret;

        console.log('req.headers.access_token',req.headers.access_token);
        if(req[property]) return next();
        if(req.headers.access_token){
            var tokenObject = jwt.decode(req.headers.access_token, tokenSecret);
            if(Date.now() > tokenObject.expired){
                // token is expired
                return next();
            }else{
                var su = tokenObject._id;
                req._passport.instance.deserializeUser(su, function(err, user) {
                    if (err) { return next(); }
                    if (!user) {
                        return next();
                    };

                    req[property] = user;
                    next();
                });

            }
        }else{
            next();
        }
    }
}


text:
package com.amazonaws.services.iotdata;

import javax.annotation.Generated;

import com.amazonaws.services.iotdata.model.*;

/**
 * Interface for accessing AWS IoT Data Plane asynchronously. Each asynchronous method will return a Java Future object
 * representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
 * notification when an asynchronous operation completes.
 *

 * Note: Do not directly implement this interface, new methods are added to it regularly. Extend from
 * {@link com.amazonaws.services.iotdata.AbstractAWSIotDataAsync} instead.
 *

 *

 * <fullname>AWS IoT</fullname>
 *

 * AWS IoT-Data enables secure, bi-directional communication between Internet-connected things (such as sensors,
 * actuators, embedded devices, or smart appliances) and the AWS cloud. It implements a broker for applications and
 * things to publish messages over HTTP (Publish) and retrieve, update, and delete thing shadows. A thing shadow is a
 * persistent representation of your things and their state in the AWS cloud.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public interface AWSIotDataAsync extends AWSIotData {

    /**
     *

     * Deletes the thing shadow for the specified thing.
     *

     *

     * For more information, see DeleteThingShadow in
     * the AWS IoT Developer Guide.
     *

     *
     * @param deleteThingShadowRequest
     *        The input for the DeleteThingShadow operation.
     * @return A Java Future containing the result of the DeleteThingShadow operation returned by the service.
     * @sample AWSIotDataAsync.DeleteThingShadow
     */
    java.util.concurrent.Future<DeleteThingShadowResult> deleteThingShadowAsync(DeleteThingShadowRequest deleteThingShadowRequest);

    /**
     *

     * Deletes the thing shadow for the specified thing.
     *

     *

     * For more information, see DeleteThingShadow in
     * the AWS IoT Developer Guide.
     *

     *
     * @param deleteThingShadowRequest
     *        The input for the DeleteThingShadow operation.
     * @param asyncHandler
     *        Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
     *        implementation of the callback methods in this interface to receive notification of successful or
     *        unsuccessful completion of the operation.
     * @return A Java Future containing the result of the DeleteThingShadow operation returned by the service.
     * @sample AWSIotDataAsyncHandler.DeleteThingShadow
     */
    java.util.concurrent.Future<DeleteThingShadowResult> deleteThingShadowAsync(DeleteThingShadowRequest deleteThingShadowRequest,
            com.amazonaws.handlers.AsyncHandler<DeleteThingShadowRequest, DeleteThingShadowResult> asyncHandler);

    /**
     *

     * Gets the thing shadow for the specified thing.
     *

     *

     * For more information, see GetThingShadow in the
     * AWS IoT Developer Guide.
     *

     *
     * @param getThingShadowRequest
     *        The input for the GetThingShadow operation.
     * @return A Java Future containing the result of the GetThingShadow operation returned by the service.
     * @sample AWSIotDataAsync.GetThingShadow
     */
    java.util.concurrent.Future<GetThingShadowResult> getThingShadowAsync(GetThingShadowRequest getThingShadowRequest);

    /**
     *

     * Gets the thing shadow for the specified thing.
     *

     *

     * For more information, see GetThingShadow in the
     * AWS IoT Developer Guide.
     *

     *
     * @param getThingShadowRequest
     *        The input for the GetThingShadow operation.
     * @param asyncHandler
     *        Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
     *        implementation of the callback methods in this interface to receive notification of successful or
     *        unsuccessful completion of the operation.
     * @return A Java Future containing the result of the GetThingShadow operation returned by the service.
     * @sample AWSIotDataAsyncHandler.GetThingShadow
     */
    java.util.concurrent.Future<GetThingShadowResult> getThingShadowAsync(GetThingShadowRequest getThingShadowRequest,
            com.amazonaws.handlers.AsyncHandler<GetThingShadowRequest, GetThingShadowResult> asyncHandler);

    /**
     *

     * Publishes state information.
     *

     *

     * For more information, see HTTP
     * Protocol in the AWS IoT Developer Guide.
     *

     *
     * @param publishRequest
     *        The input for the Publish operation.
     * @return A Java Future containing the result of the Publish operation returned by the service.
     * @sample AWSIotDataAsync.Publish
     */
    java.util.concurrent.Future<PublishResult> publishAsync(PublishRequest publishRequest);

    /**
     *

     * Publishes state information.
     *

     *

     * For more information, see HTTP
     * Protocol in the AWS IoT Developer Guide.
     *

     *
     * @param publishRequest
     *        The input for the Publish operation.
     * @param asyncHandler
     *        Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
     *        implementation of the callback methods in this interface to receive notification of successful or
     *        unsuccessful completion of the operation.
     * @return A Java Future containing the result of the Publish operation returned by the service.
     * @sample AWSIotDataAsyncHandler.Publish
     */
    java.util.concurrent.Future<PublishResult> publishAsync(PublishRequest publishRequest,
            com.amazonaws.handlers.AsyncHandler<PublishRequest, PublishResult> asyncHandler);

    /**
     *

     * Updates the thing shadow for the specified thing.
     *

     *

     * For more information, see UpdateThingShadow in
     * the AWS IoT Developer Guide.
     *

     *
     * @param updateThingShadowRequest
     *        The input for the UpdateThingShadow operation.
     * @return A Java Future containing the result of the UpdateThingShadow operation returned by the service.
     * @sample AWSIotDataAsync.UpdateThingShadow
     */
    java.util.concurrent.Future<UpdateThingShadowResult> updateThingShadowAsync(UpdateThingShadowRequest updateThingShadowRequest);

    /**
     *

     * Updates the thing shadow for the specified thing.
     *

     *

     * For more information, see UpdateThingShadow in
     * the AWS IoT Developer Guide.
     *

     *
     * @param updateThingShadowRequest
     *        The input for the UpdateThingShadow operation.
     * @param asyncHandler
     *        Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
     *        implementation of the callback methods in this interface to receive notification of successful or
     *        unsuccessful completion of the operation.
     * @return A Java Future containing the result of the UpdateThingShadow operation returned by the service.
     * @sample AWSIotDataAsyncHandler.UpdateThingShadow
     */
    java.util.concurrent.Future<UpdateThingShadowResult> updateThingShadowAsync(UpdateThingShadowRequest updateThingShadowRequest,
            com.amazonaws.handlers.AsyncHandler<UpdateThingShadowRequest, UpdateThingShadowResult> asyncHandler);

}


text:
<?php

class Core_Model_Acl_Role extends BV_Model_Essential_Abstract
{

    protected $_roleId;

    public function __construct($roleId = null)
    {
        parent::__construct();
        if (is_numeric($roleId) and $roleId > 3) {
            $this->_roleId = $roleId;
        }
    }

    /*
     * Set the roleId
     */
    public function setId($roleId = null)
    {
        if (is_numeric($roleId) and $roleId > 3) {
            $this->_roleId = $roleId;
        }
    }

    /*
     * Fetch a single role record
     */
    public function fetch()
    {
       $result = $this->db->fetchRow('SELECT * FROM role WHERE role_id = ?', $this->_roleId);
       return $result;
    }

    /*
     * Delete the role
     */
    public function delete()
    {
        $where = $this->db->quote($this->_roleId, 'INTEGER');
        $result = $this->db->delete('role', "role_id = $where");
        return $result;
    }

}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace SDKTemplate
{
    public abstract class SharePage : Page
    {
        protected MainPage rootPage = MainPage.Current;
        private DataTransferManager dataTransferManager;

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Register the current page as a share source.
            this.dataTransferManager = DataTransferManager.GetForCurrentView();
            this.dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.OnDataRequested);

            // Request to be notified when the user chooses a share target app.
            this.dataTransferManager.TargetApplicationChosen += OnTargetApplicationChosen;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Unregister our event handlers.
            this.dataTransferManager.DataRequested -= new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.OnDataRequested);
            this.dataTransferManager.TargetApplicationChosen -= OnTargetApplicationChosen;
        }

        // When share is invoked (by the user or programatically) the event handler we registered will be called to populate the datapackage with the
        // data to be shared.
        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            // Register to be notified if the share operation completes.
            e.Request.Data.ShareCompleted += OnShareCompleted;

            // Call the scenario specific function to populate the datapackage with the data to be shared.
            if (GetShareContent(e.Request))
            {
                // Out of the datapackage properties, the title is required. If the scenario completed successfully, we need
                // to make sure the title is valid since the sample scenario gets the title from the user.
                if (String.IsNullOrEmpty(e.Request.Data.Properties.Title))
                {
                    e.Request.FailWithDisplayText(MainPage.MissingTitleError);
                }
            }
        }

        private void OnTargetApplicationChosen(DataTransferManager sender, TargetApplicationChosenEventArgs e)
        {
            this.rootPage.NotifyUser($"User chose {e.ApplicationName}", NotifyType.StatusMessage);
        }

        private void OnShareCompleted(DataPackage sender, ShareCompletedEventArgs e)
        {
            string shareCompletedStatus = "Shared successfully. ";

            // Typically, this information is not displayed to the user because the
            // user already knows which share target was selected.
            if (!String.IsNullOrEmpty(e.ShareTarget.AppUserModelId))
            {
                // The user picked an app.
                shareCompletedStatus += $"Target: App \"{e.ShareTarget.AppUserModelId}\"";
            }
            else if (e.ShareTarget.ShareProvider != null)
            {
                // The user picked a ShareProvider.
                shareCompletedStatus += $"Target: Share Provider \"{e.ShareTarget.ShareProvider.Title}\"";
            }

            this.rootPage.NotifyUser(shareCompletedStatus, NotifyType.StatusMessage);
        }

        protected void ShowUIButton_Click(object sender, RoutedEventArgs e)
        {
            // If the user clicks the share button, invoke the share flow programatically.
            DataTransferManager.ShowShareUI();
        }

        // This function is implemented by each scenario to share the content specific to that scenario (text, link, image, etc.).
        protected abstract bool GetShareContent(DataRequest request);

        protected Uri ApplicationLink
        {
            get
            {
                return GetApplicationLink(GetType().Name);
            }
        }

        public static Uri GetApplicationLink(string sharePageName)
        {
            return new Uri("ms-sdk-sharesourcecs:navigate?page=" + sharePageName);
        }
    }
}


text:
package  vnmr.ui;

import java.awt.*;
import javax.swing.*;
import java.beans.*;
import javax.swing.border.*;

import vnmr.util.*;

/**
 * A two-line button consists of two text lines.
 */
public class TwoLineButton extends JToggleButton implements PropertyChangeListener {
    /** two-line icon */
    private TwoLineIcon icon;
    protected Font font;

    /**
     * constructor
     */
    public TwoLineButton() {
		icon = new TwoLineIcon(this);
		setIcon(icon);
	    setEnabled(false);
	    setOpaque(true);
	    setBorder(BorderFactory.createRaisedBevelBorder());
        DisplayOptions.addChangeListener(this);
    } // TwoLineButton()

    public void propertyChange(PropertyChangeEvent e)
    {
        String strProperty = e.getPropertyName();
        if (strProperty == null)
            return;
        strProperty = strProperty.toLowerCase();
        if (strProperty.indexOf("vjbackground") >= 0)
            setBackground(Util.getBgColor());
    }

    /**
     * set first line
     * @param lineStr string
     */
    public void setLine1(String lineStr) {
	if (lineStr == null)
	    icon.line1Str = "";
	else
	    icon.line1Str = lineStr;
    } // setLine1()

    public boolean isRequestFocusEnabled()
    {
        return Util.isFocusTraversal();
    }

    /**
     * set first line's foreground
     * @param color color
     */
    public void setLine1Color(Color color) {
	icon.line1Color = color;
    } // setLine1Color()

    /**
     * set first line's font
     */
    public void setLine1Font(Font f) {
		icon.line1Font = f;
    } // setLine1Font()

    /**
     * set second line
     * @param lineStr string
     */
    public void setLine2(String lineStr) {
	if (lineStr == null)
	   icon.line2Str = "";
	else
	   icon.line2Str = lineStr;
    } // setLine2()

    /**
     * set second line's foreground
     * @param color color
     */
    public void setLine2Color(Color color) {
	icon.line2Color = color;
    } // setLine2Color()

    /**
     * set second line's font
     */
    public void setLine2Font(Font f) {
		icon.line2Font = f;
    } // setLine1Font()

} // class TwoLineButton

/**
 * two-line icon
 */
class TwoLineIcon implements Icon {
    // ==== instance variables
    /** parent component */
    private Component parent;
    /** first line */
    protected String line1Str;
    /** first line's foreground color */
    protected Color line1Color = Color.black;
    /** first line's font */
    protected Font line1Font;
    /** second line */
    protected String line2Str;
    /** second line's foreground color */
    protected Color line2Color = Color.black;
    /** second line's font */
    protected Font line2Font;

    /**
     * constructor
     * @param parent parent component
     */
    public TwoLineIcon(Component parent) {
		this.parent = parent;
    	line1Font = DisplayOptions.getFont("Dialog", Font.PLAIN, 12);
    	line2Font = DisplayOptions.getFont("Dialog", Font.PLAIN, 12);
    	line1Str = " ";
    	line2Str = " ";
   } // TwoLineIcon()

    /**
     * paint icon
     * The std java interface assumes only one x,y location.
     * This TwolineButton has always been starting both lines at the x location.
     * That means that the label (such as Spin) moves around depending on the
     * size of the value on line 2.  This has now been modified to adjust
     * the x,y for each line such that both lines are centered based on their
     * individual widths.
     */
    public void paintIcon(Component c, Graphics g, int x, int y) {
        int w1=0,w2=0,xnew;
		FontMetrics metrics = c.getFontMetrics(line1Font);
        w1=metrics.stringWidth(line1Str);
		if (metrics != null)
		   y += metrics.getAscent();
	  	else
		   y += 10;
        metrics = parent.getFontMetrics(line2Font);
        w2=metrics.stringWidth(line2Str);
        if(w1 < w2)
            // Adjust x for centering of line 1
            xnew = x + (w2 - w1)/2;
        else
            xnew = x;
		g.setFont(line1Font);
		g.setColor(line1Color);
		g.drawString(line1Str, xnew, y);
		if (metrics != null)
		    y += metrics.getHeight();
	  	else
		   y += 10;
		if(w1 > w2)
            // Adjust x for centering of line 2
            xnew = x + (w1 - w2)/2;
        else
            xnew = x;
		g.setColor(line2Color);
		g.setFont(line2Font);
		g.drawString(line2Str, xnew, y);
    } // paintIcon()

    /**
     * get width
     * @return width
     */
    public int getIconWidth() {
		int w1=0,w2=0;
		FontMetrics metrics;
	    metrics = parent.getFontMetrics(line1Font);
	    w1=metrics.stringWidth(line1Str);
	    metrics = parent.getFontMetrics(line2Font);
	    w2=metrics.stringWidth(line2Str);
	    return w1>w2?w1:w2;
    } // getIconWidth()

    /**
     * get height
     * @return height
     */
    public int getIconHeight() {
		int ht;
	    FontMetrics metrics = parent.getFontMetrics(line1Font);
	    ht=metrics.getHeight();
	    metrics = parent.getFontMetrics(line2Font);
	    return ht+metrics.getHeight();
    } // getIconHeight()

} // class TwoLineIcon


text:
//==========================================
// include guard
#ifndef libClass_h
#define libClass_h

/** Includes Core Arduino functionality **/
#if ARDUINO
    #if ARDUINO < 100
        #include <WProgram.h>
    #else
        #include <Arduino.h>
    #endif
#endif

class libClass {
public:

    //==========================================
    // constructor

    libClass();
    libClass(uint32_t duration_new);

    virtual ~libClass();

    //==========================================
    // public types

    // typedef void (*cbfunc_t) (libClass *pInstance);
    typedef void (*cbfunc_t) (uint32_t counter);

    //==========================================
    // public functions

    void init();
    void update();

    void set_callbackfunc(cbfunc_t callbackfunc_new);
    void set_duration(uint32_t duration_new);

private:

    uint32_t lastAction;
    uint32_t duration;
    uint32_t counter;

    bool cbfunc_valid;
    cbfunc_t callbackfunc;

};

// typedef void (libCalss::*cbfunc_t)(libClass *pInstance);

#endif // libClass_h


text:
<?php

use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;

$metadata = new ClassMetadata('JMS\Serializer\Tests\Fixtures\Discriminator\Car');

return $metadata;