text:
package hipg.app.scc;

import hipg.BarrierAndReduce;
import hipg.Config;
import hipg.Node;
import hipg.Reduce;
import hipg.format.GraphCreationException;
import hipg.format.GraphIO;
import hipg.graph.ExplicitGraph;
import hipg.graph.ExplicitLocalNode;
import hipg.runtime.Runtime;

import java.io.PrintStream;

import myutils.ConversionUtils;

public final class owctypa3 {

	private static final boolean vverbose = false;
	private static final boolean verbose = false;
	private static final boolean check121 = false;

	private static final boolean OUTDEGREE_OPTIM = false;
	private static final boolean RECOMPUTE_INDEGREE = true;
	private static final boolean START_NESTED_ALGS = true;
	private static final int NESTED_ALGS_DEPTH_LIMIT = 50;
	private static final boolean PARTIAL_COMPUTATION = false;
	private static final int PARTIAL_COMPUTATION_STATES_LIMIT = 10000;
	private static final boolean DISPLAY_PROGRESS = false;
	private static int MAX_STATES = 0;
	private static final int MAX_OWCTY_DEPTH = 50;

	private static int net_id, cluster_size;
	private static int max_owcty_depth;
	private static int nsccs;
	private static int scc_structure_size[];
	private static int scc_structure_count[];
	private static int ntrivsccs;
	private static final int global_indegree[][] = new int[MAX_OWCTY_DEPTH][];
	private static final int global_found[][] = new int[MAX_OWCTY_DEPTH][];
	private static final int prev_global_found[][] = new int[MAX_OWCTY_DEPTH][];
	private static final int global_visited[][] = new int[MAX_OWCTY_DEPTH][];

	private static final class my_queue_t {
		private int[] q;
		private int size;
		private int first;
		private int last;
		private int max_size;
		private int depth;
		private int type;

		private my_queue_t() {
		}

		private final void qinit() {
			first = 0;
			last = 0;
			size = 0;
		}

		private final int qpop(int id) {
			if (size <= 0) {
				fprintf(System.err, "qpop(, %d): Queue underflow %d   %d!\n", id, depth, type);
				fflush(System.err);
				throw new RuntimeException("Queue underflow " + depth + " " + type + " " + size + " " + max_size);
			}
			int ret = q[first];
			first = (first + 1) % max_size;
			size--;
			return ret;
		}

		private final void qpush(int elem, int id) {
			if (size >= max_size) {
				fprintf(System.err, "qpush(, %d): Queue overflow %d %d! (q size %d,q max size %d)\n", id, depth, type,
						size, max_size);
				fflush(System.err);
				throw new RuntimeException("Queue overflow: " + id + " " + " q size " + size + " < " + max_size);
			}
			q[last] = elem;
			last = (last + 1) % max_size;
			size++;
		}

		private final void qalloc(int max_size, int depth, int type) {
			this.q = new int[max_size];
			this.max_size = max_size;
			this.depth = depth;
			this.type = type;
		}
	};

	private enum alg_type_t {
		explorer, trimmer
	};

	public static interface SccNode extends Node {
		public void explore(alg_record_t ar);

		public void trim(alg_record_t ar);

		public void bwd(alg_record_t ar);

		public void fwd(alg_record_t ar);
	}

	public static final class SccLocalNode extends ExplicitLocalNode<SccNode> implements SccNode {

		public SccLocalNode(ExplicitGraph<SccNode> graph, int reference) {
			super(graph, reference);
		}

		public final void explore(alg_record_t ar) {
			if (prev_global_found[ar.depth] == null || prev_global_found[ar.depth][reference] == ar.getId()) {
				if (RECOMPUTE_INDEGREE && ar.depth != 0)
					global_indegree[ar.depth][reference]++;
				if (global_found[ar.depth][reference] == 0) {
					if (vverbose)
						System.out.println(Runtime.getRank() + ": explore alg=" + ar.getId() + " node=" + reference
								+ " global_visited=" + global_visited[ar.depth][reference] + " global_indegree="
								+ global_indegree[ar.depth][reference]);
					ar.queue_two.qpush(reference, 13);
					global_found[ar.depth][reference] = ar.iteration;
					for (int j = 0; hasNeighbor(j); j++)
						neighbor(j).explore(ar);
				}
			}
		}

		public final void trim(alg_record_t ar) {
			if ((prev_global_found[ar.depth] == null || prev_global_found[ar.depth][reference] == ar.getId())
					&& global_found[ar.depth][reference] == ar.iteration) {
				if (vverbose)
					System.out.println(Runtime.getRank() + ": trim alg=" + ar.getId() + " node=" + reference
							+ " global_visited=" + global_visited[ar.depth][reference] + " global_indegree="
							+ global_indegree[ar.depth][reference]);
				if (global_visited[ar.depth][reference] == 0) {
					ar.queue_two.qpush(reference, 14);
					global_visited[ar.depth][reference] = 1;
				}
				if (global_indegree[ar.depth][reference] > 0) {
					global_indegree[ar.depth][reference]--;
					if (global_indegree[ar.depth][reference] == 0) {
						for (int j = 0; hasNeighbor(j); j++)
							neighbor(j).trim(ar);
					}
				}
			}
		}

		public final void bwd(alg_record_t ar) {
			if ((prev_global_found[ar.depth] == null || prev_global_found[ar.depth][reference] == ar.getId())
					&& global_found[ar.depth][reference] == ar.iteration) {
				if (global_visited[ar.depth][reference] == 0) {
					if (vverbose)
						System.out.println(Runtime.getRank() + ": bwd alg=" + ar.getId() + " node=" + reference
								+ " visited=" + global_visited[ar.depth][reference]);
					ar.queue_one.qpush(reference, 16);
					global_visited[ar.depth][reference] = 1;
					for (int j = 0; hasInNeighbor(j); j++)
						inNeighbor(j).bwd(ar);
				}
			}
		}

		public final void fwd(alg_record_t ar) {
			if ((prev_global_found[ar.depth] == null || prev_global_found[ar.depth][reference] == ar.getId())
					&& global_found[ar.depth][reference] == ar.iteration) {
				if (vverbose)
					System.out.println(Runtime.getRank() + ": fwd alg=" + ar.getId() + " node=" + reference
							+ " global_visited=" + global_visited[ar.depth][reference] + " global_indegree="
							+ global_indegree[ar.depth][reference]);
				if (global_visited[ar.depth][reference] == 0) {
					global_indegree[ar.depth][reference]--;
					if (global_indegree[ar.depth][reference] < 0) {
						printf("%d: R1NEGATIVE INDEGREE, depth = %d, s2 = %d\n", net_id, ar.depth, reference);
						fflush(System.out);
					}
					ar.queue_two.qpush(reference, 17);
					global_visited[ar.depth][reference] = 2;
				} else if (global_visited[ar.depth][reference] == 2) {
					global_indegree[ar.depth][reference]--;
					if (global_indegree[ar.depth][reference] < 0) {
						printf("%d: R2NEGATIVE INDEGREE, depth = %d, s2 = %d\n", net_id, ar.depth, reference);
						fflush(System.out);
					}

				}
			}
		}

	}

	public static final class alg_record_t extends hipg.runtime.Synchronizer {
		private final ExplicitGraph<SccNode> g;
		private final alg_type_t algtype;

		private boolean ihaveunexploredvertex;
		private int first_unexplored_idx;
		private int first_unexplored_queue_idx;
		private final int depth;
		private int iteration;
		private int subiteration;
		private int candidate_net_id;
		private int min_candidate_net_id;
		private int sum_qone_size;
		private int sum_qtwo_size;
		private int sum_qsource_size;
		private final my_queue_t source_queue;
		private final my_queue_t queue_one;
		private final my_queue_t queue_two;

		// private int update_fun = fun_sync_struct_none;

		public alg_record_t(ExplicitGraph<SccNode> g, alg_type_t algtype, int depth) {
			this.g = g;
			source_queue = new my_queue_t();
			queue_one = new my_queue_t();
			queue_two = new my_queue_t();
			this.depth = depth;
			this.algtype = algtype;
		}

		@Override
		public String toString() {
			return "id=" + getId() + "type=" + algtype.toString() + ",unexpl.vert=" + ihaveunexploredvertex + ",depth="
					+ depth + ",iteration=" + iteration + ",subiteration=" + subiteration;
		}

		// public final int propagate(int ss) {
		// // System.out.println(net_id + " propagate " + update_fun);
		// switch (update_fun) {
		// case fun_sync_struct_none:
		// break;
		// case fun_sync_struct_min_candidate:
		// process_sync_struct_min_candidate(ss);
		// break;
		// case fun_sync_struct_sum_qfwd:
		// process_sync_struct_sum_qfwd(ss);
		// break;
		// case fun_sync_struct_sum_qbwd:
		// process_sync_struct_sum_qbwd(ss);
		// break;
		// case fun_sync_struct_sum_qsource:
		// process_sync_struct_sum_qsource(ss);
		// break;
		// default:
		// throw new RuntimeException("Unknown sync struct function: "
		// + update_fun);
		// }
		// return ss;
		// }

		// @BarrierAndReduce2
		// private int updateBarr(int ss) {
		// return doUpdate(ss);
		// }
		//
		// @Reduce
		// private int updateRed(int ss) {
		// return doUpdate(ss);
		// }
		//
		// private int doUpdate(int ss) {
		// switch (update_fun) {
		// case fun_sync_struct_min_candidate:
		// return update_sync_struct_min_candidate(ss);
		// case fun_sync_struct_sum_qfwd:
		// return update_sync_struct_sum_qfwd(ss);
		// case fun_sync_struct_sum_qbwd:
		// return update_sync_struct_sum_qbwd(ss);
		// case fun_sync_struct_sum_qsource:
		// return update_sync_struct_sum_qsource(ss);
		// default:
		// throw new RuntimeException("Unknown sync struct function: "
		// + update_fun);
		// }
		// }

		@Reduce
		public final int update_sync_struct_min_candidate(int value) {
			// System.out.println(net_id + " update_sync_struct_min_candidate "
			// + candidate_net_id);
			return imin(value, candidate_net_id);
		}

		@BarrierAndReduce
		public final int update_sync_struct_sum_qfwd(int value) {
			// System.out.println(net_id + " update " + update_fun +
			// " with val "+ queue_one.size);
			return value + queue_one.size;
		}

		@BarrierAndReduce
		public final int update_sync_struct_sum_qbwd(int value) {
			// System.out.println(net_id + " update_sync_struct_sum_qbwd "
			// + +queue_two.size);
			return value + queue_two.size;
		}

		@BarrierAndReduce
		public final int update_sync_struct_sum_qsource(int value) {
			// System.out.println(net_id + " update " + update_fun +
			// " with val "+ source_queue.size);
			return value + source_queue.size;
		}

		private final void process_sync_struct_min_candidate(int value) {
			min_candidate_net_id = value;
		}

		private final void process_sync_struct_sum_qfwd(int value) {
			sum_qone_size = value;
		}

		private final void process_sync_struct_sum_qbwd(int value) {
			sum_qtwo_size = value;
		}

		private final void process_sync_struct_sum_qsource(int value) {
			sum_qsource_size = value;
		}

		int bwd_fill = 0;

		@Override
		public void run() {
			if (algtype == alg_type_t.explorer) {

				/* explorer */

				if (verbose && net_id == 0)
					System.out.println(net_id + ": Alg=" + getId() + " starting explorer father=" + getFatherId()
							+ " source size=" + source_queue.size);
				if (prev_global_found[depth] != null) {
					for (int i = 0; i < source_queue.size; i++) {
						int s1 = source_queue.qpop(3);
						source_queue.qpush(s1, 7);
						prev_global_found[depth][s1] = getId();
					}
				}

				while (true) {

					// search for vertex
					if (ihaveunexploredvertex && global_found[depth][first_unexplored_idx] != 0) {
						ihaveunexploredvertex = false;
					}
					while (!ihaveunexploredvertex && first_unexplored_queue_idx < source_queue.size) {
						first_unexplored_idx = source_queue.qpop(7);
						// System.out.println("checking first unexplored vertex: "
						// + ar.first_unexplored_idx);
						source_queue.qpush(first_unexplored_idx, 20);
						first_unexplored_queue_idx++;
						if (global_found[depth][first_unexplored_idx] == 0) {
							if (!PARTIAL_COMPUTATION || first_unexplored_queue_idx < PARTIAL_COMPUTATION_STATES_LIMIT) {
								if (!OUTDEGREE_OPTIM || depth > 0 || g.node(first_unexplored_idx).outdegree() > 0) {
									ihaveunexploredvertex = true;
									break;
								} else {
									ntrivsccs++;
									global_found[depth][first_unexplored_idx] = iteration;
								}
							}
						}
					}
					queue_one.qinit();
					queue_two.qinit();
					candidate_net_id = ihaveunexploredvertex ? net_id : cluster_size;
					// update(ar.ihaveunexploredvertex ? net_id : cluster_size);

					process_sync_struct_min_candidate(update_sync_struct_min_candidate(cluster_size));

					// onsynchronized: as_start
					if (min_candidate_net_id >= cluster_size) {
						// vertex not found
						if (verbose && net_id == 0)
							System.out.println(net_id + ": Alg=" + getId() + " no global vertex found, explorer done");
						return;
					}

					// vertex found
					// ar.queue_one.qinit();
					// ar.queue_two.qinit();
					// update_fun = fun_sync_struct_sum_qbwd;
					if (min_candidate_net_id == net_id) {
						if (verbose)
							System.out.println(net_id + ": Alg=" + getId() + " initializing explore from vertex "
									+ first_unexplored_idx);

						global_found[depth][first_unexplored_idx] = iteration;
						// ar.queue_one.qpush(ar.first_unexplored_idx, 1);
						queue_two.qpush(first_unexplored_idx, 1);
						// explore
						SccLocalNode s = (SccLocalNode) g.node(first_unexplored_idx);

						for (int j = 0; s.hasNeighbor(j); j++)
							s.neighbor(j).explore(this);
					}
					// compute size of the explored chunk
					// update(0);
					process_sync_struct_sum_qbwd(update_sync_struct_sum_qbwd(0));

					// onsynchronized: as_explore
					if (verbose && net_id == 0)
						System.out.println(net_id + ": Alg=" + getId() + " explored chunk of size " + sum_qtwo_size
								+ (check121 && sum_qtwo_size % 121 != 0 ? "!!!!!!!!!!" : ""));

					if (START_NESTED_ALGS && depth < NESTED_ALGS_DEPTH_LIMIT) {
						alg_record_t newar = new alg_record_t(g, alg_type_t.trimmer, depth + 1);
						newar.iteration = 1;
						// newar.update_fun = fun_sync_struct_sum_qsource;
						if (max_owcty_depth < newar.depth) {
							max_owcty_depth = newar.depth;
							prev_global_found[newar.depth] = new int[MAX_STATES];
							global_visited[newar.depth] = new int[MAX_STATES];
							global_found[newar.depth] = new int[MAX_STATES];
							global_indegree[newar.depth] = new int[MAX_STATES];
						}
						newar.source_queue.qalloc(sum_qtwo_size, newar.depth, 0);
						newar.source_queue.qinit();
						newar.queue_one.qalloc(sum_qtwo_size, newar.depth, 1);
						newar.queue_one.qinit();
						newar.queue_two.qalloc(sum_qtwo_size, newar.depth, 2);
						newar.queue_two.qinit();
						for (int i = 0; i < queue_two.size; i++) {
							int s1 = queue_two.qpop(100);
							queue_two.qpush(s1, 101);
							newar.source_queue.qpush(s1, 102);
							// prev_global_found[newar.depth][s1] =
							// newar.getId();
							global_found[newar.depth][s1] = newar.iteration;
							global_indegree[newar.depth][s1] = global_indegree[depth][s1];
						}
						if (min_candidate_net_id == net_id) {
							global_visited[newar.depth][first_unexplored_idx] = 1;
							if (global_indegree[newar.depth][first_unexplored_idx] == 0) {
								newar.queue_one.qpush(first_unexplored_idx, 104);
								newar.queue_two.qpush(first_unexplored_idx, 105);
							} else {
								newar.queue_two.qpush(first_unexplored_idx, 106);
							}
						}
						spawn(newar);

						iteration++;
						queue_one.qinit();
						queue_two.qinit();
						// update_fun = fun_sync_struct_min_candidate;
					}

				}
			} else {

				/* trimmer */

				int alg_id = getId();

				if (verbose && net_id == 0)
					System.out.println(net_id + ": Alg=" + getId() + " starting trimmer father=" + getFatherId());
				for (int i = 0; i < source_queue.size; i++) {
					int s1 = source_queue.qpop(100);
					source_queue.qpush(s1, 101);
					prev_global_found[depth][s1] = alg_id;
				}

				while (true) {
					while (queue_one.size > 0) {
						int s1 = queue_one.qpop(9);
						queue_two.qpush(s1, 1355354);
						if (global_indegree[depth][s1] == 0) {
							SccLocalNode s = (SccLocalNode) g.node(s1);
							for (int j = 0; s.hasNeighbor(j); j++)
								s.neighbor(j).trim(this);
						}
					}
					// compute sum_qsource
					// update(0);
					process_sync_struct_sum_qsource(update_sync_struct_sum_qsource(0));
					// as_trim: onsynchronized : synchronization after
					// ar.queue_one.qinit();
					if (DISPLAY_PROGRESS && alg_id > 0) {
						printf("%d: BEFOREBWD: alg_id = %d, qtwo_size = %d\n", net_id, alg_id, queue_two.size);
						fflush(System.out);
					}
					int trimmed = 0;
					int reached = 0;

					while (queue_two.size > 0) {
						int s1 = queue_two.qpop(1);
						if (global_indegree[depth][s1] == 0) {
							ntrivsccs++;
							trimmed++;
						} else {
							reached++;
							// ar.queue_one.qpush(s1, 6);
							// ar.queue_two.qpush(s1, 25);
							queue_one.qpush(s1, 25);
							SccLocalNode s = (SccLocalNode) g.node(s1);
							for (int j = 0; s.hasInNeighbor(j); j++)
								s.inNeighbor(j).bwd(this);

							if (DISPLAY_PROGRESS && alg_id > 0) {
								printf("%d: alg_id = %d, bwdseed = %d\n", net_id, alg_id, s1);
								fflush(System.out);
							}
						}
					}
					// ar.update_fun = sync_struct_fun.fun_sync_struct_sum_qbwd;
					// update_fun = fun_sync_struct_sum_qfwd;
					if (DISPLAY_PROGRESS) {
						printf("%d: BWD %d\n", net_id, alg_id);
						fflush(System.out);
					}
					// while (ar.queue_one.size > 0) {
					// int s1 = ar.queue_one.qpop(10);
					// ar.queue_two.qpush(s1, 25);
					// SccLocalNode s = (SccLocalNode) g.node(s1);
					// for (SccNode n : s.inNeighbors())
					// call_bwd(n, this);
					// }
					// compute sum_qbwd (queueu_two.size)
					// actually sum_qfwd (queue_one.size) after changing
					// update(0);
					process_sync_struct_sum_qfwd(update_sync_struct_sum_qfwd(0));

					int bwd_size = sum_qone_size;
					if (verbose && net_id == 0)
						System.out.println(net_id + ": Alg=" + getId() + " computed bwd of size " + bwd_size
								+ " (of chunk of size " + sum_qsource_size + ")");
					bwd_fill += bwd_size;
					if (check121 && bwd_size % 121 != 0)
						System.out.println(net_id + ":Alg=" + getId() + " bwd size " + bwd_size
								+ " is not multiplicity of 121 !!!!!!!!!!!!!!!!!!!!!!!!!! locall " + queue_one.size);
					// as_bwd: onsynchronized
					// if (ar.sum_qsource_size == ar.sum_qtwo_size) {
					if (sum_qsource_size == bwd_size) {
						nsccs++;
						int i = 0;
						while (scc_structure_count[i] != 0) {
							if (scc_structure_size[i] == sum_qsource_size) {
								scc_structure_count[i]++;
								break;
							}
							i++;
						}
						if (scc_structure_count[i] == 0) {
							scc_structure_size[i] = sum_qsource_size;
							scc_structure_count[i]++;
						}
						if (verbose)
							System.out.println(net_id + ": Alg=" + getId() + " found SCC of size " + sum_qsource_size);
						if (DISPLAY_PROGRESS) {
							printf("%d: %d DETECTED COMPONENT OF SIZE %d\n", net_id, alg_id, sum_qsource_size);
							fflush(System.out);
						}

						return;
					}

					if (START_NESTED_ALGS && depth < NESTED_ALGS_DEPTH_LIMIT && bwd_size > 0) {

						alg_record_t newar = new alg_record_t(g, alg_type_t.explorer, depth + 1);
						newar.iteration = 1;
						// newar.update_fun = fun_sync_struct_min_candidate;

						if (max_owcty_depth < newar.depth) {
							max_owcty_depth = newar.depth;
							prev_global_found[newar.depth] = new int[MAX_STATES];
							global_visited[newar.depth] = new int[MAX_STATES];
							global_found[newar.depth] = new int[MAX_STATES];
							global_indegree[newar.depth] = new int[MAX_STATES];

						}
						newar.source_queue.qalloc(bwd_size, newar.depth, 0);
						newar.source_queue.qinit();
						newar.queue_one.qalloc(bwd_size, newar.depth, 1);
						newar.queue_one.qinit();
						newar.queue_two.qalloc(bwd_size, newar.depth, 2);
						newar.queue_two.qinit();
						for (int i = 0; i < queue_one.size; i++) {
							int s1 = queue_one.qpop(3);
							queue_one.qpush(s1, 7);
							newar.source_queue.qpush(s1, 8);
							if (!RECOMPUTE_INDEGREE)
								global_indegree[newar.depth][s1] = global_indegree[depth][s1];
						}
						spawn(newar);
					}
					// ar.queue_one.qinit();
					// ar.queue_one.qinit();
					// ar.update_fun = sync_struct_fun.fun_sync_struct_sum_qfwd;
					// update_fun = fun_sync_struct_sum_qbwd;
					if (DISPLAY_PROGRESS) {
						printf("%d: FWD %d\n", net_id, alg_id);
						fflush(System.out);
					}
					// while (ar.queue_two.size > 0) {
					while (queue_one.size > 0) {
						// int s1 = ar.queue_two.qpop(12);
						int s1 = queue_one.qpop(12);
						SccLocalNode s = (SccLocalNode) g.node(s1);
						for (int j = 0; s.hasNeighbor(j); j++)
							s.neighbor(j).fwd(this);
					}
					// compute sum_qfwd (sum of queue_one.size)
					// actually sum_qbwd
					// update(0);

					process_sync_struct_sum_qbwd(update_sync_struct_sum_qbwd(0));

					// as_fwd: onsynchronized
					if (verbose && net_id == 0)
						System.out.println(net_id + ": Alg=" + getId() + " computed fwd of size " + sum_qtwo_size
								+ ". Progress " + bwd_fill + "/" + sum_qsource_size);
					if (sum_qtwo_size == 0) {
						if (bwd_fill != sum_qsource_size)
							System.out.println("!!!!! problem sum of found bwd sets " + bwd_fill
									+ " differs from original source size " + sum_qsource_size
									+ " when found empty fwd ");
						return;
					}
					int orig_qsize = queue_two.size;
					for (int i = 0; i < orig_qsize; i++) {
						int s1 = queue_two.qpop(4);
						if (global_indegree[depth][s1] == 0)
							queue_one.qpush(s1, 10);
						else
							queue_two.qpush(s1, 10235235);
						if (DISPLAY_PROGRESS && alg_id > 0) {
							printf("%d: alg_id = %d, NEW bwdseed = %d, qtwo_size = %d\n", net_id, alg_id, s1,
									queue_two.size);
							fflush(System.out);
						}
					}
					// update_fun = fun_sync_struct_none;
					if (DISPLAY_PROGRESS) {
						printf("%d: TRIM %d\n", net_id, alg_id);
						fflush(System.out);
					}
					subiteration++;
					barrier();
				}
			}
		}

	}

	private static final int imin(int a, int b) {
		return (a < b ? a : b);
	}

	private static final void printf(String format, Object... args) {
		System.out.printf(format, args);
	}

	private static final void fprintf(PrintStream stream, String format, Object... args) {
		stream.printf(format, args);
	}

	private static final void fflush(PrintStream stream) {
		stream.flush();
	}

	public static void main(String[] args) throws GraphCreationException {

		if (args.length < 2) {
			System.err.println(owctypa3.class.getName() + " <graph>");
			System.err.println("where graph can be specifiec as one of the following:");
			System.err.println(GraphIO.formatSpecificationMessage());
			System.exit(1);
		}
		String format = args[0];
		String path = args[1];
		int poolSize = Config.POOLSIZE;

		/* read graph */
		if (Runtime.getRank() == 0)
			System.out.println("Reading graph " + path);
		long readingStart = System.nanoTime();
		final ExplicitGraph<SccNode> g = hipg.format.GraphIO.readUndirected(SccLocalNode.class, SccNode.class, format,
				path, poolSize);
		long readingTime = System.nanoTime() - readingStart;
		if (Runtime.getRank() == 0)
			System.out.println("Graph with " + g.getGlobalSize() + " nodes read in "
					+ ConversionUtils.ns2sec(readingTime) + "s");

		/* prepare OBFR-MP */
		net_id = Runtime.getRank();
		cluster_size = Runtime.getPoolSize();
		MAX_STATES = g.nodes();
		System.out.println("MAX_STATES = " + g.getGlobalSize());
		global_indegree[0] = new int[g.nodes()];
		printf("%d: states = %d\n", net_id, g.nodes());
		fflush(System.out);
		int transitions = 0;
		for (int i = 0; i < g.nodes(); i++)
			transitions += g.node(i).outdegree();
		printf("%d: transitions = %d\n", net_id, transitions);
		fflush(System.out);

		scc_structure_size = new int[MAX_STATES];
		scc_structure_count = new int[MAX_STATES];

		printf("%d: CE:\n", net_id);
		fflush(System.out);

		max_owcty_depth = 0;
		nsccs = 0;
		ntrivsccs = 0;

		global_visited[0] = new int[MAX_STATES];
		global_found[0] = new int[MAX_STATES];
		alg_record_t mainAlg = new alg_record_t(g, alg_type_t.explorer, 0);

		mainAlg.iteration = 1;
		// mainAlg.update_fun = fun_sync_struct_min_candidate;

		mainAlg.source_queue.qalloc(MAX_STATES, 0, 0);
		mainAlg.source_queue.qinit();

		mainAlg.queue_one.qalloc(MAX_STATES, 0, 1);
		mainAlg.queue_one.qinit();

		mainAlg.queue_two.qalloc(MAX_STATES, 0, 2);
		mainAlg.queue_two.qinit();

		for (int i = 0; i < g.nodes(); i++)
			mainAlg.source_queue.qpush(i, 18);

		if (DISPLAY_PROGRESS) {
			printf("%d: START 0\n", net_id);
			fflush(System.out);
		}

		/* global_indegree */
		for (int i = 0; i < g.nodes(); i++) {
			SccLocalNode n = (SccLocalNode) g.node(i);
			global_indegree[0][i] = n.indegree();
		}

		/* OBFR-MP */
		Runtime.getRuntime().barrier();
		long start = System.nanoTime();
		Runtime.getRuntime().spawnAll(mainAlg);
		Runtime.getRuntime().barrier();
		long time = System.nanoTime() - start;

		/* results */
		if (Runtime.getRank() == 0) {
			System.out.println("FB on " + Runtime.getPoolSize() + " processors done in " + ConversionUtils.ns2sec(time)
					+ "s");
			if (ntrivsccs > 0)
				System.out.println("Found " + ntrivsccs + " SCCs of size 1");
			for (int i = 0; i < scc_structure_count.length; i++) {
				if (scc_structure_count[i] > 0) {
					System.out.println("Found " + scc_structure_count[i] + " SCCs of size " + scc_structure_size[i]);
				}
			}
		}
	}

}


text:
"use strict";

class gsuiTracklist extends HTMLElement {
	#tracks = new Map();

	constructor() {
		super();
		Object.seal( this );

		this.oncontextmenu = () => false;
		this.onchange = this.#onchange.bind( this );
		this.onkeydown = this.#onkeydown.bind( this );
		this.ondblclick = this.#ondblclick.bind( this );
		this.onmousedown = this.#onmousedown.bind( this );
		this.addEventListener( "focusout", this.#onfocusout.bind( this ) );
	}

	// .........................................................................
	getTrack( id ) {
		return this.#tracks.get( id );
	}
	addTrack( id ) {
		const tr = GSUI.$createElement( "gsui-track", { "data-id": id } );

		tr.rowElement.dataset.id = id;
		this.#tracks.set( id, tr );
		this.append( tr );
		return tr;
	}
	removeTrack( id ) {
		const tr = this.#tracks.get( id );

		tr.remove();
		tr.rowElement.remove();
		this.#tracks.delete( id );
	}

	// .........................................................................
	#onkeydown( e ) {
		const inp = e.target;

		if ( inp.dataset.action === "rename" ) {
			e.stopPropagation();
			switch ( e.key ) {
				case "Escape": inp.value = GSUI.$getAttribute( inp.parentNode.parentNode, "name" );
				case "Enter": inp.blur();
			}
		}
	}
	#onfocusout( e ) {
		if ( e.target.dataset.action === "rename" ) {
			e.target.disabled = true;
		}
	}
	#onchange( e ) {
		const inp = e.target;
		const id = inp.parentNode.parentNode.dataset.id;
		const name = inp.value.trim();

		inp.disabled = true;
		GSUI.$dispatchEvent( this, "gsuiTracklist", "renameTrack", id, name );
	}
	#ondblclick( e ) {
		const inp = e.target;

		if ( inp.dataset.action === "rename" ) {
			inp.disabled = false;
			inp.select();
			inp.focus();
		}
	}
	#onmousedown( e ) {
		if ( e.target.dataset.action === "toggle" ) {
			const par = e.target.parentNode;
			const id = par.dataset.id;

			if ( e.button === 2 ) {
				GSUI.$dispatchEvent( this, "gsuiTracklist", "toggleSoloTrack", id );
			} else if ( e.button === 0 ) {
				GSUI.$dispatchEvent( this, "gsuiTracklist", "toggleTrack", id );
			}
		}
	}
}

Object.freeze( gsuiTracklist );
customElements.define( "gsui-tracklist", gsuiTracklist );

redpajama_set_name: RedPajamaGithub


text:
.. _testservers:

Test Servers
============

Test Server 1-3
---------------

Deployment via Bamboo. Only for branches of the ``ls1intum/Artemis`` repository, no forks.
Guide available in the Artemis Developer Confluence Space: `Deploying changes to test server`_.

.. _`Deploying changes to test server`: https://confluence.ase.in.tum.de/display/Artemis/Deploying+changes+to+test+server

Test Server 5
-------------

Pull requests on GitHub can be deployed to TS5_, including forks.
To invoke a deployment, you need to be part of the `@ls1intum/artemis-developers` GitHub team.

#. Waiting for build to finish

    .. figure:: testservers/actions-deploy-wait-for-build.png
        :alt: GitHub Actions UI: Waiting for build to finish

#. Deployment waiting for approval

    .. figure:: testservers/actions-deploy-wait-for-approval.png
        :alt: GitHub Actions UI: Deployment waiting for approval

#. Review Deployment

    .. figure:: testservers/actions-deploy-review-deployment.png
        :alt: GitHub Actions UI: Review Deployment

#. Deployment done

    .. figure:: testservers/actions-deploy-done.png
        :alt: GitHub Actions UI: Deployment done

Start the deployment by reviewing the `Build & Deploy` action.
(Refer to the `GitHub documentation "Reviewing deployments"`_.)
TS5 is locked to a pull request using the `lock:artemistest5`_ label.
The workflow applies the lock label automatically on deployment.
Remove the label from the PR once the test server is free to use by other developers.

.. _TS5: https://artemistest5.ase.in.tum.de
.. _`GitHub documentation "Reviewing deployments"`: https://docs.github.com/en/actions/managing-workflow-runs/reviewing-deployments
.. _`lock:artemistest5`: https://github.com/ls1intum/Artemis/pulls?q=is%3Aopen+is%3Apr+label%3Alock%3Aartemistest5


text:
package org.apache.asterix.test.jsonplan;

import java.io.File;

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class JsonOptimizedLogicalPlanTest extends JsonLogicalPlanTest {

    public JsonOptimizedLogicalPlanTest(File queryFile, File actualFile) {
        super(queryFile, actualFile);
        optimized = true;
        PATH_ACTUAL = "target" + File.separator + "joptplantest" + SEPARATOR;
    }
}


text:
import styled from 'styled-components'

const Test = styled.div`
  width: 100%;
`
const Test2 = styled('div')``
const Test3 = true ? styled.div`` : styled.div``
const styles = { One: styled.div`` }
let Component
Component = styled.div``
const WrappedComponent = styled(Inner)``
const StyledObjectForm = styled.div({ color: red })
const StyledFunctionForm = styled.div(p => ({ color: p.color || 'red' }))
const normalFunc = add(5, 3)


text:
import asyncio
import os
import threading
import subprocess
import concurrent.futures
import sys
import logging
import warnings

from pyshark import ek_field_mapping
from pyshark.packet.packet import Packet
from pyshark.tshark.output_parser import tshark_ek
from pyshark.tshark.output_parser import tshark_json
from pyshark.tshark.output_parser import tshark_xml
from pyshark.tshark.tshark import get_process_path, get_tshark_display_filter_flag, \
    tshark_supports_json, TSharkVersionException, get_tshark_version, tshark_supports_duplicate_keys

if sys.version_info < (3, 8):
    asyncTimeoutError = concurrent.futures.TimeoutError
else:
    asyncTimeoutError = asyncio.exceptions.TimeoutError

class TSharkCrashException(Exception):
    pass

class UnknownEncyptionStandardException(Exception):
    pass

class RawMustUseJsonException(Exception):
    """If the use_raw argument is True, so should the use_json argument"""

class StopCapture(Exception):
    """Exception that the user can throw anywhere in packet-handling to stop the capture process."""
    pass

class Capture:
    """Base class for packet captures."""
    SUMMARIES_BATCH_SIZE = 64
    DEFAULT_LOG_LEVEL = logging.CRITICAL
    SUPPORTED_ENCRYPTION_STANDARDS = ["wep", "wpa-pwk", "wpa-pwd", "wpa-psk"]

    def __init__(self, display_filter=None, only_summaries=False, eventloop=None,
                 decryption_key=None, encryption_type="wpa-pwd", output_file=None,
                 decode_as=None,  disable_protocol=None, tshark_path=None,
                 override_prefs=None, capture_filter=None, use_json=False, include_raw=False,
                 use_ek=False, custom_parameters=None, debug=False):

        self.loaded = False
        self.tshark_path = tshark_path
        self._override_prefs = override_prefs
        self.debug = debug
        self.use_json = use_json
        self._use_ek = use_ek
        self.include_raw = include_raw
        self._packets = []
        self._current_packet = 0
        self._display_filter = display_filter
        self._capture_filter = capture_filter
        self._only_summaries = only_summaries
        self._output_file = output_file
        self._running_processes = set()
        self._decode_as = decode_as
        self._disable_protocol = disable_protocol
        self._log = logging.Logger(
            self.__class__.__name__, level=self.DEFAULT_LOG_LEVEL)
        self._closed = False
        self._custom_parameters = custom_parameters
        self._eof_reached = False
        self._last_error_line = None
        self._stderr_handling_tasks = []
        self.__tshark_version = None

        if include_raw and not (use_json or use_ek):
            raise RawMustUseJsonException(
                "use_json/use_ek must be True if include_raw")

        if self.debug:
            self.set_debug()

        self.eventloop = eventloop
        if self.eventloop is None:
            self._setup_eventloop()
        if encryption_type and encryption_type.lower() in self.SUPPORTED_ENCRYPTION_STANDARDS:
            self.encryption = (decryption_key, encryption_type.lower())
        else:
            raise UnknownEncyptionStandardException("Only the following standards are supported: %s."
                                                    % ", ".join(self.SUPPORTED_ENCRYPTION_STANDARDS))

    def __getitem__(self, item):
        """Gets the packet in the given index.

        :param item: packet index
        :return: Packet object.
        """
        return self._packets[item]

    def __len__(self):
        return len(self._packets)

    def next(self) -> Packet:
        return self.next_packet()

    # Allows for child classes to call next() from super() without 2to3 "fixing"
    # the call
    def next_packet(self) -> Packet:
        if self._current_packet >= len(self._packets):
            raise StopIteration()
        cur_packet = self._packets[self._current_packet]
        self._current_packet += 1
        return cur_packet

    def clear(self):
        """Empties the capture of any saved packets."""
        self._packets = []
        self._current_packet = 0

    def reset(self):
        """Starts iterating packets from the first one."""
        self._current_packet = 0

    def load_packets(self, packet_count=0, timeout=None):
        """Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.

        If 0 as the packet_count is given, reads forever

        :param packet_count: The amount of packets to add to the packet list (0 to read forever)
        :param timeout: If given, automatically stops after a given amount of time.
        """
        initial_packet_amount = len(self._packets)

        def keep_packet(pkt):
            self._packets.append(pkt)

            if packet_count != 0 and len(self._packets) - initial_packet_amount >= packet_count:
                raise StopCapture()

        try:
            self.apply_on_packets(
                keep_packet, timeout=timeout, packet_count=packet_count)
            self.loaded = True
        except asyncTimeoutError:
            pass

    def set_debug(self, set_to=True, log_level=logging.DEBUG):
        """Sets the capture to debug mode (or turns it off if specified)."""
        if set_to:
            handler = logging.StreamHandler(sys.stdout)
            handler.setFormatter(logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
            self._log.addHandler(handler)
            self._log.level = log_level
        self.debug = set_to

    def _verify_capture_parameters(self):
        """Optionally verify that the capture's parameters are valid.

        Should raise an exception if they are not valid.
        """
        pass

    def _setup_eventloop(self):
        """Sets up a new eventloop as the current one according to the OS."""
        if os.name == "nt":
            current_eventloop = asyncio.get_event_loop_policy().get_event_loop()
            if isinstance(current_eventloop, asyncio.ProactorEventLoop):
                self.eventloop = current_eventloop
            else:
                # On Python before 3.8, Proactor is not the default eventloop type, so we have to create a new one.
                # If there was an existing eventloop this can create issues, since we effectively disable it here.
                if asyncio.Task.all_tasks():
                    warnings.warn("The running eventloop has tasks but pyshark must set a new eventloop to continue. "
                                  "Existing tasks may not run.")
                self.eventloop = asyncio.ProactorEventLoop()
                asyncio.set_event_loop(self.eventloop)
        else:
            try:
                self.eventloop = asyncio.get_event_loop_policy().get_event_loop()
            except RuntimeError:
                if threading.current_thread() != threading.main_thread():
                    # Ran not in main thread, make a new eventloop
                    self.eventloop = asyncio.new_event_loop()
                    asyncio.set_event_loop(self.eventloop)
                else:
                    raise
            if os.name == "posix" and isinstance(threading.current_thread(), threading._MainThread):
                # The default child watchers (ThreadedChildWatcher) attach_loop method is empty!
                # While using pyshark with ThreadedChildWatcher, asyncio could raise a ChildProcessError
                # "Unknown child process pid %d, will report returncode 255"
                # This led to a TSharkCrashException in _cleanup_subprocess.
                # Using the SafeChildWatcher fixes this issue, but it is slower.
                # SafeChildWatcher O(n) -> large numbers of processes are slow
                # ThreadedChildWatcher O(1) -> independent of process number
                # asyncio.get_child_watcher().attach_loop(self.eventloop)
                asyncio.set_child_watcher(asyncio.SafeChildWatcher())
                asyncio.get_child_watcher().attach_loop(self.eventloop)

    def _packets_from_tshark_sync(self, packet_count=None, existing_process=None):
        """Returns a generator of packets.

        This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and
         reimplements reading packets in a sync way, yielding each packet as it arrives.

        :param packet_count: If given, stops after this amount of packets is captured.
        """
        # NOTE: This has code duplication with the async version, think about how to solve this
        tshark_process = existing_process or self.eventloop.run_until_complete(
            self._get_tshark_process())
        parser = self._setup_tshark_output_parser()
        packets_captured = 0

        data = b""
        try:
            while True:
                try:
                    packet, data = self.eventloop.run_until_complete(
                        parser.get_packets_from_stream(tshark_process.stdout, data,
                                                       got_first_packet=packets_captured > 0))

                except EOFError:
                    self._log.debug("EOF reached (sync)")
                    self._eof_reached = True
                    break

                if packet:
                    packets_captured += 1
                    yield packet
                if packet_count and packets_captured >= packet_count:
                    break
        finally:
            if tshark_process in self._running_processes:
                self.eventloop.run_until_complete(
                    self._cleanup_subprocess(tshark_process))

    def apply_on_packets(self, callback, timeout=None, packet_count=None):
        """Runs through all packets and calls the given callback (a function) with each one as it is read.

        If the capture is infinite (i.e. a live capture), it will run forever, otherwise it will complete after all
        packets have been read.

        Example usage:
        def print_callback(pkt):
            print(pkt)
        capture.apply_on_packets(print_callback)

        If a timeout is given, raises a Timeout error if not complete before the timeout (in seconds)
        """
        coro = self.packets_from_tshark(callback, packet_count=packet_count)
        if timeout is not None:
            coro = asyncio.wait_for(coro, timeout)
        return self.eventloop.run_until_complete(coro)

    async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):
        """
        A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and
        closes the process when it is done.

        Do not use interactively. Can be used in order to insert packets into your own eventloop.
        """
        tshark_process = await self._get_tshark_process(packet_count=packet_count)
        try:
            await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)
        except StopCapture:
            pass
        finally:
            if close_tshark:
                await self.close_async()

    async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
        """A coroutine which goes through a stream and calls a given callback for each XML packet seen in it."""
        packets_captured = 0
        self._log.debug("Starting to go through packets")

        parser = self._setup_tshark_output_parser()
        data = b""

        while True:
            try:
                packet, data = await parser.get_packets_from_stream(fd, data,
                                                                    got_first_packet=packets_captured > 0)
            except EOFError:
                self._log.debug("EOF reached")
                self._eof_reached = True
                break

            if packet:
                packets_captured += 1
                try:
                    packet_callback(packet)
                except StopCapture:
                    self._log.debug("User-initiated capture stop in callback")
                    break

            if packet_count and packets_captured >= packet_count:
                break

    def _create_stderr_handling_task(self, stderr):
        self._stderr_handling_tasks.append(asyncio.ensure_future(self._handle_process_stderr_forever(stderr)))

    async def _handle_process_stderr_forever(self, stderr):
        while True:
            stderr_line = await stderr.readline()
            if not stderr_line:
                break
            stderr_line = stderr_line.decode().strip()
            self._last_error_line = stderr_line
            self._log.debug(stderr_line)

    def _get_tshark_path(self):
        return get_process_path(self.tshark_path)

    def _get_tshark_version(self):
        if self.__tshark_version is None:
            self.__tshark_version = get_tshark_version(self.tshark_path)
        return self.__tshark_version

    async def _get_tshark_process(self, packet_count=None, stdin=None):
        """Returns a new tshark process with previously-set parameters."""
        self._verify_capture_parameters()

        output_parameters = []
        if self.use_json or self._use_ek:
            if not tshark_supports_json(self._get_tshark_version()):
                raise TSharkVersionException(
                    "JSON only supported on Wireshark >= 2.2.0")

        if self.use_json:
            output_type = "json"
            if tshark_supports_duplicate_keys(self._get_tshark_version()):
                output_parameters.append("--no-duplicate-keys")
        elif self._use_ek:
            output_type = "ek"
        else:
            output_type = "psml" if self._only_summaries else "pdml"
        parameters = [self._get_tshark_path(), "-l", "-n", "-T", output_type] + \
            self.get_parameters(packet_count=packet_count) + output_parameters

        self._log.debug(
            "Creating TShark subprocess with parameters: " + " ".join(parameters))
        self._log.debug("Executable: %s" % parameters[0])
        tshark_process = await asyncio.create_subprocess_exec(*parameters,
                                                              stdout=subprocess.PIPE,
                                                              stderr=subprocess.PIPE,
                                                              stdin=stdin)
        self._create_stderr_handling_task(tshark_process.stderr)
        self._created_new_process(parameters, tshark_process)
        return tshark_process

    def _created_new_process(self, parameters, process, process_name="TShark"):
        self._log.debug(
            process_name + f" subprocess (pid {process.pid}) created")
        if process.returncode is not None and process.returncode != 0:
            raise TSharkCrashException(
                "%s seems to have crashed. Try updating it. (command ran: '%s')" % (
                    process_name, " ".join(parameters)))
        self._running_processes.add(process)

    async def _cleanup_subprocess(self, process):
        """Kill the given process and properly closes any pipes connected to it."""
        self._log.debug(f"Cleanup Subprocess (pid {process.pid})")
        if process.returncode is None:
            try:
                process.kill()
                return await asyncio.wait_for(process.wait(), 1)
            except asyncTimeoutError:
                self._log.debug(
                    "Waiting for process to close failed, may have zombie process.")
            except ProcessLookupError:
                pass
            except OSError:
                if os.name != "nt":
                    raise
        elif process.returncode > 0:
            if process.returncode != 1 or self._eof_reached:
                raise TSharkCrashException(f"TShark (pid {process.pid}) seems to have crashed (retcode: {process.returncode}).\n"
                                           f"Last error line: {self._last_error_line}\n"
                                           "Try rerunning in debug mode [ capture_obj.set_debug() ] or try updating tshark.")

    def _setup_tshark_output_parser(self):
        if self.use_json:
            return tshark_json.TsharkJsonParser(self._get_tshark_version())
        if self._use_ek:
            ek_field_mapping.MAPPING.load_mapping(str(self._get_tshark_version()),
                                                  tshark_path=self.tshark_path)
            return tshark_ek.TsharkEkJsonParser()
        return tshark_xml.TsharkXmlParser(parse_summaries=self._only_summaries)

    def close(self):
        self.eventloop.run_until_complete(self.close_async())

    async def close_async(self):
        for process in self._running_processes.copy():
            await self._cleanup_subprocess(process)
        self._running_processes.clear()

        # Wait for all stderr handling to finish
        await asyncio.gather(*self._stderr_handling_tasks)

    def __del__(self):
        if self._running_processes:
            self.close()

    def __enter__(self): return self
    async def __aenter__(self): return self
    def __exit__(self, exc_type, exc_val, exc_tb): self.close()

    async def __aexit__(self, exc_type, exc_val,
                        exc_tb): await self.close_async()

    def get_parameters(self, packet_count=None):
        """Returns the special tshark parameters to be used according to the configuration of this class."""
        params = []
        if self._capture_filter:
            params += ["-f", self._capture_filter]
        if self._display_filter:
            params += [get_tshark_display_filter_flag(self._get_tshark_version(),),
                       self._display_filter]
        # Raw is only enabled when JSON is also enabled.
        if self.include_raw:
            params += ["-x"]
        if packet_count:
            params += ["-c", str(packet_count)]

        if self._custom_parameters:
            if isinstance(self._custom_parameters, list):
                params += self._custom_parameters
            elif isinstance(self._custom_parameters, dict):
                for key, val in self._custom_parameters.items():
                    params += [key, val]
            else:
                raise TypeError("Custom parameters type not supported.")

        if all(self.encryption):
            params += ["-o", "wlan.enable_decryption:TRUE", "-o", 'uat:80211_keys:"' + self.encryption[1] + '","' +
                                                                  self.encryption[0] + '"']
        if self._override_prefs:
            for preference_name, preference_value in self._override_prefs.items():
                if all(self.encryption) and preference_name in ("wlan.enable_decryption", "uat:80211_keys"):
                    continue  # skip if override preferences also given via --encryption options
                params += ["-o",
                           "{0}:{1}".format(preference_name, preference_value)]

        if self._output_file:
            params += ["-w", self._output_file]

        if self._decode_as:
            for criterion, decode_as_proto in self._decode_as.items():
                params += ["-d",
                           ",".join([criterion.strip(), decode_as_proto.strip()])]

        if self._disable_protocol:
            params += ["--disable-protocol", self._disable_protocol.strip()]

        return params

    def __iter__(self):
        if self.loaded:
            return iter(self._packets)
        else:
            return self._packets_from_tshark_sync()

    def __repr__(self):
        return "<%s (%d packets)>" % (self.__class__.__name__, len(self._packets))


text:
package com.sun.xml.ws.sdo.sample.service.types;

import commonj.sdo.Type;
import commonj.sdo.impl.HelperProvider;
import org.eclipse.persistence.sdo.SDODataObject;

@SuppressWarnings({"serial"})
public class GetTotalCompResponseElementImpl extends SDODataObject implements GetTotalCompResponseElement {

   public static String SDO_URI = "http://sdo.sample.service/types/";

   public GetTotalCompResponseElementImpl() {}

//   public Type getType() {
//      if(type == null){
//         Type lookupType = HelperProvider.getTypeHelper().getType(SDO_URI, "GetTotalCompResponseElement");
//         setType(lookupType);
//      }
//      return type;
//   }

   public java.math.BigDecimal getResult() {
      return (java.math.BigDecimal)get("result");
   }

   public void setResult(java.math.BigDecimal value) {
      set("result" , value);
   }

}


text:
if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

var BLAZE_DEBUG_MODE = false;
var API_KEYS = {
    BLAZE: "p3YZ1qDutpcBd7Bte2mcDw((",
    DEBUG: "2WQ5ksCzcYLeeYJ0qM4kHw(("
}

$(document).ready(function() {
    var apiEndpoint = "answers";
    var currentPage = 1;
    var pageSize = 100;
      var autorefresh_time = 1000000000; //crazy long == no refresh, because I'm lazy
      var autorefresh_timeout;
    var sort = ByCreationDate;
    var previousFlags;
    var previousFlagText = "";
    var highlightsOnly = true;

    $("#blaze-api-key-field").focus();
    InitSiteAPIKeyAutocomplete();

    var hasToken = false;

    var lochash = location.hash.substr(1);

    var site = lochash.substr(lochash.indexOf('site=')).split('&')[0].split('=')[1];

    if (site) {
        console.log("site: " + site);
        $("#blaze-api-key-field").val(site);
    }

    var token = lochash.substr(lochash.indexOf('access_token='))
                    .split('&')[0]
                    .split('=')[1];
    if (token) {
        console.log("saving token to localstorage: " + token);
        localStorage.setItem('access_token', token);
    }

    var token = localStorage.getItem('access_token');

    if (token) {
        SetAuthButtonText("Verifying...")

        $.ajax({
            type: "GET",
            url: "https://api.stackexchange.com/2.2/access-tokens/" + token,
            data: "key=" + BLAZE_DEBUG_MODE ? API_KEYS.DEBUG : API_KEYS.BLAZE + "",
            success: function(data) {
                console.log("success!")
                console.log(data);
                hasToken = true
                if (data["items"].length == 0) {
                    console.log("current token invalid")
                    localStorage.removeItem("access_token")
                    hasToken = false
                    SetAuthButtonText("Authenticate")
                }
                else {
                    SetAuthButtonText("Verified")
                }
            },
            error: function(data) {
                console.log("error!");
                console.log(data);
                ShowErrorWithMessage(JSON.parse(data.responseText).error_message);
            }
        });
    }

    $(document).on('click', 'a.flag-post-naa', function(e) {
        e.preventDefault();
        var $this = $(e.target)
        if (!$this.is('a.flag-post-naa')) {
          $this = $this.parents('a.flag-post-naa')
        }
        var postId = $this.attr("data-postid");
        var siteName = $this.attr("data-site");

        $.ajax({
            type: "GET",
            url: "https://api.stackexchange.com/2.2/answers/" + postId + "/flags/options",
            data: {
                'key': BLAZE_DEBUG_MODE ? API_KEYS.DEBUG : API_KEYS.BLAZE,
                'site': siteName,
                'access_token': token
            },
            success: function(data) {
                $("#flag_options_form").html("");
                $("#flag_options_form").html(RenderFlagOptions(data["items"]));

                $("#flag_modal").modal();

                $("#modal-flag-answer-button").attr("data-site-name", siteName);
                $("#modal-flag-answer-button").attr("data-post-id", postId);

                console.log(data);
            },
            error: function(data) {
                console.log("error!");
                console.log(data);
                ShowErrorWithMessage(JSON.parse(data.responseText).error_message);
            }
        });
    });

    function AutoRefresh() {
        RefreshData();
        autorefresh_timeout = setTimeout(AutoRefresh, autorefresh_time);
    }

    $(".autorefresh-option#autorefresh-none").click(function() {
        $(".autorefresh-option").removeClass("chosen");
        $(this).addClass("chosen");
        autorefresh_time = 10000000000;
        clearTimeout(autorefresh_timeout);
        autorefresh_timeout = setTimeout(AutoRefresh, autorefresh_time);
    });

    $(".autorefresh-option#autorefresh-10-seconds").click(function() {
        $(".autorefresh-option").removeClass("chosen");
        $(this).addClass("chosen");
        autorefresh_time = 10000;
        clearTimeout(autorefresh_timeout);
        autorefresh_timeout = setTimeout(AutoRefresh, autorefresh_time);
    });

    $(".autorefresh-option#autorefresh-30-seconds").click(function() {
        $(".autorefresh-option").removeClass("chosen");
        $(this).addClass("chosen");
        autorefresh_time = 30000;
        clearTimeout(autorefresh_timeout);
        autorefresh_timeout = setTimeout(AutoRefresh, autorefresh_time);
    });

    $(".autorefresh-option#autorefresh-5-minutes").click(function() {
        $(".autorefresh-option").removeClass("chosen");
        $(this).addClass("chosen");
        autorefresh_time = 300000;
        clearTimeout(autorefresh_timeout);
        autorefresh_timeout = setTimeout(AutoRefresh, autorefresh_time);
    });

    $(".dropdown li").click(function() {
        $(this).addClass("chosen");
        $(this).siblings("li").not(this).removeClass("chosen");
    });

    $(document).on("click", "#modal-flag-answer-button", function(e) {
        var $this = $(e.target)
        if (!$this.is('#modal-flag-answer-button')) {
          $this = $this.parents('#modal-flag-answer-button')
        }
        var postId = $this.attr("data-post-id");
        var postText = $("#answer_" + postId.toString()).text();
        var flagId = $('input[name=flag_type]:checked', '#flag_options_form').val();
        var site = $this.attr("data-site-name");

        $.ajax({
            type: "POST",
            url: "https://api.stackexchange.com/2.2/answers/" + postId + "/flags/add",
            data: {
                'key': BLAZE_DEBUG_MODE ? API_KEYS.DEBUG : API_KEYS.BLAZE,
                'site': site,
                'access_token': token,
                'option_id': flagId,
                'comment': ''
            },
            success: function(data) {
                console.log(data);
                $("#flag_modal").modal('hide')
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("error");
                console.log(data);
                ShowErrorWithMessage(jqXHR.responseText.error_message);
            }
        });
    });

    $(".blaze-logo").click(function() {
        $("table#datatable tr").remove();
        $(".blaze-header").fadeIn();
        $(".site-api-key-form").fadeIn();
        $("nav").fadeOut();
    });

    $("#select-answers").click(function() {
        $(".blaze-fetch-items").html("Fetch Answers");
        apiEndpoint = 'answers';
    });

    $("#select-comments").click(function() {
        $(".blaze-fetch-items").html("Fetch Comments");
        apiEndpoint = 'comments';
    });

    $("#select-questions").click(function() {
        $(".blaze-fetch-items").html("Fetch Questions");
        apiEndpoint = 'questions';
    });

    $("#select-users").click(function() {
        $(".blaze-fetch-items").html("Fetch Users");
        apiEndpoint = 'users';
    });

    $(".blaze-fetch-items").click(function() {
        RefreshData();
    });

    $(".authenticate-user-button").click(function() {
        var token = localStorage.getItem('access_token');

        SetAuthButtonText("Working...");

        if (token) {
            $.ajax({
                type: "GET",
                url: "https://api.stackexchange.com/2.2/access-tokens/" + token,
                data: {
                    'key': BLAZE_DEBUG_MODE ? API_KEYS.DEBUG : API_KEYS.BLAZE
                },
                success: function(data) {
                    if (data["items"].length == 0) {
                        console.log("current token invalid");
                        localStorage.removeItem("access_token");
                        window.open("https://stackexchange.com/oauth/dialog?client_id=2670&scope=write_access&redirect_uri=https://charcoal-se.org/blaze/index.html","_self");
                        SetAuthButtonText("Redirecting...");
                        hasToken = false;
                    }
                    else {
                        SetAuthButtonText("Verified");
                        hasToken = true;
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    ShowErrorWithMessage(jqXHR.responseText.error_message);
                }
            });
        }
        else {
            window.open("https://stackexchange.com/oauth/dialog?client_id=2670&scope=write_access&redirect_uri=https://charcoal-se.org/blaze/index.html", "_self")
        }
    });

    $(".refresh-current-data-button").click(function() {
        var oldHTML = $(this).html();
        $(this).html("working...");

        RefreshData(function() {
            $(".refresh-current-data-button").html(oldHTML);
        });
    });

    $(document).keypress(function(e) {
        if(e.which == 13) {
            RefreshData();
        }
    });

    function RefreshData(f) {
        RemoveErrorsAndWarnings();

        var site = $("#blaze-api-key-field").val();

        window.location.hash = "site=" + site;

        var oldButtonText = $(".blaze-fetch-items").html();
        $(".blaze-fetch-items").html("Loading...");

        var args = {
            'page': currentPage,
            'pagesize': pageSize,
            'key': BLAZE_DEBUG_MODE ? API_KEYS.DEBUG : API_KEYS.BLAZE,
            'site': site,
            'order': 'desc',
            'sort': 'creation',
            'filter': '!LeJQlFEfIbsDDTG1lReSJX'
        }

        if (apiEndpoint == "questions") args.filter = '!)Q7pHZaD2SW58N2KuVqkwvB5';
        if (apiEndpoint == "comments") args.filter = '!)Q3IqX*j)mxF9SKNRz3tb5yK';
        if (apiEndpoint == "users") args.filter = '!40.F89yKwjYalEn_s';

        var url = "https://api.stackexchange.com/2.2/" + apiEndpoint;
        $.ajax({
            type: "GET",
            url: url,
            data: args,
            success: function(data) {
                console.log("backoff: " + data["backoff"]);
                if (data["backoff"]) {
                    var backoff = parseInt(data["backoff"], 10);
                    if (backoff > 0) {
                        ShowWarningWithMessage("Backoff received: " + backoff + " seconds :(");
                    }
                }

                $(".blaze-header").fadeOut();
                $(".site-api-key-form").fadeOut();

                $("nav").fadeIn();

                var items = data["items"];

                items.sort(sort);

                $("table#datatable tr").remove();
                $(items).each(function(index, item) {
                    if (apiEndpoint == 'questions') {
                        $("table#datatable").append(RenderQuestion(item));
                    }
                    else if (apiEndpoint == 'answers') {
                        $("table#datatable").append(RenderAnswer(item, site));
                    }
                    else if (apiEndpoint == 'comments') {
                        $("table#datatable").append(RenderComment(item));
                    }
                    else if (apiEndpoint == 'users') {
                        $("table#datatable").append(RenderUser(item));
                    }
                });

                $(".blaze-fetch-items").html(oldButtonText);

                $("div.alert.alert-danger").remove();

                if (typeof(f) === "function") f();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                string = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
                string = string + jqXHR.responseText["error_message"].charAt(0).toUpperCase() + jqXHR.responseText["error_message"].slice(1);
                string = string + '
';
                $("div.alert.alert-danger").remove();
                $(".site-api-key-form").prepend(string);
                $(".blaze-fetch-items").html(oldButtonText);
                ShowErrorWithMessage(jqXHR.responseText["error_message"].charAt(0).toUpperCase() + jqXHR.responseText["error_message"].slice(1));
            }
        });
    }

    // Array sorting functions:

    function ByLength(a, b) {
        var aLength = a["body"].length;
        var bLength = b["body"].length;
        return ((aLength < bLength) ? -1 : ((aLength > bLength) ? 1 : 0));
    }

    function ByCreationDate(a, b) {
        var aDate = a["creation_date"];
        var bDate = b["creation_date"];
        return ((aDate > bDate) ? -1 : ((aDate < bDate) ? 1 : 0));
    }

    $("#sort-by-newest-creation").click(function() {
        sort = ByCreationDate;
        $("table#datatable tr").remove();
        $("#current-sort-indicator").html("Working...");
        RefreshData(function()
            {
                $("#current-sort-indicator").html("Newest");
            });
    });

    $("#sort-by-shortest-length").click(function() {
        sort = ByLength;
        console.log($("#current-sort-indicator"));
        $("table#datatable tr").remove();
        RefreshData(function()
            {
                $("#current-sort-indicator").html("Shortest");
            });
    });

    $("#highlights-enable").click(function() {
        highlightsOnly = true;
        RefreshData(function(){});
    });

    $("#highlights-disable").click(function() {
        highlightsOnly = false;
        RefreshData(function(){});
    });

    // Rendering things

    function RenderAnswer(item) {
        var string;
        var warningChecks = AnswerWarningHeuristics(item);
        if(warningChecks) {
            string = '

';
        }
        else {
            string = '

';
        }
        string = string + item["score"];
        string = string + '

';
        string = string + item["title"];
        string = string + '';
        string = string + '
';
        string += '';
        if(warningChecks) {
            string += 'Warning: ' + warningChecks;
        }
        string += '';
        string += '
';
        string = string + item["body"];
        string = string + ''
        var siteUrl = item["link"].split("/")[2];
        if (hasToken) {
            string = string + '
Flag on Site'
        }
        string = string + RenderUsercard(item["owner"], item);
        string = string + '

';
        string = string + '

'; //flag
        return string;
    }

    function RenderQuestion(item) {
        var string = '

';
        string = string + item["score"];
        string = string + '

';
        string = string + item["title"];
        string = string + '';
        string = string + "
";
        for (var i = 0; i < item["tags"].length; i++) {
            string = string + '' + item["tags"][i] + ' ';
        };
        string = string + "";
        string = string + '

';
        string = string + item["body"];
        var siteUrl = item["link"].split("/")[2];
        string = string + RenderUsercard(item["owner"], item);
        string = string + '

';
        return string;
    }

    function RenderComment(item) {
        var string = '

';
        if (item["score"] != "0") string = string + item["score"];
        string = string + '

';
        string = string + '';
        string = string + item["body"];
        string = string + ' - ';
        string = string + item["owner"]["display_name"];
        if (item["owner"]["user_type"] == 'moderator') string = string + " ♦";
        string = string + ' ';
        string = string + '

';
        return string;
    }

    function RenderUser(item) {
        var string = '
';
        string = string + RenderUsercard(item, item).replace("posted ", "created ");
        string = string + '

';
        string = string + (("about_me" in item) ? item["about_me"] : "-");
        string = string + '

';
        return string;
    }

    function RenderUsercard(user, item) {
        var string = "

posted ";
        string = string + '';
        string = string + "

";
        string = string + user["display_name"];
        if (user['user_type'] == 'moderator') string = string + ' ♦';
        string = string + "";
        string = string + "
";
        string = string + FormatRep(user["reputation"]);
        string = string + "";
        string = string + "

";
        return string;
    }

    function RenderFlagOptions(items) {
        string = "";

        $(items).each(function(index, item) {
            if(!item["has_flagged"]) {
                string = string + '<input type="radio" name="flag_type" value="' + item["option_id"] + '">'
                string = string + '' + item["title"] + '';
                string = string + '
' + item["description"] + '
';
            }
            else {
                string = string + '<input disabled type="radio" name="flag_type" value="' + item["option_id"] + '">';
                string = string + '' + item["title"] + '';
                string = string + '
you have already raised this type of flag
';
            }
            string = string + '
';
        });

        return string;
    }

    // Autocomplete things

    function InitSiteAPIKeyAutocomplete() {
        $.ajax({
            type: "GET",
            url: "https://api.stackexchange.com/2.2/sites",
            data: {
                'pagesize': 1000,
                'filter': '!mszzl.y_MC',
                'key': BLAZE_DEBUG_MODE ? API_KEYS.DEBUG : API_KEYS.BLAZE
            },
            success: function(data) {
                var items = data["items"];

                var siteApiKeys = [];

                jQuery.each(items, function(index, item) {
                    siteApiKeys.push(item["api_site_parameter"]);
                });

                $("#blaze-api-key-field").autocomplete({
                    source: siteApiKeys
                });
            },
            error: function(jqXHR, textStatus, errorThrown) {
                ShowErrorWithMessage(jqXHR.responseText.error_message);
            }
        });
    }

    $(".choose-site").click(function(e) {
        $("#blaze-api-key-field").val($(this).attr("id"));
        e.preventDefault();
    });

    function ShowWarningWithMessage(message) {
        RemoveErrorsAndWarnings();
        $(".navbar").before($("

", {
            'class': 'blaze-modal-warning'
        }).text(message).click(function() {
            $(this).slideUp(200);
        }));
    }

    function ShowErrorWithMessage(message) {
        RemoveErrorsAndWarnings();
        $(".navbar").before($("

", {
            'class': 'blaze-modal-error'
        })
        .text(message)
        .click(function() {
            $(this).slideUp(200);
        }));
    }

    function RemoveErrorsAndWarnings()     {
        $(".blaze-modal-error").each(function() {
            $(this).slideUp(200);
        });
        $(".blaze-modal-warning").each(function() {
            $(this).slideUp(200);
        });
    }

    function SetAuthButtonText(text) {
        $(".authenticate-user-button").html(' ' + text);
    }

    function FormatRep(reputation) {
        return Math.abs(Number(reputation)) >= 1.0e+4 ?
        (Math.abs(Number(reputation)) / 1.0e+3).toFixed(1) + "k" :
        Math.abs(Number(reputation));
    }

    // Experimental post-classifying heuristics

    function getKey(object, item) {
        for(var key in object) {
            if(object[key] == item) {
                return key;
            }
        }
        return null;
    }

    /**
     * Applies post-classifying heuristics for post warnings to an answer.
     * @param {object} item - The API-returned object representing the answer.
     * @returns {string||boolean} - If the post should be highlighted, the reason(s). If not, false.
     */
    function AnswerWarningHeuristics(item) {
        var answerText = item["body"];

        var checks = {
            "ContainsTelephone": function(text) {
                var matches = text.match(/[0-9\-\*]{7,15}/gi);
                if(matches) {
                    for(var match in matches) {
                        var formatted;
                        try {
                            formatted = phoneUtils.formatE164(match);
                        }
                        catch(e) {
                            continue;
                        }
                        var testCountries = ["US", "IN"];
                        for(var countryCode in testCountries) {
                            try {
                                if(phoneUtils.isPossibleNumber(formatted, countryCode)
                                    && phoneUtils.isValidNumber(formatted, countryCode)) return true;
                            }
                            catch(e) {}
                        }
                    }
                    return false;
                }
                else return false;
            },
            "ContainsEmail": function(text) {
                // Thanks voyager (http://stackoverflow.com/users/34813) (http://stackoverflow.com/a/1373724/3160466)
                return text.match(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gi);
            },
            "PostLengthUnderThreshold": function(text) {
                return text.length < 100;
            },
            "HighLinkProportion": function(text, item) {
                var proportionThreshold = 0.35;     // as in, max 35% of the answer can be links

                var id = item["answer_id"];

                var linkRegex = /(.*)<\/a>/gi;
                var matches = linkRegex.exec(text);

                if(matches) {
                    console.log("[AWC.HighLinkProportion] id " + id + " has matches:");
                    console.log(matches);
                    var linkLength = 0;

                    for(var i = 3; i < matches.length; i += 4) {    // This only matches link titles, not the entire HTML.
                        linkLength += matches[i].length;
                    }

                    return (linkLength / text.length) >= proportionThreshold;
                }
                else {
                    return false;
                }
            },
            "ContainsSignature": function(text, item) {
                return text.substr(-item["owner"]["display_name"].length) === item["owner"]["display_name"];
            },
            "MeTooAnswer": function(text) {
                return (text.match(/(how\s(can(\si)?|to)\s)?(fix|solve|answer)(\s\w+){0,3}\s(problem|question|issue)\?/gi) ||
                        text.match(/(i\s)?(have\s)?(the\s)?same\s((problem|question|issue)|here)/gi)) &&
                        !text.match(/(i\s)?(fixed|solved)\s(this|it)\s(problem|question|issue)?(by|when)/gi);
            },
            "ThanksAnswer": function(text) {
                return text.match(/thank(s)?(ing)?\s(you|to|@\w+)/gi) && text.match(/that\s(helped|solved)/gi);
            },
            "Can'tCommentAnswer": function(text) {
                return text.match(/(can't(\sadd(\sa)?)?|rep(utation)?(\sto)?)\scomment/gi);
            }
        };

        var checkHits = [];

        $.each(checks, function(index, value) {
            if(value(answerText, item)) {
                var matchedReason = getKey(checks, value);
                console.warn("Post ID " + item["answer_id"] + " matched warning '" + matchedReason + "'.");
                checkHits.push(getKey(checks, value));
            }
        });

        return checkHits.join(', ');
    }

});


text:
package demoapp.dom.types.primitive.doubles.jdo;

import javax.inject.Named;
import javax.jdo.annotations.DatastoreIdentity;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;

import org.springframework.context.annotation.Profile;

import org.apache.causeway.applib.annotation.DomainObject;
import org.apache.causeway.applib.annotation.Editing;
import org.apache.causeway.applib.annotation.Property;
import org.apache.causeway.applib.annotation.PropertyLayout;
import org.apache.causeway.applib.annotation.Title;

import lombok.Getter;
import lombok.Setter;

import demoapp.dom.types.primitive.doubles.persistence.PrimitiveDoubleEntity;

/* This file was GENERATED by the showcase generator (tooling). Do NOT edit! */
@Profile("demo-jdo")
//tag::class[]
@PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "demo")
@DatastoreIdentity(strategy = IdGeneratorStrategy.IDENTITY, column = "id")
@Named("demo.PrimitiveDoubleEntity")
@DomainObject
public class PrimitiveDoubleJdo                                          // <.>
        extends PrimitiveDoubleEntity {

//end::class[]
    public PrimitiveDoubleJdo(final double initialValue) {
        this.readOnlyProperty = initialValue;
        this.readWriteProperty = initialValue;
    }

//tag::class[]
    @Title(prepend = "double (primitive) JDO entity: ")
    @PropertyLayout(fieldSetId = "read-only-properties", sequence = "1")
    @Getter @Setter
    private double readOnlyProperty;                             // <.>

    @Property(editing = Editing.ENABLED)
    @PropertyLayout(fieldSetId = "editable-properties", sequence = "1")
    @Getter @Setter
    private double readWriteProperty;

}
//end::class[]


text:
class Presto < Formula
  desc "Distributed SQL query engine for big data"
  homepage "https://prestodb.io"
  url "https://search.maven.org/remotecontent?filepath=com/facebook/presto/presto-server/0.184/presto-server-0.184.tar.gz"
  sha256 "a08c42fc9bc87b74fb0eeb31dfc34f1f12993b40af1cf795c09b7ec0afd68182"

  bottle :unneeded

  depends_on :java => "1.8+"

  resource "presto-cli" do
    url "https://search.maven.org/remotecontent?filepath=com/facebook/presto/presto-cli/0.184/presto-cli-0.184-executable.jar"
    sha256 "12fcba5d731752b9d38f9be23cbf7a9eb023550d6528aed80aa1d54e8afe448c"
  end

  def install
    libexec.install Dir["*"]

    (libexec/"etc/node.properties").write <<-EOS.undent
      node.environment=production
      node.id=ffffffff-ffff-ffff-ffff-ffffffffffff
      node.data-dir=#{var}/presto/data
    EOS

    (libexec/"etc/jvm.config").write <<-EOS.undent
      -server
      -Xmx16G
      -XX:+UseG1GC
      -XX:G1HeapRegionSize=32M
      -XX:+UseGCOverheadLimit
      -XX:+ExplicitGCInvokesConcurrent
      -XX:+HeapDumpOnOutOfMemoryError
      -XX:+ExitOnOutOfMemoryError
    EOS

    (libexec/"etc/config.properties").write <<-EOS.undent
      coordinator=true
      node-scheduler.include-coordinator=true
      http-server.http.port=8080
      query.max-memory=5GB
      query.max-memory-per-node=1GB
      discovery-server.enabled=true
      discovery.uri=http://localhost:8080
    EOS

    (libexec/"etc/log.properties").write "com.facebook.presto=INFO"

    (libexec/"etc/catalog/jmx.properties").write "connector.name=jmx"

    (bin/"presto-server").write <<-EOS.undent
      #!/bin/bash
      exec "#{libexec}/bin/launcher" "$@"
    EOS

    resource("presto-cli").stage do
      bin.install "presto-cli-#{version}-executable.jar" => "presto"
    end
  end

  def post_install
    (var/"presto/data").mkpath
  end

  def caveats; <<-EOS.undent
    Add connectors to #{libexec}/etc/catalog/. See:
    https://prestodb.io/docs/current/connector.html
    EOS
  end

  plist_options :manual => "presto-server run"

  def plist; <<-EOS.undent
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
    "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>#{plist_name}</string>
        <key>RunAtLoad</key>
        <true/>
        <key>AbandonProcessGroup</key>
        <true/>
        <key>WorkingDirectory</key>
        <string>#{opt_libexec}</string>
        <key>ProgramArguments</key>
        <array>
          <string>#{opt_bin}/presto-server</string>
          <string>run</string>
        </array>
      </dict>
    </plist>
    EOS
  end

  test do
    system bin/"presto-server", "run", "--help"
    assert_equal "Presto CLI #{version}", shell_output("#{bin}/presto --version").chomp
  end
end


text:
#pragma once
#include <aws/redshift-serverless/RedshiftServerless_EXPORTS.h>
#include <aws/redshift-serverless/RedshiftServerlessRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace RedshiftServerless
{
namespace Model
{

  /**
   */
  class AWS_REDSHIFTSERVERLESS_API PutResourcePolicyRequest : public RedshiftServerlessRequest
  {
  public:
    PutResourcePolicyRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "PutResourcePolicy"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline const Aws::String& GetPolicy() const{ return m_policy; }

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline bool PolicyHasBeenSet() const { return m_policyHasBeenSet; }

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline void SetPolicy(const Aws::String& value) { m_policyHasBeenSet = true; m_policy = value; }

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline void SetPolicy(Aws::String&& value) { m_policyHasBeenSet = true; m_policy = std::move(value); }

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline void SetPolicy(const char* value) { m_policyHasBeenSet = true; m_policy.assign(value); }

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline PutResourcePolicyRequest& WithPolicy(const Aws::String& value) { SetPolicy(value); return *this;}

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline PutResourcePolicyRequest& WithPolicy(Aws::String&& value) { SetPolicy(std::move(value)); return *this;}

    /**
     *
The policy to create or update. For example, the following policy grants a
     * user authorization to restore a snapshot.

 "{\"Version\":
     * \"2012-10-17\", \"Statement\" : [{ \"Sid\": \"AllowUserRestoreFromSnapshot\",
     * \"Principal\":{\"AWS\": [\"739247239426\"]}, \"Action\":
     * [\"redshift-serverless:RestoreFromSnapshot\"] , \"Effect\": \"Allow\"
     * }]}"

     */
    inline PutResourcePolicyRequest& WithPolicy(const char* value) { SetPolicy(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline const Aws::String& GetResourceArn() const{ return m_resourceArn; }

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline PutResourcePolicyRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline PutResourcePolicyRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the account to create or update a resource
     * policy for.

     */
    inline PutResourcePolicyRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;}

  private:

    Aws::String m_policy;
    bool m_policyHasBeenSet = false;

    Aws::String m_resourceArn;
    bool m_resourceArnHasBeenSet = false;
  };

} // namespace Model
} // namespace RedshiftServerless
} // namespace Aws


text:
using System.Runtime.Remoting.Lifetime;
using RedGate.AppHost.Interfaces;

namespace RedGate.SSC.Windows.Remote.Services
{
    public interface ISsmsOperations : ISponsor
    {
        void CreateAugmentedQueryWindow(string sqlScript, string title, IRemoteElement remoteElement);
    }
}


text:
\documentclass{beamer}

\usetheme{Boulder}

\title{git and GitHub}
\subtitle{Using GitHub at MLSO}
\author{Michael D. Galloy}
\institute[NCAR/MLSO]{NCAR/HAO --- MLSO}

\date{4 October 2016}

\begin{document}

\begin{frame}{xkcd}
  \includegraphics[width=4in]{git_commit.png}
\end{frame}

\begin{frame}[plain]
  \titlepage
\end{frame}

\section{Introduction}
\subsection*{}

\begin{frame}
  \tableofcontents
\end{frame}

\section{git}

\subsection{Distributed revision control}
\begin{frame}{git is distributed}
  \begin{enumerate}
    \item no central repo (but we can act like it)
    \item each repo is self-contained (though might not have everything)
    \item can do work locally and choose what to share to others
  \end{enumerate}
  \begin{center}
    \includegraphics[width=3in]{drc.pdf}
  \end{center}
\end{frame}

\begin{frame}{Terminology/concepts}
  \begin{description}
    \item[stage] put local files in the staging area, ready for the next commit
    \item[commit] make a local commit
    \item[hash] revision ``number'' of a commit
    \item[remote] another git repo, such as {\em origin}
    \item[push/fetch/pull] transfer commits, tags, etc. between local repo and a remote
  \end{description}
\end{frame}

\subsection{Normal workflow}
\begin{frame}[fragile]
  \frametitle{Cloning a repo}
To ``checkout'' an existing repo:
  \begin{small}
  \begin{lstlisting}
git clone https://github.com/ncar-mlso/comp-pipeline.git
  \end{lstlisting}
  \end{small}
The remote you clone from is typically called the {\em origin}.

\vspace{1em}

Upload your public key to GitHub --- keys make for less password typing.
  \begin{small}
  \begin{lstlisting}
git clone git@github.com:ncar-mlso/comp-pipeline.git
  \end{lstlisting}
  \end{small}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Stage}
After making a local change, stage the files you want to commit:
  \begin{lstlisting}
git add <filename>
  \end{lstlisting}
Check to see status:
  \begin{lstlisting}
git status
  \end{lstlisting}
Git status messages show useful commands (such as how to stage a file, un-stage a file, or discard changes to a file)!
\end{frame}

\begin{frame}[fragile]
  \frametitle{Commit and push}
After staging, you are ready to commit:
  \begin{lstlisting}
git commit
  \end{lstlisting}
And push to GitHub:
  \begin{lstlisting}
git push origin master
  \end{lstlisting}
Here, {\em origin} is the remote to push to and {\em master} is the branch to push to.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Pull}
Get changes from another repo:
  \begin{lstlisting}
git pull origin master
  \end{lstlisting}
Technically, this is a fetch and a merge, but is convenient in the normal case.

\vspace{1em}

Do this before starting work.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Examine old commits}
  \begin{small}
  \begin{lstlisting}
$ git log --oneline
1dc418e Typo.
3512d91 Breaking COMP_PARSE_TIME out of COMP_EXTRACT_TIME.
ee7db9f Formatting.
798f6d5 Formatting.
01456d9 Basic top-level run.
5176a3a Updating library routines.

$ git checkout 5176a3a
  \end{lstlisting}
  \end{small}
\end{frame}

\subsection{Reverting changes}
\begin{frame}[fragile]
  \frametitle{Undo a local change}
Easy to find local changes:
  \begin{lstlisting}
git diff
git diff <filename>
  \end{lstlisting}
Use {\tt --staged} to compare differences in staged files.

\vspace{1em}

If you have made a local change that you want to revert, but haven't committed yet:
  \begin{lstlisting}
git checkout -- <filename>
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{New commit that undoes existing commits}
For example, to undo the last two commits:
  \begin{lstlisting}
git revert HEAD~2..HEAD
  \end{lstlisting}
Or to revert back to commit 0123456:
  \begin{lstlisting}
git revert 0123456..HEAD
  \end{lstlisting}
These commands create a new ``inverse'' commit.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Revert existing commits}
Undo last commit (but keep changes):
  \begin{lstlisting}
git reset --soft HEAD~1
  \end{lstlisting}
Completely remove last commit and changes:
  \begin{lstlisting}
git reset --hard HEAD~1
  \end{lstlisting}
These are problematic if the commits have been pushed to a remote.
\end{frame}

\begin{frame}{Other things you can do}
  \begin{enumerate}
    \item make a branch
    \item merge branches
    \item make a tag
    \item stash temporarily
    \item bisect
    \item and many more\ldots
  \end{enumerate}
\end{frame}

\subsection{Resources}
\begin{frame}{Resources}
  \begin{itemize}
    \item Just starting:
      \begin{itemize}
        \item https://try.github.io/
        \item https://www.atlassian.com/git/tutorials/
      \end{itemize}
    \item Full reference:
      \begin{itemize}
        \item Pro Git book: http://git-scm.com/book
      \end{itemize}
  \end{itemize}
\end{frame}

\section{GitHub}
\subsection*{}

\begin{frame}{Features}
GitHub is a social code hosting site. It features:
  \begin{itemize}
    \item browsing files, commits, branches, tags, etc.
    \item issues tracker
    \item wiki pages (actually another git repo)
    \item social: watch/star repos, follow people
  \end{itemize}
\end{frame}

\begin{frame}{OS clients}
The GitHub client applications can handle non-GitHub repos as well.

\vspace{1em}

Get the appropriate client here:
  \begin{itemize}
    \item https://mac.github.com
    \item https://windows.github.com
  \end{itemize}
Sorry Linux! (The command line is better anyway.)
\end{frame}

\begin{frame}{OS clients}
  \includegraphics[width=4in]{mac-client.png}
\end{frame}

\section{Conclusion}
\subsection*{}

\begin{frame}{Conclusion}
  \begin{enumerate}
    \item While git is more powerful than Subversion, you can use it like Subversion
    \item GitHub provides an easy browser with social integration and other code management features such as an issue tracker and wiki
  \end{enumerate}
\end{frame}

\begin{frame}{Thanks!}
  \begin{center}{\huge Thanks!}\end{center}
  \begin{itemize}
    \item {\tt mgalloy@ucar.edu}
  \end{itemize}
\end{frame}

\end{document}


text:
<?php

declare(strict_types=1);

namespace Ray\Di;

use Ray\Compiler\DiCompiler;
use Ray\Compiler\ScriptInjector;

use function assert;
use function microtime;
use function printf;
use function range;
use function serialize;
use function unserialize;

require __DIR__ . '/bootstrap.php';
$n = 20;

$injector = new Injector(new FakeCarModule());
$serialize = serialize($injector);

$timer = microtime(true);
foreach (range(1, $n) as $i) {
    $injector = new Injector(new FakeCarModule());
    $injector->getInstance(FakeCarInterface::class);
}

$timer1 = microtime(true) - $timer;

$timer = microtime(true);
$injector = unserialize($serialize);
assert($injector instanceof InjectorInterface);
foreach (range(1, $n) as $i) {
    $injector->getInstance(FakeCarInterface::class);
}

$timer2 = microtime(true) - $timer;

$compiler = new DiCompiler(new FakeCarModule(), __DIR__ . '/tmp');
$compiler->compile();
$timer = microtime(true);
$injector = new ScriptInjector(__DIR__ . '/tmp');
foreach (range(1, $n) as $i) {
    $injector->getInstance(FakeCarInterface::class);
}

$timer3 = microtime(true) - $timer;

// Microsecond per inject
printf("micro second per inject (MPI):%f speed:x%d\n", $timer2 / $n, $timer1 / $timer2);
printf("micro second per inject (MPI):%f speed:x%d\n", $timer3 / $n, $timer1 / $timer3);


text:
import { setNestedState, getNestedState } from './nestedState';
import { validateRootShape, setShape } from './nestedShape';
import { forEach } from 'lodash';
import { NAMESPACE } from './constants';

export default (state, routes, deserializer = null) => {
  const updatedState = { ...state };
  if (!validateRootShape(updatedState)) {
    return {
      ...updatedState,
      [NAMESPACE]: setShape(),
    };
  }

  forEach(routes, (route, index) => {
    const dataAtDepth = getNestedState(updatedState, index);

    let deserializedData;
    if (route.deserializer) {
      deserializedData = route.deserializer(dataAtDepth);
    } else if (deserializer) {
      deserializedData = deserializer(route, dataAtDepth);
    } else {
      deserializedData = dataAtDepth;
    }

    updatedState[NAMESPACE] = setNestedState(state, deserializedData, index);
  });

  return updatedState;
};


text:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Hanselman.Helpers;
using Shiny.Jobs;

namespace Hanselman.Services
{
    [Preserve(AllMembers = true)]
    public class BackgroundRefreshJob : IJob
    {
        DataService dataService;
        public BackgroundRefreshJob()
        {
            dataService = new DataService();
        }

        public async Task<bool> Run(JobInfo jobInfo, CancellationToken cancelToken)
        {
            try
            {
                var getTweets = dataService.GetTweetsAsync(true);
                var getBlogs = dataService.GetBlogItemsAsync(true);

                await Task.WhenAll(getTweets, getBlogs);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to refresh items: {ex}");
                return false;
            }

            return true;
        }

    }

}