text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="#6699cc"
            android:gravity="center"
            android:orientation="horizontal" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/emcall"
                android:src="@drawable/emcall" />

            <TextView
                android:id="@+id/emergence"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/emcall"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#ffffff" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="10dp"
            android:layout_weight="2"
            android:background="#ffffff"
            android:orientation="vertical"
            android:paddingTop="10dp" >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/username"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#0000cc" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/profile"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#0000cc" />
            </LinearLayout>

            <ImageView
                android:id="@+id/proedit"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="right"
                android:layout_marginTop="-35dp"
                android:contentDescription="@string/editpro"
                android:src="@drawable/edit" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <ImageView
                    android:id="@+id/photoimageviev"
                    android:layout_width="77dp"
                    android:layout_height="77dp"
                    android:layout_marginRight="10dp"
                    android:contentDescription="@string/profile"
                    android:src="@drawable/icare" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical" >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal"
                        android:paddingTop="5dp" >

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:text="@string/age"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/colon"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000" />

                        <TextView
                            android:id="@+id/agetv"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="1"
                            android:hint="@string/age"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal" >

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:text="@string/ht"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/colon"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000" />

                        <TextView
                            android:id="@+id/httv"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="1"
                            android:hint="@string/ht"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal" >

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:text="@string/wt"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/colon"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000" />

                        <TextView
                            android:id="@+id/wttv"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="1"
                            android:hint="@string/wt"
                            android:textAppearance="?android:attr/textAppearanceMedium"
                            android:textColor="#000000" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="5dp" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="@string/specialinfo"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000000"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/colon"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000000" />

                <TextView
                    android:id="@+id/specialinfotv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:hint="@string/specialinfo"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000000" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/dietTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="#deeeeb"
                android:drawableTop="@drawable/adddiet"
                android:gravity="center"
                android:padding="13dp"
                android:text="@string/dietchart"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000cc" />

            <TextView
                android:id="@+id/vccTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="#deeeeb"
                android:drawableTop="@drawable/vcc"
                android:gravity="center"
                android:padding="10dp"
                android:text="@string/vccchart"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000cc" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/docprofileTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="#d7d8ed"
                android:drawableTop="@drawable/doctor"
                android:gravity="center"
                android:padding="10dp"
                android:text="@string/docprofile"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000cc" />

            <TextView
                android:id="@+id/medicalhistoryTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="#d7d8ed"
                android:drawableTop="@drawable/mdhistory"
                android:gravity="center"
                android:padding="10dp"
                android:text="@string/mdhis"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000cc" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/galleryTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="#fbeff2"
                android:drawableTop="@drawable/gallery"
                android:gravity="center"
                android:padding="10dp"
                android:text="@string/gallery"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000cc" />

            <TextView
                android:id="@+id/carecenterTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="#fbeff2"
                android:drawableTop="@drawable/center"
                android:gravity="center"
                android:padding="10dp"
                android:text="@string/carecenter"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#0000cc" />
        </LinearLayout>
    </LinearLayout>

</ScrollView>


text:
package com.nick.scalpel;

import android.app.Application;
import android.support.annotation.CallSuper;

import com.nick.scalpel.config.Configuration;

public class ScalpelApplication extends Application {
    @Override
    @CallSuper
    public void onCreate() {
        super.onCreate();
        Scalpel.getDefault()
                .application(this)
                .config(Configuration.builder()
                        .autoFindIfNull(true)
                        .debug(true)
                        .logTag(getClass().getSimpleName())
                        .build());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package main;
our $SEE;

package KmerGraph;

use strict;
use warnings;
use Carp;
use KmerNode;
use ReadTracker;

use base qw (ReadCoverageGraph);

no warnings qw (recursion);

my $MIN_DISPLAY_SEQ_TAG_LENGTH = 10; # lower than this, and shows up in the dot file as a label.

sub new {
	my $packagename = shift;
	my $KmerLength = shift;

	unless ($KmerLength > 1) { croak "Error, need KmerLength > 1"; }

	my $self = {
		_nodes => {},  #kmerSeq => nodeAddress until after compaction... becomes nodeaddress => $nodeaddress
		KmerLength => $KmerLength,
		compacted => 0,
        color_to_accs => {},

	};

	bless ($self, $packagename);

	return($self);
}

sub add_sequence_to_graph {
	my $self = shift;
	my ($acc, $sequence, $weight, $color) = @_;  ## Sequence type can be undef, ReferenceTranscript, or GreedyPath

	unless (defined($weight) && $weight =~ /^\d+/) {
		confess "Error, params: (seq, weight, color), and weight must be numeric.";
	}

	if ($self->{compacted}) {
		confess "Cannot add more sequences to the graph after it has been compacted";
	}

    push (@{$self->{color_to_accs}->{$color}}, $acc); # add this accession to color indicator. # prefer 1-1 relationship here.

	$sequence = uc $sequence;

	my $KmerLength = $self->{KmerLength};

	if (length($sequence) < $KmerLength+1) {
		warn "sequence $sequence is less than KmerLength $KmerLength+1; skipping it\n";
		return;
	}

	my $prevKmer = substr($sequence, 0, $KmerLength);
	my $prevKmerNode = $self->get_or_create_node($prevKmer);
	$prevKmerNode->{_count}++;
	$prevKmerNode->track_reads($acc);

	if ($color) {
		$prevKmerNode->add_color($color);
	}

	for (my $i = 1; $i <= length($sequence)-$KmerLength; $i++) {
		my $nextKmer = substr($sequence, $i, $KmerLength);
		my $nextKmerNode = $self->get_or_create_node($nextKmer);
		$nextKmerNode->track_reads($acc);

		if ($color) {
			$nextKmerNode->add_color($color);
		}

		$nextKmerNode->{_count}++;

		my $prev_edge_weight = $self->get_edge_count($prevKmerNode, $nextKmerNode);

		## only link together kmers that contain only recognizable nucleotides
		$self->link_adjacent_nodes($prevKmerNode, $nextKmerNode, $weight);

		my $edge_weight = $self->get_edge_count($prevKmerNode, $nextKmerNode);
		if ($edge_weight < $weight) {
			confess "Error, added weight $weight to edge $prevKmerNode -> $nextKmerNode and didn't stick";
		}

		if ($prev_edge_weight > $edge_weight) {
			confess "Error, after adding new edge, prev weight of $prev_edge_weight became: $edge_weight ";
		}
		#print "$prevKmerNode -> $nextKmerNode : $prev_edge_weight -> $edge_weight\n";

		$prevKmerNode = $nextKmerNode;
		$prevKmer = $nextKmer;
	}

	return;
}

sub get_or_create_node {
        my $self = shift;
        my ($node_name, $read_accession) = @_;

        if ($self->node_exists($node_name)) {
                my $node = $self->get_node($node_name);
				return($node);

        }
        else {
                # instantiate it, add it to the graph
                return($self->create_node($node_name));
        }
}

sub create_node {
        my $self = shift;

        my ($node_name) = @_;

        if ($self->node_exists($node_name)) {
                confess "Error, node $node_name already exists in the graph";
        }

        my $node = new KmerNode($node_name);

        $self->{_nodes}->{$node_name} = $node;

        return($node);
}

####
sub compact_graph {
	my $self = shift;

	$self->validate_graph();

	my $kmer_length = $self->{KmerLength};

	unless ($self->{compacted}) {
		$self->_prep_graph_for_compaction();

		$self->{compacted} = 1;
	}

	my $COMPACTED = 0; # flag

	## identify all nodes that are branched on the left and not branched on the right
	## then join together the unbranched nodes starting from these and walking right.

	my @nodes = $self->get_all_nodes();

	## merge unbranched nodes in runs.

	####
	####  \
	####    (-)---
	#### /

	# or

	#  (-)---

	# or

	####      (-)------------
	####    /
	####  -
	####    \
	####     (-) ------------

	# or, single line with incompatible decorations:

	#    aaaaaaaaaa b bbbbbbbbbb
	#    ----------(-)----------

	my @init_nodes;
	foreach my $node (@nodes) {
		my @prev_nodes = $node->get_all_prev_nodes();

		my @next_nodes = $node->get_all_next_nodes();

		if

			(  (scalar(@next_nodes) == 1)
			  &&

			   (

				(
				  (scalar(@prev_nodes) != 1)  # branched before or no node before.
				  ||
				  (scalar (@prev_nodes) == 1 && scalar($prev_nodes[0]->get_all_next_nodes() > 1) ) # previous node branches off.

				)

				||

				## decoration switch
				(scalar(@prev_nodes) == 1 && (! &_compatible_decorations($node, $prev_nodes[0])) && (&_compatible_decorations($node, $next_nodes[0])) )

			   )

			)
		{
			# got one
			push (@init_nodes, $node);
		}

	}

	print "Got " . scalar(@init_nodes) . " init nodes.\n" if $main::SEE;

	#foreach my $node (@init_nodes) {
	#	print "Init node $node:\n" . $node->toString() . "\n";# if $main::SEE;
	#}

	## Collapse neighboring nodes before branching
	foreach my $node (@init_nodes) {

		#print "Init node $node:\n" . $node->toString() . "\n";# if $main::SEE;

		my @unbranched_path;

		my ($next_node) = $node->get_all_next_nodes();

		unless ($next_node) {
			print "warning, init node now lacks next nodes...  skipping.\n"; # potential bug?  or circular dealt with already?
			next;
		}

		my %seen = ($node => 1);

	    while (1) {
			# avoid circularity
			if ($seen{$next_node}) {
				print "Seen $next_node already... avoiding circularity.\n" if $main::SEE;
				last;
			}
			$seen{$next_node} = 1;

			unless (&_compatible_decorations($node, $next_node)) {
				print "Incompatible decorations.\n" if $main::SEE;
				last;
			}

			# check for left branching on next node
			my $num_prev_nodes = scalar ($next_node->get_all_prev_nodes());
			if (scalar $num_prev_nodes > 1) {
				print "Got $num_prev_nodes prev nodes for $next_node; terminating extension.\n" if $main::SEE;
				last;
			}

			push (@unbranched_path, $next_node);
			my @next_nodes = $next_node->get_all_next_nodes();

			if (scalar @next_nodes != 1) {
				last;
			}
			$next_node = shift @next_nodes;

		}

		if ($main::SEE) {
			print "Single unbranched path:\n";
			$self->print_path($node, @unbranched_path);
		}

		foreach my $next_node (@unbranched_path) {
			# merge pairs
			$self->_append_node($node, $next_node);
			$COMPACTED = 1;

		}

		if ($main::SEE) {
			print "Collapsed:\n";
			$self->print_path($node);
			print "\n\n\n";
		}

	}

	$self->validate_graph();

	return ($COMPACTED);
}

####
sub _append_node {
	my $self = shift;
	my ($node, $next_node) = @_;

	## In compacted mode already.

	if (! _compatible_decorations($node, $next_node)) {
		confess "Error, trying to join nodes with incompatible decorations.";
	}

	my $KmerLength = $self->{KmerLength};

	# add counts
	$node->set_count($node->get_count() + $next_node->get_count());

	my $orig_node_seq = $node->get_sequence();
	my $orig_next_node_seq = $next_node->get_sequence();

	my $new_node_sequence = $orig_node_seq . substr($orig_next_node_seq, $KmerLength-1); # exclude K-1 prefix.

	# add terminal base
	$node->set_sequence($new_node_sequence);

	# add read evidence
	$node->{_ReadTracker}->append_to_ReadTracker($next_node->{_ReadTracker});

	# sever connection between node and next
	$node->delete_next_node($next_node);
	$next_node->delete_prev_node($node);

	# sever connection between next and next-next nodes, and reconnect next-next's with node.

	my @next_node_next_nodes = $next_node->get_all_next_nodes();

	my %next_next_node_edge_count;

	## update edge counts.
	foreach my $next_next_node (@next_node_next_nodes) {
		my $edge_count = $self->get_edge_count($next_node, $next_next_node);

		$next_next_node_edge_count{$next_next_node} = $edge_count;
	}

	$self->delete_node_from_graph($next_node);

	foreach my $next_next_node (@next_node_next_nodes) {
		$self->link_adjacent_nodes($node, $next_next_node, $next_next_node_edge_count{$next_next_node});

	}

	return;
}

####
sub toGraphViz {
	my $self = shift;

	my (%settings) = @_;

	my @nodes = $self->get_all_nodes();

	my $text = "digraph G {\n";

	$text .=
		#"node [width=0.1,height=0.1,fontsize=10,shape=point];\n"
		"node [width=0.1,height=0.1,fontsize=10];\n"
		. "edge [fontsize=12];\n"
		. "margin=1.0;\n"
		. "rankdir=LR;\n"
		. "labeljust=l;\n";

	foreach my $node (sort {$a->get_ID() cmp $b->get_ID()}  @nodes) {

		my @prev_nodes = $node->get_all_prev_nodes();
		my @next_nodes = $node->get_all_next_nodes();

		my $sequence = $node->get_sequence();

		if (my $min_len = $settings{no_short_singletons}) {

			if ( scalar(@prev_nodes) == 0
				 &&
				 scalar(@next_nodes) == 0
				 &&
				 length($sequence) < $min_len) {

				next;
			}
		}

		my $seqLen = length($sequence);

		my $count = $node->get_count();

		my $len = $seqLen;

		if (scalar(@prev_nodes)==0) { # no left connecting node:
			$len = $seqLen - ($self->{KmerLength} - 1);
		}

		my $avg_count = $count; #int($count/$len + 0.5);

		my $id = hex($node->get_ID());

		my $atts = "";

		if (length($sequence) < $MIN_DISPLAY_SEQ_TAG_LENGTH) {
			$atts = "-$sequence";
		}
		else {
			$atts = "-" . substr($sequence, 0, 3) . "..." . substr($sequence, -3);
		}

		my $depth ="";
		if (defined $node->{depth}) {
			$depth = $node->{depth};
		}

		#$text .= "\t$id \[label=\"$id-L$seqLen-C$avg_count$atts\"$color];\n";
		$text .= "\t$id \[label=\"D:$depth-L$seqLen-C$avg_count$atts\"];\n";

		foreach my $next_node (@next_nodes) {

			my $next_id = hex($next_node->get_ID());

			my @colors_in_common = &get_colors_in_common($node, $next_node);

			my $edge_weight = $self->get_edge_count($node, $next_node);

			if (@colors_in_common) {
				foreach my $color (@colors_in_common) {

                    my $label = "$edge_weight";
                    unless ($color eq 'black') { # reserved for general data
                        my @accs = @{$self->{color_to_accs}->{$color}};
                        $label = join(",", @accs);
                    }
					#$text .= "\t$id->$next_id [label=$edge_weight, color=\"$color\"];\n";
					$text .= "\t$id->$next_id [label=\"$label\", color=\"$color\"];\n";

				}
			}

		}
	}

	$text .= "}\n";

	return($text);
}

sub get_colors_in_common {
	my ($node, $next_node) = @_;

	my @colorsA = $node->get_colors();
	my @colorsB = $next_node->get_colors();

	my %counts;

	foreach my $color (@colorsA, @colorsB) {
		$counts{$color}++;
	}
	my @colors = grep { $counts{$_} > 1 } keys %counts;

	return(@colors);
}

####
sub _prep_graph_for_compaction {
	my $self = shift;

	my @nodes = $self->get_all_nodes();

	my %new_node_set;  ## change lookup so it's not based on sequence anymore.

	foreach my $node (@nodes) {
		$new_node_set{"$node"} = $node;
	}

	$self->{_nodes} = \%new_node_set;
}

####
sub delete_node_from_graph {
	my $self = shift;
	my ($node) = @_;

	$self->prune_nodes_from_graph($node);

	if ($self->{compacted}) {

		delete $self->{_nodes}->{$node};

	}
	else {
		my $kmer = $node->get_sequence();
		delete $self->{_nodes}->{"$kmer"};
	}

	return;
}

####
sub purge_nodes_below_count {
	my $self = shift;

	my ($min_count) = @_;

	my @nodes = $self->get_all_nodes();

    my $num_deleted = 0;

	foreach my $node (@nodes) {

        if ($node->get_count() < $min_count) {

			my @colors = $node->get_colors();
            unless (scalar(@colors) == 1 && $colors[0] eq "black") {
                next;
                ## skipping base data (reads) below coverage limit
            }

            $self->delete_node_from_graph($node);

            $num_deleted++;
        }
	}

    print STDERR "  -purged nodes below count($min_count), deleted $num_deleted nodes.\n";

	return;
}

####
sub validate_graph {
	my $self = shift;

	print STDERR "Validating graph.\n";

	my @nodes = $self->get_all_nodes();

	my %node_ids_in_graph;

	foreach my $node (@nodes) {

		my $node_id = $node->get_ID();
		$node_ids_in_graph{$node_id} = $node;
	}

	foreach my $node (@nodes) {

		my $id = $node->get_ID();

		my @prev_nodes = $node->get_all_prev_nodes();
		foreach my $prev_node (@prev_nodes) {
			my $prev_id = $prev_node->get_ID();

			unless (exists ($node_ids_in_graph{$prev_id})) {
				print STDERR "Error, $prev_id exists as prev_node to $id, but not in graph\n";
				print STDERR $prev_node->get_sequence() . "\n" . $prev_node->toString();
				confess;
			}

			unless ($prev_node->has_next_node($node)) {
				confess "Error, prev_node: $prev_id lacks current next node $id  as link.\n";
			}

		}

		my @next_nodes = $node->get_all_next_nodes();
		foreach my $next_node (@next_nodes) {
			my $next_id = $next_node->get_ID();

			unless (exists ($node_ids_in_graph{$next_id})) {
				print STDERR "Error, $next_id exists as next_node to $id, but not in graph\n";
				print STDERR $next_node->get_sequence() . "\n" . $next_node->toString();
				confess;
			}

			unless ($next_node->has_prev_node($node)) {
			    confess "Error, next node: $next_id lacks current node $id as prev link.\n";
			}

		}

	}

	return;
}

####
sub print_path {
	my $self = shift;
	my @nodes = @_;

	my $counter = 0;
	my $prev_node;

	foreach my $node (@nodes) {
		$counter++;
		printf("%4s", $counter);

		my $edge_count = "";
		if ($prev_node) {
			$edge_count = " edge_weight: " . $self->get_edge_count($prev_node, $node);
		}

		print " " . $node->get_value() . " C:" . $node->get_count() . " " . join(",", $node->get_colors()) . "$edge_count\n";

		$prev_node = $node;

	}
	print "\n";

	return;
}

sub _compatible_decorations {
	my ($nodeA, $nodeB) = @_;

	my @colorsA = $nodeA->get_colors();
	my @colorsB = $nodeB->get_colors();

	unless (@colorsA || @colorsB) {
		# no decorations.
		return(1);
	}

	my %counts;
	foreach my $color (@colorsA, @colorsB) {
		$counts{$color}++;
	}

	my @colors_unique = grep { $counts{$_} == 1 } keys %counts;

	if (@colors_unique) {
		#print STDERR "unique colors: @colors_unique\n";
		return(0);
	}

	else {
		return(1);
	}
}

####
sub score_nodes {
	my $self = shift;

	$self->assign_depth_to_nodes();

	##  score = sum prev counts for those reads that are consistent, excluding those that are from bifurcating reads.

	my @nodes = sort {$a->{depth}<=>$b->{depth}} $self->get_all_nodes();

	## assign base scores:
	foreach my $node (@nodes) {

		## define base scores: contributions by reads that are not in prev or next nodes.
		my %neighboring_reads = $self->gather_read_indices($node->get_all_prev_nodes(), $node->get_all_next_nodes());

		my $base_score = 0;

		my $read_tracker = $node->get_ReadTracker();
		my @reads = $read_tracker->get_tracked_read_indices();
		foreach my $read (@reads) {
			if ($node->{depth} == 0 || ! $neighboring_reads{$read}) {
				my $count = $read_tracker->get_read_base_count($read);

				$base_score += $count;
				#print "$node has read [$read] with count [$count]\n";

			}
		}

		$node->{_base_score} = $base_score;
		$node->{_sum_score} = $base_score; # init
		#print "$node : base score = $base_score\n";
	}

	## assign sum scores
	foreach my $node (@nodes) {
		my %indices_exclude;

		my $read_tracker = $node->get_ReadTracker();

		my $highest_prev_score = $node->{_sum_score};
		my $highest_prev_node = undef;

		foreach my $prev_node ($node->get_all_prev_nodes()) {
			## want reads that are in current node and prev node, but not other next nodes of prev node (exclusive to current node).
			my $sum_score = $prev_node->{_sum_score};

			my @other_prev_next_nodes = grep { $_ ne $node } $prev_node->get_all_next_nodes();

			my %reads_ignore = $self->gather_read_indices(@other_prev_next_nodes);

			foreach my $read ($read_tracker->get_tracked_read_indices()) {

				if (! $reads_ignore{$read}) {

					$sum_score += $read_tracker->get_read_base_count($read);
				}
			}

			push (@{$prev_node->{_forward_scores}}, { next_node => $node,
													  score => $sum_score,
				  } );

			if ($sum_score > $highest_prev_score) {
				$highest_prev_score = $sum_score;
				$highest_prev_node = $prev_node;
			}
		}

		$node->{_sum_score} = $highest_prev_score;
		$node->{_best_prev} = $highest_prev_node;
	}

	## find highest sum score
	my $highest_sum_score = 0;
	my $best_node = undef;

	foreach my $node (@nodes) {
		#print "Node: $node, has sum score: " . $node->{_sum_score} . "\n";
		if ($node->{_sum_score} > $highest_sum_score) {
			$highest_sum_score = $node->{_sum_score};
			$best_node = $node;
		}
	}

	my @path_nodes;
	my $prev_node = $best_node;
	while ($prev_node) {
		#print "Backtracked: $prev_node " . $prev_node->{_sum_score} . "\n";
		#print $prev_node->toString();
		push (@path_nodes, $prev_node);
		$prev_node = $prev_node->{_best_prev};

	}

	@path_nodes = reverse @path_nodes;

	return (@path_nodes);

}

####
sub extract_sequence_from_path {
	my $self = shift;
	my (@ordered_nodes) = @_; # ordered left to right

	my @seqs;

	foreach my $node (@ordered_nodes) {

		$node->{_visited} = 1;

		push (@seqs, $node->get_sequence());

	}

	my $kmer_length = $self->{KmerLength};

	my $final_seq = shift @seqs; ## first one gets full kmer treatment.

	foreach my $seq (@seqs) {
		$seq = substr($seq, $kmer_length-1);

		$final_seq .= $seq;
	}

	return($final_seq);
}

####
sub gather_read_indices {
	my $self = shift;
	my (@nodes) = @_;

	my %indices;

	foreach my $node (@nodes) {

		my $read_tracker = $node->get_ReadTracker();

		my @read_indices = $read_tracker->get_tracked_read_indices();

		foreach my $read (@read_indices) {
			$indices{$read}=1;
		}
	}

	return(%indices);
}

####
sub assign_depth_to_nodes {
	my $self = shift;
	print STDERR "Assigning depth to nodes\n";

	my @root_nodes = $self->get_root_nodes();

	## base cases.
	foreach my $root (@root_nodes) {
		$root->{depth} = 0;
	}

	foreach my $node ($self->get_all_nodes()) {
		if (! defined ($node->{depth})) {
			$self->assign_depth($node, {});
		}
	}

	return;
}

####
sub assign_depth {
	my $self = shift;
	my $node = shift;
	my $seen_href = shift;

	my @ancestors = $node->get_all_prev_nodes();

	my $max_depth = 0;

	foreach my $ancestor (@ancestors) {

		my $depth;
		if (defined($ancestor->{depth})) {
			$depth = 1 + $ancestor->{depth};
		}
		else {

			if ($seen_href->{$ancestor}) {
				# print "Breaking cycle: $ancestor\n" . join("\n", keys %$seen_href) . "\n";
				next;
			}
			$seen_href->{$ancestor} = 1;

			$depth = 1 + $self->assign_depth($ancestor, $seen_href);
		}
		if ($depth > $max_depth) {
			$max_depth = $depth;
		}
	}

	# print "$node\tdepth: $max_depth\n";
	$node->{depth} = $max_depth;
	return($max_depth);
}

####
sub all_nodes_visited {
	my $self = shift;

	my @nodes = $self->get_all_nodes();

	foreach my $node (@nodes) {

		if (! $node->{_visited}) {
			return(0);
		}
	}

	return(1); # all visited.
}

####
sub extract_path_from_unvisited_node {
	my $self = shift;

	my @nodes = $self->get_all_nodes();

	my $highest_scoring_unvisited_node = undef;
	my $highest_score = -1;

	foreach my $node (@nodes) {
		if (! $node->{_visited}) {
			if ($node->{_base_score} > $highest_score) {
				$highest_score = $node->{_base_score};
				$highest_scoring_unvisited_node = $node;
			}
		}
	}

	unless ($highest_scoring_unvisited_node) {
		confess "Error, no unvisited node found";
	}

	my @best_path;

	my %seen; # don't follow cycles.  FIXME: cycles shouldn't be part of the scoring, though... bug somewhere upstream?

	my $prev_node = $highest_scoring_unvisited_node;
	while ($prev_node && ! $prev_node->{_visited} && ! $seen{$prev_node}) {
		print "walking prev_node: $prev_node\n" if $main::SEE;
		$seen{$prev_node} = 1;
		unshift(@best_path, $prev_node);
		$prev_node = $prev_node->{_best_prev};
	}

	## now track forward.
	my $next_node = $highest_scoring_unvisited_node;
	delete $seen{$next_node}; # already used above.
	while ($next_node && ! $next_node->{_visited} && ! $seen{$next_node}) {
		print "walking next_node: $next_node\n" if $main::SEE;
		$seen{$next_node} = 1;
		my @structs = @{$next_node->{_forward_scores}};
		if (@structs) {
			@structs = sort {$a->{score}<=>$b->{score}} @structs;
			my $best_struct = pop @structs;
			push (@best_path, $next_node);
			$next_node = $best_struct->{next_node};
		}
		else {
			$next_node = undef;
		}
	}

	return(@best_path);
}

####
sub prune_low_weight_edges {
	my $self = shift;
	my %params = @_;

	my $edge_weight_threshold = $params{edge_weight_threshold};

	my @nodes = $self->get_all_nodes();

	my @edges_to_prune;

	foreach my $node (@nodes) {
		my @prev_nodes = $node->get_all_prev_nodes();

		foreach my $prev_node (@prev_nodes) {

			my $edge_ratio = $self->compute_edge_support_ratio($prev_node, $node);

			#print "EdgeRatio: $edge_ratio\n";

			if ($edge_ratio < $edge_weight_threshold) {
				push (@edges_to_prune, [$prev_node, $node]);

			}
		}
	}

	if (@edges_to_prune) {

		foreach my $edges_to_prune (@edges_to_prune) {

			my ($prev_node, $node) = @$edges_to_prune;
			$self->prune_edge($prev_node, $node);
		}

		return(scalar(@edges_to_prune));
	}
	else {
		return(0);
	}

}

####
sub prune_singletons {
	my $self = shift;

	my ($min_seq_length) = @_;

	my @nodes = $self->get_all_nodes();

	foreach my $node (@nodes) {

		if (  (! $node->get_all_prev_nodes())
			  &&
			  (! $node->get_all_next_nodes()) ) {

			if (length ($node->get_sequence()) < $min_seq_length) {

				$self->delete_node_from_graph($node);
			}
		}
	}

	return;
}

####
sub compute_edge_support_ratio {
	my $self = shift;
	my ($prev_node, $node) = @_;

	## ratio = reads in common / (all reads out of prev UNION all reads into node)

	my @reads_exiting_prev_node = $prev_node->get_reads_exiting_node();
	my %exiting_reads = map { + $_ => 1 } @reads_exiting_prev_node;

	my @reads_entering_node = $node->get_reads_entering_node();
	my %entering_reads = map { + $_ => 1 } @reads_entering_node;

	my %all_reads = map { + $_ => 1 } (@reads_exiting_prev_node, @reads_entering_node);

	my @all = keys %all_reads;
	my @shared;

	foreach my $read (@all) {
		if ($entering_reads{$read} && $exiting_reads{$read}) {
			push (@shared, $read);
		}
	}

	my $ratio = scalar(@shared) / scalar(@all);

	return($ratio);
}

####
sub prune_dangling_nodes {
	my $self = shift;
	my %params = @_;

	my $min_leaf_node_length = $params{min_leaf_node_length};
	my $min_leaf_node_avg_cov = $params{min_leaf_node_avg_cov};

	unless (defined ($min_leaf_node_length)
					 &&
			defined ($min_leaf_node_avg_cov) ) {

		confess "Error, must define values for both: min_leaf_node_length && min_leaf_node_avg_cov";
	}

	my @nodes = $self->get_all_nodes();

	my @nodes_to_prune;

	my $kmer_length = $self->{KmerLength};

	foreach my $node (@nodes) {

		## check to see if it's a dangling node.
		if (  (! $node->get_all_prev_nodes())
			  ||
			  (! $node->get_all_next_nodes())
			) {

			my $length = length($node->get_sequence());

			my $cov = $node->get_count();

			my $avg_cov = $cov / ($length - ($kmer_length - 1));

			if ($avg_cov < $min_leaf_node_avg_cov && $length < $min_leaf_node_length) {
				push (@nodes_to_prune, $node);
			}

		}
	}

	if (@nodes_to_prune) {

		foreach my $node (@nodes_to_prune) {

			$self->prune_nodes_from_graph($node);
		}

		return(scalar(@nodes_to_prune)); # nodes pruned.
	}

	else {
		return(0); # no nodes pruned.
	}

}

1; #EOM


text:
const INITIAL_LOAD = 'logger-app/logs/INITIAL_LOAD';
const INITIAL_LOAD_SUCCESS = 'logger-app/logs/INITIAL_LOAD_SUCCESS';
const INITIAL_LOAD_FAIL = 'logger-app/logs/INITIAL_LOAD_FAIL';

const ACTIVATE_LOG = 'logger-app/logs/ACTIVATE_LOG';
const PAUSE_LOG = 'logger-app/logs/PAUSE_LOG';
const RESUME_LOG = 'logger-app/logs/RESUME_LOG';
const DEACTIVATE_LOG = 'logger-app/logs/DEACTIVATE_LOG';
const CLEAR_LOG_OUTPUT = 'logger-app/logs/CLEAR_LOG_OUTPUT';
const TOGGLE_SCROLL_LOCK = 'logger-app/logs/TOGGLE_SCROLL_LOCK';
const TOGGLE_LOG_EXTRA_ACTIONS_OPEN = 'logger-app/logs/TOGGLE_LOG_EXTRA_ACTIONS_OPEN';

const ADD_LINE_TO_LOG = 'logger-app/logs/ADD_LINE_TO_LOG';
const SET_LOG_READ = 'logger-app/logs/SET_LOG_READ';

// Log Management actions
// Edit Group Name
const TOGGLE_EDIT_OPEN = 'logger-app/logs/TOGGLE_EDIT_OPEN';
const SET_EDITED_NAME = 'logger-app/logs/SET_EDITED_NAME';
const SET_EDITED_GROUP = 'logger-app/logs/SET_EDITED_GROUP';
const SET_EDITED_FILE = 'logger-app/logs/SET_EDITED_FILE';
const SET_EDITED_PATH = 'logger-app/logs/SET_EDITED_PATH';
const SAVE_LOG_CHANGES = 'logger-app/logs/SAVE_LOG_CHANGES';
const SAVE_LOG_CHANGES_SUCCESS = 'logger-app/logs/SAVE_LOG_CHANGES_SUCCESS';

// Delete Group
const TOGGLE_DELETE_LOG_OPEN = 'logger-app/logs/TOGGLE_DELETE_LOG_OPEN';
const DELETE_LOG = 'logger-app/logs/DELETE_LOG';
const DELETE_LOG_SUCCESS = 'logger-app/logs/DELETE_LOG_SUCCESS';

// Socket Events
import {
  GROUP_DELETE_EMITTED,
  NEW_LOG_EMITTED,
  LOG_NAME_CHANGE_EMITTED,
  LOG_FILE_CHANGE_EMITTED,
  LOG_PATH_CHANGE_EMITTED,
  LOG_DELETE_EMITTED,
  TAIL_ERROR_EMITTED,
  SAVE_LOG_CHANGES_FAIL,
  DELETE_LOG_FAIL
} from './sharedActions.js';

const initialState = {
  loaded: false,
  idsAlphabetically: []
};

// This returns the ordered list of IDs from a object of groups
const getOrderedIds = logsObject =>
  Object.keys(logsObject)
    .map(logId => ({ logId, name: logsObject[logId].name }))
    .sort((first, second) => first.name.localeCompare(second.name))
    .map(obj => obj.logId);

const applyDefaultLogValues = (log) => ({
  ...log,
  logData: [],
  pausedLogData: [],
  extraActionsOpen: false,
  activeState: 'INACTIVE',
  hasNew: false,
  scrollLocked: true,
  logLevelMapping: null,
  tailError: null,
  // Log Management Page Variables
  editPanelOpen: false,
  editedName: log.name,
  editedGroup: null,
  editedFile: log.fname,
  editedPath: log.fpath,
  editSaving: false,
  deletePanelOpen: false,
  deleteSaving: false
});

const logReducer = (state, action) => {
  switch (action.type) {
    case ACTIVATE_LOG:
      return {
        ...state,
        activeState: 'ACTIVE',
        tailError: null
      };
    case PAUSE_LOG:
      return {
        ...state,
        activeState: 'PAUSED'
      };
    case RESUME_LOG:
      return {
        ...state,
        activeState: 'ACTIVE',
        logData: state.logData.concat(state.pausedLogData),
        pausedLogData: []
      };
    case DEACTIVATE_LOG:
      return {
        ...state,
        activeState: state.logData.length ? 'INACTIVE_WITH_OUTPUT' : 'INACTIVE',
        pausedLogData: []
      };
    case CLEAR_LOG_OUTPUT:
      return {
        ...state,
        activeState: state.activeState === 'INACTIVE_WITH_OUTPUT' ? 'INACTIVE' : state.activeState,
        logData: [],
        pausedLogData: []
      };
    case TOGGLE_SCROLL_LOCK:
      return {
        ...state,
        scrollLocked: !state.scrollLocked
      };
    case TOGGLE_LOG_EXTRA_ACTIONS_OPEN:
      return {
        ...state,
        extraActionsOpen: !state.extraActionsOpen
      };
    case ADD_LINE_TO_LOG:
      return {
        ...state,
        logData: state.activeState === 'PAUSED' ? state.logData : state.logData.concat(action.newLine),
        pausedLogData: state.activeState === 'PAUSED' ? state.pausedLogData.concat(action.newLine) : state.pausedLogData,
        hasNew: true
      };
    case SET_LOG_READ:
      return {
        ...state,
        hasNew: false
      };
    case TAIL_ERROR_EMITTED:
      return {
        ...state,
        activeState: 'INACTIVE'
      };
    case TOGGLE_EDIT_OPEN:
      return {
        ...state,
        editPanelOpen: !state.editPanelOpen
      };
    case SET_EDITED_NAME:
      return {
        ...state,
        editedName: action.editedName
      };
    case SET_EDITED_GROUP:
      return {
        ...state,
        editedGroup: action.editedGroup
      };
    case SET_EDITED_FILE:
      return {
        ...state,
        editedFile: action.editedFile
      };
    case SET_EDITED_PATH:
      return {
        ...state,
        editedPath: action.editedPath
      };
    case SAVE_LOG_CHANGES:
      return {
        ...state,
        editSaving: true
      };
    case SAVE_LOG_CHANGES_SUCCESS:
      return {
        ...state,
        editPanelOpen: false,
        editSaving: false
      };
    case SAVE_LOG_CHANGES_FAIL:
      return {
        ...state,
        editSaving: false
      };
    case TOGGLE_DELETE_LOG_OPEN:
      return {
        ...state,
        deletePanelOpen: !state.deletePanelOpen
      };
    case DELETE_LOG:
      return {
        ...state,
        deleteSaving: true
      };
    case DELETE_LOG_FAIL:
      return {
        ...state,
        deleteSaving: false
      };
    case LOG_NAME_CHANGE_EMITTED:
      return {
        ...state,
        name: action.newName
      };
    case LOG_FILE_CHANGE_EMITTED:
      return {
        ...state,
        fname: action.newFile
      };
    case LOG_PATH_CHANGE_EMITTED:
      return {
        ...state,
        fpath: action.newPath
      };
    default:
      return state;
  }
};

export default function logs(state = initialState, action = {}) {
  switch (action.type) {
    case INITIAL_LOAD:
      return {
        ...state,
        loading: true
      };
    case INITIAL_LOAD_SUCCESS:
      return {
        ...state,
        loading: false,
        loaded: true,
        data: Object.keys(action.result).reduce((prev, logId) => ({
          ...prev,
          [logId]: applyDefaultLogValues(action.result[logId])
        }), {}),
        error: null,
        idsAlphabetically: getOrderedIds(action.result)
      };
    case INITIAL_LOAD_FAIL:
      return {
        ...state,
        loading: false,
        loaded: false,
        data: null,
        error: action.error
      };
    case NEW_LOG_EMITTED: {
      const newData = {
        ...state.data,
        [action.newLogId]: applyDefaultLogValues({
          name: action.logName,
          fname: action.logFile,
          fpath: action.logPath
        })
      };

      return {
        ...state,
        data: newData,
        idsAlphabetically: getOrderedIds(newData)
      };
    }
    case LOG_DELETE_EMITTED: {
      const newData = {
        ...state.data,
        [action.logId]: undefined
      };

      return {
        ...state,
        data: newData,
        idsAlphabetically: getOrderedIds(newData)
      };
    }
    case GROUP_DELETE_EMITTED: {
      const newData = {
        // This function will start with the original value of `state.data` and
        // loop over each log ID to be deleted setting its data to undefined
        ...action.logIds.reduce((last, logId) => ({
          ...last,
          [logId]: undefined
        }), { ...state.data })
      };

      return {
        ...state,
        data: newData,
        idsAlphabetically: getOrderedIds(newData)
      };
    }
    case ACTIVATE_LOG:
    case PAUSE_LOG:
    case RESUME_LOG:
    case DEACTIVATE_LOG:
    case CLEAR_LOG_OUTPUT:
    case TOGGLE_SCROLL_LOCK:
    case TOGGLE_LOG_EXTRA_ACTIONS_OPEN:
    case ADD_LINE_TO_LOG:
    case SET_LOG_READ:
    case TAIL_ERROR_EMITTED:
    case TOGGLE_EDIT_OPEN:
    case SET_EDITED_NAME:
    case SET_EDITED_GROUP:
    case SET_EDITED_FILE:
    case SET_EDITED_PATH:
    case SAVE_LOG_CHANGES:
    case SAVE_LOG_CHANGES_SUCCESS:
    case SAVE_LOG_CHANGES_FAIL:
    case TOGGLE_DELETE_LOG_OPEN:
    case DELETE_LOG:
    case DELETE_LOG_FAIL:
    case LOG_FILE_CHANGE_EMITTED:
    case LOG_PATH_CHANGE_EMITTED:
      return {
        ...state,
        data: {
          ...state.data,
          [action.logId]: logReducer(state.data[action.logId], action)
        }
      };
    case LOG_NAME_CHANGE_EMITTED:
      // This is the same as the above case but we also recalculate idsAlphabetically
      return {
        ...state,
        data: {
          ...state.data,
          [action.logId]: logReducer(state.data[action.logId], action)
        },
        idsAlphabetically: getOrderedIds({
          ...state.data,
          [action.logId]: { name: action.newName }
        })
      };
    default:
      return state;
  }
}

export function isLoaded(globalState) {
  return globalState.logs && globalState.logs.loaded;
}

export function load() {
  return {
    types: [INITIAL_LOAD, INITIAL_LOAD_SUCCESS, INITIAL_LOAD_FAIL],
    promise: (client) => client.get('/system/getLogs')
  };
}

export function activateLog(logId) {
  return {
    type: ACTIVATE_LOG,
    logId
  };
}

export function pauseLog(logId) {
  return {
    type: PAUSE_LOG,
    logId
  };
}

export function resumeLog(logId) {
  return {
    type: RESUME_LOG,
    logId
  };
}

export function deactivateLog(logId) {
  return {
    type: DEACTIVATE_LOG,
    logId
  };
}

export function clearLogOutput(logId) {
  return {
    type: CLEAR_LOG_OUTPUT,
    logId
  };
}

export function toggleScrollLock(logId) {
  return {
    type: TOGGLE_SCROLL_LOCK,
    logId
  };
}

export function toggleLogExtraActionsOpen(logId) {
  return {
    type: TOGGLE_LOG_EXTRA_ACTIONS_OPEN,
    logId
  };
}

export function addLineToLog(logId, newLine) {
  return {
    type: ADD_LINE_TO_LOG,
    logId,
    newLine
  };
}

export function setLogRead(logId) {
  return {
    type: SET_LOG_READ,
    logId
  };
}

export function toggleEditOpen(logId) {
  return {
    type: TOGGLE_EDIT_OPEN,
    logId
  };
}

export function setEditedName(logId, editedName) {
  return {
    type: SET_EDITED_NAME,
    logId,
    editedName
  };
}

export function setEditedGroup(logId, editedGroup) {
  return {
    type: SET_EDITED_GROUP,
    logId,
    editedGroup
  };
}

export function setEditedPath(logId, editedPath) {
  return {
    type: SET_EDITED_PATH,
    logId,
    editedPath
  };
}

export function setEditedFile(logId, editedFile) {
  return {
    type: SET_EDITED_FILE,
    logId,
    editedFile
  };
}

export function saveLogChanges(logId, logName, oldGroupId, editedName, editedGroupId, editedFile, editedPath) {
  return {
    types: [SAVE_LOG_CHANGES, SAVE_LOG_CHANGES_SUCCESS, SAVE_LOG_CHANGES_FAIL],
    promise: (client) => client.post('/system/saveLogChanges', {
      data: {
        logId,
        oldGroupId,
        editedName,
        editedGroupId,
        editedFile,
        editedPath
      }
    }),
    logId,
    logName
  };
}

export function toggleDeleteLogOpen(logId) {
  return {
    type: TOGGLE_DELETE_LOG_OPEN,
    logId
  };
}

export function deleteLog(groupId, logId, logName) {
  return {
    types: [DELETE_LOG, DELETE_LOG_SUCCESS, DELETE_LOG_FAIL],
    promise: (client) => client.post('/system/deleteLog', {
      data: {
        groupId,
        logId
      }
    }),
    logId,
    logName
  };
}


text:
import requests
import os
import sys
import time
import json
import zipfile
from . parse_urls import parse_urls
import datetime
import shutil

class package_api:
    def __init__(self,dh,dataset,
                 variable_name,
                 longitude_west,
                 longitude_east,
                 latitude_south,
                 latitude_north,
                 reftime_start=None,
                 reftime_end=None,
                 time_start=None,
                 time_end=None,
                 area_name="",folder='./'):
        self.dh = dh
        self.dataset = dataset
        self.variable_name = variable_name
        self.coordinates = (longitude_west,longitude_east,latitude_south,latitude_north)
        if time_start == None or time_end == None:
             self.temporal_extent = ''
        else:
            self.temporal_extent = (time_start,time_end)
        self.reftime_start = reftime_start
        self.reftime_end = reftime_end
        self.variable = variable_name
        self.area_name = area_name
        self.folder = folder
        self.package_key = self.define_package_key()
        self.local_file_name = self.get_local_file_name()

    def make_package(self):
        if self.get_package_exists(): return
        if self.temporal_extent == '':
                kwgs = {'dataset':self.dataset,
                'polygon':'[[{0},{2}],[{1},{2}],[{1},{3}],[{0},{3}],[{0},{2}]]'.format(self.coordinates[0],self.coordinates[1],self.coordinates[2],self.coordinates[3]),
                'grouping':'location',
                'package':self.package_key,
                'var':self.variable_name}
                'time_recent:true'
        else:
            kwgs = {'dataset':self.dataset,
                    'polygon':'[[{0},{2}],[{1},{2}],[{1},{3}],[{0},{3}],[{0},{2}]]'.format(self.coordinates[0],self.coordinates[1],self.coordinates[2],self.coordinates[3]),
                    'grouping':'location',
                    'time_start':self.temporal_extent[0],
                    'time_end':self.temporal_extent[1],
                    'package':self.package_key,
                    'var':self.variable_name}
        if self.reftime_start:
            kwgs.update({'reftime_start':self.reftime_start})
        if self.reftime_end:
            kwgs.update({'reftime_end':self.reftime_start})

        putrequest = "http://{0}/{1}/{2}?apikey={3}".format(self.dh.server,self.dh.version,'packages',self.dh.apikey)
        for i,j in kwgs.items():
            putrequest += "&{0}={1}".format(i,j)
        print("Sending package with PUT {}".format(putrequest))
        mp = requests.put(putrequest)

        if mp.status_code == 200:
            return
        else:
            raise ValueError("Package submittion failed")

    def get_package_exists(self):
        rrr = parse_urls(self.dh.server,self.dh.version,'packages/'+self.package_key,self.dh.apikey)
        return_status = False
        if rrr.r.status_code == 200:
            rjson = rrr.r.json()
            if 'packageResult' in rjson:
                if rjson['packageResult']['success']:
                    print("Package exists")
                    return_status = True
            elif rjson['packageStatus'] == 'started':
                print("Package started")
                return_status = True
            else:
                raise ValueError("Unknown package status, exit")
        return return_status

    def get_status(self):
        rrr = parse_urls(self.dh.server,self.dh.version,'packages/'+self.package_key,self.dh.apikey)
        rjson = rrr.r.json()
        print(rjson)
        if 'packageResult' in rjson:
            if rjson['packageResult']['success'] == True:
                return_status = 'ready'
            else:
                return_status = 'failure'
        else:
            return_status = 'not_ready'
        return return_status

    def define_package_key(self):
        if not self.temporal_extent == '':
            return self.dataset + '_' + iso_time_simplify(self.temporal_extent[0]) + 'to' + \
                   iso_time_simplify(self.temporal_extent[1]) + '_' + self.area_name
        else:
            today = iso_time_simplify(str(datetime.date.today()))
            return self.dataset + '_recent_reftime_' + today + '_' + self.area_name

    def get_local_file_name(self):
        return self.folder + self.package_key + '.nc'

    def wait_for_package_completion(self,maxtime=600):
        check_time = 10
        count = 0
        while count * check_time <= maxtime:
            status = self.get_status()
            if status == 'ready': return True
            elif status == 'not_ready':
                time.sleep(check_time)
            else:
                raise ValueError('Package creation failed')
            count += 1
        return False

    def get_download_path(self):
        return "http://{0}/{1}/packages/{2}/data?apikey={3}".format(self.dh.server,self.dh.version,self.package_key,self.dh.apikey)

    def download_package(self):
        if os.path.exists(self.local_file_name):
            print("File already downloaded")
            return
        if self.wait_for_package_completion():
            r = requests.get(self.get_download_path(),stream = True)
            print("Download response {}".format(r.text))
            print("Download status {}".format(r.status_code))
            print("Download path {}".format(self.get_download_path()))

            if r.status_code == 200:
                 with open(self.package_key + ".zip", "wb") as dat:
                    dat.write(r.content)
            else:
                raise ValueError('Download fails {}'.format(r.text))
            # self.unzip()
        else:
            print("Package was not downloaded and error was not detected. It is safe to run \"download_package\" function as many times as needed.")

    def unzip(self):
        zip_filename = self.package_key + '.zip'
        zip_ref = zipfile.ZipFile(zip_filename, 'r')
        zip_ref.extractall(self.folder)
        if self.temporal_extent == '':
            files = os.listdir(self.folder + 'reference_time')

            os.rename(self.folder + 'reference_time/' + files[-1] + '/data', self.local_file_name)
            shutil.rmtree(self.folder + 'reference_time')

        else:
            os.rename(self.folder + 'data', self.local_file_name)
        os.remove(zip_filename)

def iso_time_simplify(indate):
    return indate.replace(':','').replace('-','')


text:
package org.cagrid.tools.database;

/**
 * @author Stephen Langella
 * @author Scott Oster
 * @author Shannon Hastings
 * @author David Ervin
 */
public class DatabaseException extends Exception {

	public DatabaseException() {
		super();
	}

	public DatabaseException(String message) {
		super(message);
	}

	public DatabaseException(Throwable cause) {
		super(cause);
	}

	public DatabaseException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
<?php

declare(strict_types = 1);

namespace UnitConverter\Calculator\Formula\Length\Mile;

use UnitConverter\Calculator\Formula\AbstractFormula;

/**
 * Formula to convert imperial mile values to metric picometres.
 *
 * @version 1.0.0
 * @since 0.8.4
 * @author Jordan Brauer <18744334+jordanbrauer@users.noreply.github.com>
 */
final class ToPicometres extends AbstractFormula
{
    const FORMULA_STRING = 'mi = pm × 1.609e+15';

    const FORMULA_TEMPLATE = '%smi = %spm × 1.609e+15';

    /**
     * {@inheritDoc}
     */
    public function describe($value, $fromUnits, $toUnits, int $precision = null)
    {
        $result = $this->calculator->mul($value, 1609000000000000);

        $this->plugVariables($result, $value);

        return $result;
    }
}


text:
.PHONY:	build push

PREFIX=gcr.io/google-containers
TAG = 2.0.5

build:
	docker build --pull -t $(PREFIX)/fluentd-gcp:$(TAG) .

push:
	gcloud docker -- push $(PREFIX)/fluentd-gcp:$(TAG)


text:
var menus = [];

// --- menu class ---
function menu (item_struct, pos, styles) {
	// browser check
	this.item_struct = item_struct;
	this.pos = pos;
	this.styles = styles;
	this.id = menus.length;
	this.items = [];
	this.children = [];

	this.add_item = menu_add_item;
	this.hide = menu_hide;

	this.onclick = menu_onclick;
	this.onmouseout = menu_onmouseout;
	this.onmouseover = menu_onmouseover;
	this.onmousedown = menu_onmousedown;

	var i;
	for (i = 0; i < this.item_struct.length; i++)
		new menu_item(i, this, this);
	for (i = 0; i < this.children.length; i++)
		this.children[i].visibility(true);
	menus[this.id] = this;
}
function menu_add_item (item) {
	var id = this.items.length;
	this.items[id] = item;
	return (id);
}
function menu_hide () {
	for (var i = 0; i < this.items.length; i++) {
		this.items[i].visibility(false);
		this.items[i].switch_style('onmouseout');
	}
}
function menu_onclick (id) {
	var item = this.items[id];
	return (item.fields[1] ? true : false);
}
function menu_onmouseout (id) {
	this.hide_timer = setTimeout('menus['+ this.id +'].hide();',
		this.pos['hide_delay'][this.active_item.depth]);
	if (this.active_item.id == id)
		this.active_item = null;
}
function menu_onmouseover (id) {
	this.active_item = this.items[id];
	clearTimeout(this.hide_timer);
	var curr_item, visib;
	for (var i = 0; i < this.items.length; i++) {
		curr_item = this.items[i];
		visib = (curr_item.arrpath.slice(0, curr_item.depth).join('_') ==
			this.active_item.arrpath.slice(0, curr_item.depth).join('_'));
		if (visib)
			curr_item.switch_style (
				curr_item == this.active_item ? 'onmouseover' : 'onmouseout');
		curr_item.visibility(visib);
	}
}
function menu_onmousedown (id) {
	this.items[id].switch_style('onmousedown');
}
// --- menu item Class ---
function menu_item (path, parent, container) {
	this.path = new String (path);
	this.parent = parent;
	this.container = container;
	this.arrpath = this.path.split('_');
	this.depth = this.arrpath.length - 1;
	// get pointer to item's data in the structure
	var struct_path = '', i;
	for (i = 0; i <= this.depth; i++)
		struct_path += '[' + (Number(this.arrpath[i]) + (i ? 2 : 0)) + ']';
	eval('this.fields = this.container.item_struct' + struct_path);
	if (!this.fields) return;

	// assign methods
	this.get_x = mitem_get_x;
	this.get_y = mitem_get_y;
	// these methods may be different for different browsers (i.e. non DOM compatible)
	this.init = mitem_init;
	this.visibility = mitem_visibility;
	this.switch_style = mitem_switch_style;

	// register in the collections
	this.id = this.container.add_item(this);
	parent.children[parent.children.length] = this;

	// init recursively
	this.init();
	this.children = [];
	var child_count = this.fields.length - 2;
	for (i = 0; i < child_count; i++)
		new menu_item (this.path + '_' + i, this, this.container);
	this.switch_style('onmouseout');
}
function mitem_init() {
	document.write (
		'<a id="mi_' + this.container.id + '_'
			+ this.id +'" class="m' + this.container.id + 'l' + this.depth
			+'o" href="' + this.fields[1] + '" style="position: absolute; top: '
			+ this.get_y() + 'px; left: '	+ this.get_x() + 'px; width: '
			+ this.container.pos['width'][this.depth] + 'px; height: '
			+ this.container.pos['height'][this.depth] + 'px; visibility: hidden;'
			+' background: black; color: white; z-index: ' + this.depth + ';" '
			+ 'onclick="return menus[' + this.container.id + '].onclick('
			+ this.id + ');" onmouseout="menus[' + this.container.id + '].onmouseout('
			+ this.id + ');" onmouseover="menus[' + this.container.id + '].onmouseover('
			+ this.id + ');" onmousedown="menus[' + this.container.id + '].onmousedown('
			+ this.id + ');">
'
			+ this.fields[0] + "
\n"
		);
	this.element = document.getElementById('mi_' + this.container.id + '_' + this.id);
}
function mitem_visibility(make_visible) {
	if (make_visible != null) {
		if (this.visible == make_visible) return;
		this.visible = make_visible;
		if (make_visible)
			this.element.style.visibility = 'visible';
		else if (this.depth)
			this.element.style.visibility = 'hidden';
	}
	return (this.visible);
}
function mitem_get_x() {
	var value = 0;
	for (var i = 0; i <= this.depth; i++)
		value += this.container.pos['block_left'][i]
		+ this.arrpath[i] * this.container.pos['left'][i];
	return (value);
}
function mitem_get_y() {
	var value = 0;
	for (var i = 0; i <= this.depth; i++)
		value += this.container.pos['block_top'][i]
		+ this.arrpath[i] * this.container.pos['top'][i];
	return (value);
}
function mitem_switch_style(state) {
	if (this.state == state) return;
	this.state = state;
	var style = this.container.styles[state];
	for (var i = 0; i < style.length; i += 2)
		if (style[i] && style[i+1])
			eval('this.element.style.' + style[i] + "='"
			+ style[i+1][this.depth] + "';");
}
// that's all folks


text:
package com.amazonaws.services.pinpoint.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.pinpoint.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DefaultMessage JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DefaultMessageJsonUnmarshaller implements Unmarshaller<DefaultMessage, JsonUnmarshallerContext> {

    public DefaultMessage unmarshall(JsonUnmarshallerContext context) throws Exception {
        DefaultMessage defaultMessage = new DefaultMessage();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Body", targetDepth)) {
                    context.nextToken();
                    defaultMessage.setBody(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Substitutions", targetDepth)) {
                    context.nextToken();
                    defaultMessage.setSubstitutions(new MapUnmarshaller<String, java.util.List<String>>(context.getUnmarshaller(String.class),
                            new ListUnmarshaller<String>(context.getUnmarshaller(String.class))).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return defaultMessage;
    }

    private static DefaultMessageJsonUnmarshaller instance;

    public static DefaultMessageJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DefaultMessageJsonUnmarshaller();
        return instance;
    }
}


text:
package com.netflix.spinnaker.clouddriver.aws.security.config;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.clouddriver.aws.security.AWSAccountInfoLookup;
import com.netflix.spinnaker.clouddriver.aws.security.AmazonClientProvider;
import com.netflix.spinnaker.clouddriver.aws.security.AmazonCredentials;
import com.netflix.spinnaker.clouddriver.aws.security.DefaultAWSAccountInfoLookup;
import com.netflix.spinnaker.clouddriver.aws.security.config.CredentialsConfig.Account;
import com.netflix.spinnaker.clouddriver.aws.security.config.CredentialsConfig.Region;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class CredentialsLoader<T extends AmazonCredentials> {

    private final AWSCredentialsProvider credentialsProvider;
    private final AWSAccountInfoLookup awsAccountInfoLookup;
    private final Map<String, String> templateValues;
    private final CredentialTranslator<T> credentialTranslator;
    private final ObjectMapper objectMapper;

    public CredentialsLoader(AWSCredentialsProvider credentialsProvider, AmazonClientProvider amazonClientProvider, Class<T> credentialsType) {
        this(credentialsProvider, amazonClientProvider, credentialsType, Collections.<String, String>emptyMap());
    }

    public CredentialsLoader(AWSCredentialsProvider credentialsProvider, AmazonClientProvider amazonClientProvider,Class<T> credentialsType, Map<String, String> templateValues) {
        this(credentialsProvider, new DefaultAWSAccountInfoLookup(credentialsProvider, amazonClientProvider), credentialsType, templateValues);
    }

    public CredentialsLoader(AWSCredentialsProvider credentialsProvider, AWSAccountInfoLookup awsAccountInfoLookup, Class<T> credentialsType) {
        this(credentialsProvider, awsAccountInfoLookup, credentialsType, Collections.<String, String>emptyMap());
    }

    public CredentialsLoader(AWSCredentialsProvider credentialsProvider, AWSAccountInfoLookup awsAccountInfoLookup, Class<T> credentialsType, Map<String, String> templateValues) {
        this.credentialsProvider = Objects.requireNonNull(credentialsProvider, "credentialsProvider");
        this.awsAccountInfoLookup = awsAccountInfoLookup;
        this.templateValues = templateValues;
        this.objectMapper = new ObjectMapper();
        this.credentialTranslator = findTranslator(credentialsType, this.objectMapper);
    }

    private Lazy<List<Region>> createDefaults(final List<Region> defaults) {
        return new Lazy<>(new Lazy.Loader<List<Region>>() {
            @Override
            public List<Region> get() {
                if (defaults == null) {
                    return toRegion(awsAccountInfoLookup.listRegions());
                } else {
                    List<Region> result = new ArrayList<>(defaults.size());
                    List<String> toLookup = new ArrayList<>();
                    for (Region def : defaults) {
                        if (def.getAvailabilityZones() == null || def.getAvailabilityZones().isEmpty()) {
                            toLookup.add(def.getName());
                        } else {
                            result.add(def);
                        }
                    }
                    if (!toLookup.isEmpty()) {
                        List<Region> resolved = toRegion(awsAccountInfoLookup.listRegions(toLookup));
                        for (Region region : resolved) {
                            Region fromDefault = find(defaults, region.getName());
                            if (fromDefault != null) {
                                region.setPreferredZones(fromDefault.getPreferredZones());
                                region.setDeprecated(fromDefault.getDeprecated());
                            }
                        }
                        result.addAll(resolved);
                    }
                    return result;
                }
            }
        });
    }

    private List<Region> initRegions(Lazy<List<Region>> defaults, List<Region> toInit) {
        if (toInit == null) {
            return defaults.get();
        }

        Map<String, Region> toInitByName = toInit.stream().collect(
            Collectors.toMap(Region::getName, Function.identity())
        );

        List<Region> result = new ArrayList<>(toInit.size());
        List<String> toLookup = new ArrayList<>();
        for (Region r : toInit) {
            if (r.getAvailabilityZones() == null || r.getAvailabilityZones().isEmpty()) {
                toLookup.add(r.getName());
            } else {
                result.add(r);
            }
        }

        for (Iterator<String> lookups = toLookup.iterator(); lookups.hasNext(); ) {
            Region fromDefault = find(defaults.get(), lookups.next());
            if (fromDefault != null) {
                lookups.remove();
                result.add(fromDefault);
            }
        }
        if (!toLookup.isEmpty()) {
            List<Region> resolved = toRegion(awsAccountInfoLookup.listRegions(toLookup));
            for (Region region : resolved) {
              Region src = find(toInit, region.getName());
              if (src == null || src.getPreferredZones() == null) {
                src = find(defaults.get(), region.getName());
              }

              if (src != null) {
                region.setPreferredZones(src.getPreferredZones());
              }
            }
            result.addAll(resolved);
        }

        // make a clone of all regions such that modifications apply only to this specific instance (and not global defaults)
        result = result.stream().map(Region::copyOf).collect(Collectors.toList());

        for (Region r : result) {
          Region toInitRegion = toInitByName.get(r.getName());
          if (toInitRegion != null && toInitRegion.getDeprecated() != null) {
            r.setDeprecated(toInitRegion.getDeprecated());
          }
        }

        return result;
    }

    private static Region find(List<Region> src, String name) {
        if (src != null) {
            for (Region r : src) {
                if (r.getName().equals(name)) {
                    return r;
                }
            }
        }
        return null;
    }

    private static List<Region> toRegion(List<AmazonCredentials.AWSRegion> src) {
        List<Region> result = new ArrayList<>(src.size());
        for (AmazonCredentials.AWSRegion r : src) {
            Region region = new Region();
            region.setName(r.getName());
            region.setAvailabilityZones(new ArrayList<>(r.getAvailabilityZones()));
            region.setPreferredZones(new ArrayList<>(r.getPreferredZones()));
            result.add(region);
        }
        return result;
    }

    public T load(String accountName) throws Throwable {
        CredentialsConfig config = new CredentialsConfig();
        Account account = new Account();
        account.setName(accountName);
        config.setAccounts(Arrays.asList(account));
        List<T> result = load(config);
        if (result.size() != 1) {
            throw new IllegalStateException("failed to create account");
        }
        return result.get(0);
    }

    public List<T> load(CredentialsConfig source) throws Throwable {
        final CredentialsConfig config = objectMapper.convertValue(source, CredentialsConfig.class);

        if (config.getAccounts() == null || config.getAccounts().isEmpty()) {
            return Collections.emptyList();
        }

        Lazy<List<Region>> defaultRegions = createDefaults(config.getDefaultRegions());
        List<T> initializedAccounts = new ArrayList<>(config.getAccounts().size());
        for (Account account : config.getAccounts()) {
            if (account.getAccountId() == null) {
                if (!credentialTranslator.resolveAccountId()) {
                    throw new IllegalArgumentException("accountId is required and not resolvable for this credentials type");
                }
                account.setAccountId(awsAccountInfoLookup.findAccountId());
            }

            if (account.getEnvironment() == null) {
                account.setEnvironment(account.getName());
            }

            if (account.getAccountType() == null) {
                account.setAccountType(account.getName());
            }

            account.setRegions(initRegions(defaultRegions, account.getRegions()));
            account.setDefaultSecurityGroups(account.getDefaultSecurityGroups() != null ? account.getDefaultSecurityGroups() : config.getDefaultSecurityGroups());
            account.setLifecycleHooks(account.getLifecycleHooks() != null ? account.getLifecycleHooks() : config.getDefaultLifecycleHooks());

            Map<String, String> templateContext = new HashMap<>(templateValues);
            templateContext.put("name", account.getName());
            templateContext.put("accountId", account.getAccountId());
            templateContext.put("environment", account.getEnvironment());
            templateContext.put("accountType", account.getAccountType());

            account.setDefaultKeyPair(templateFirstNonNull(templateContext, account.getDefaultKeyPair(), config.getDefaultKeyPairTemplate()));
            account.setEdda(templateFirstNonNull(templateContext, account.getEdda(), config.getDefaultEddaTemplate()));
            account.setFront50(templateFirstNonNull(templateContext, account.getFront50(), config.getDefaultFront50Template()));
            account.setDiscovery(templateFirstNonNull(templateContext, account.getDiscovery(), config.getDefaultDiscoveryTemplate()));
            account.setAssumeRole(templateFirstNonNull(templateContext, account.getAssumeRole(), config.getDefaultAssumeRole()));
            account.setSessionName(templateFirstNonNull(templateContext, account.getSessionName(), config.getDefaultSessionName()));
            account.setBastionHost(templateFirstNonNull(templateContext, account.getBastionHost(), config.getDefaultBastionHostTemplate()));

            if (account.getLifecycleHooks() != null) {
                for (CredentialsConfig.LifecycleHook lifecycleHook : account.getLifecycleHooks()) {
                  lifecycleHook.setRoleARN(templateFirstNonNull(templateContext, lifecycleHook.getRoleARN(), config.getDefaultLifecycleHookRoleARNTemplate()));
                  lifecycleHook.setNotificationTargetARN(templateFirstNonNull(templateContext, lifecycleHook.getNotificationTargetARN(), config.getDefaultLifecycleHookNotificationTargetARNTemplate()));
                }
            }

            initializedAccounts.add(credentialTranslator.translate(credentialsProvider, account));
        }
        return initializedAccounts;
    }

    private static class Lazy<T> {
        public static interface Loader<T> {
            T get();
        }

        private final Loader<T> loader;
        private final AtomicReference<T> ref = new AtomicReference<>();

        public Lazy(Loader<T> loader) {
            this.loader = loader;
        }

        public T get() {
            if (ref.get() == null) {
                ref.set(loader.get());
            }
            return ref.get();
        }
    }

    private static String templateFirstNonNull(Map<String, String> substitutions, String... values) {
        for (String value : values) {
            if (value != null) {
                return StringTemplater.render(value, substitutions);
            }
        }
        return null;
    }

    static <T extends AmazonCredentials> CredentialTranslator<T> findTranslator(Class<T> credentialsType, ObjectMapper objectMapper) {
        return new CopyConstructorTranslator<>(objectMapper, credentialsType);
    }

    static interface CredentialTranslator<T extends AmazonCredentials> {
        Class<T> getCredentialType();

        boolean resolveAccountId();

        T translate(AWSCredentialsProvider credentialsProvider, Account account) throws Throwable;
    }

    static class CopyConstructorTranslator<T extends AmazonCredentials> implements CredentialTranslator<T> {

        private final ObjectMapper objectMapper;
        private final Class<T> credentialType;
        private final Constructor<T> copyConstructor;

        public CopyConstructorTranslator(ObjectMapper objectMapper, Class<T> credentialType) {
            this.objectMapper = objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            this.credentialType = credentialType;
            try {
                copyConstructor = credentialType.getConstructor(credentialType, AWSCredentialsProvider.class);
            } catch (NoSuchMethodException nsme) {
                throw new IllegalArgumentException("Class " + credentialType + " must supply a constructor with " + credentialType + ", " + AWSCredentialsProvider.class + " args.");
            }
        }

        @Override
        public Class<T> getCredentialType() {
            return credentialType;
        }

        @Override
        public boolean resolveAccountId() {
            try {
                credentialType.getMethod("getAssumeRole");
                return false;
            } catch (NoSuchMethodException nsme) {
                return true;
            }
        }

        @Override
        public T translate(AWSCredentialsProvider credentialsProvider, Account account) throws Throwable {
            T immutableInstance = objectMapper.convertValue(account, credentialType);
            try {
                return copyConstructor.newInstance(immutableInstance, credentialsProvider);
            } catch (InvocationTargetException ite) {
                throw ite.getTargetException();
            }
        }
    }

    static class StringTemplater {
        public static String render(String template, Map<String, String> substitutions) {
            String base = template;
            int iterations = 0;
            boolean changed = true;
            while (changed && iterations < 10) {
                iterations++;
                String previous = base;
                for (Map.Entry<String, String> substitution : substitutions.entrySet()) {
                    base = base.replaceAll(Pattern.quote("{{" + substitution.getKey() + "}}"), substitution.getValue());
                }
                changed = !previous.equals(base);
            }
            if (changed) {
                throw new RuntimeException("too many levels of templatery");
            }
            return base;
        }
    }
}


text:
from ast import *
import pprint
import colors

init = {
    '__parent__': None,
    '__len__': 0,
    '__children__': [],
    'print': (Value(tycon=TyCon(name="fn", type=(string_type, unit_type)), id='print'), 4),
    'muli': (Value(tycon=TyCon(name="fn", type=(
        TyCon(name="record", type={1: int_type, 2: int_type}), int_type)), id='muli'), 8),

    'addi': (Value(tycon=TyCon(name="fn", type=(
        TyCon(name="record", type={1: int_type, 2: int_type}), int_type)), id='addi'), 12),
    'intToStr': (Value(tycon=TyCon(name="fn", type=(int_type, string_type)), id='intToStr'), 16),
    'realToStr': (Value(tycon=TyCon(name="fn", type=(real_type, string_type)), id='realToStr'), 20),
    'subi': (Value(tycon=TyCon(name="fn", type=(
        TyCon(name="record", type={1: int_type, 2: int_type}), int_type)), id='subi'), 24),
}

def typecheck(p):
    if type(p) == Declaration:
        init["__children__"] = []
        init["__len__"] = 0
        if "it" in init:
            del init["it"]
        p.checkType(init)

    print(colors.success("Type Check finished! The Symbol Table is:"))
    pprint.pprint(init)

    return init


text:
package me.termax.practice.lab04;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main extends Application {

    private Pattern currentPattern;
    private Map<String, Pattern> patternMap;
    private Label status;
    private TextField textField;

    private void updateStatus(String text) {
        status.setTextFill(currentPattern.matcher(text).matches()?Color.GREEN:Color.RED);
    }

    @Override
    public void start(Stage primaryStage) {

        patternMap = new HashMap<String, Pattern>() {{
            put("Natural number", Pattern.compile("[1-9]\\d*"));
            put("Integer", Pattern.compile("([+-]?[1-9]\\d*|0)"));
            put("Float", Pattern.compile("[+-]?((\\d+\\.\\d*)|(\\d*\\.?\\d+))([eE][-+]?\\d+)?"));;
            put("Date", Pattern.compile("(((0[1-9]|[12][0-9]|3[01])\\.(0[13578]|10|12))|((0[1-9]|[12][0-9]|30)\\.(0[469]|11))|((0[1-9]|[12][0-9])\\.02))\\.(19|20)\\d\\d"));
            put("Time", Pattern.compile("([01]?[0-9]|2[0-3])[: ][0-5][0-9]([: ][0-5][0-9])?"));
            put("Email", Pattern.compile("(\\w+\\.?)+@(\\w+_?)+\\.\\w{2,}"));
        }};

        final ComboBox<String> patternSelect = new ComboBox<>();
        patternSelect.getItems().addAll(
                "Natural number",
                "Integer",
                "Float",
                "Date",
                "Time",
                "Email"
        );

        status = new Label("\uD83C\uDF11");
        status.setTextFill(Color.RED);

        textField = new TextField ();
        textField.textProperty().addListener((observable, oldValue, newValue) -> updateStatus(newValue));

        patternSelect.valueProperty().addListener((observable, oldValue, newValue) -> {
            currentPattern = patternMap.get(newValue);
            updateStatus(textField.getText());
        });
        patternSelect.setValue("Natural number");

        ListView<String> dates = new ListView<>();
        dates.setPrefWidth(100);

        TextArea textArea = new TextArea();
        textArea.setPrefWidth(215);
        textArea.textProperty().addListener((observable, oldValue, newValue) -> {
            dates.getItems().clear();
            Matcher m = patternMap.get("Date").matcher(newValue);
            while (m.find())
                dates.getItems().add(m.group());
        });

        HBox task1 = new HBox();
        task1.setSpacing(10);
        task1.getChildren().addAll(patternSelect, textField, status);

        HBox task2 = new HBox();
        task2.setSpacing(5);
        task2.getChildren().addAll(textArea, dates);

        VBox root = new VBox();
        root.setSpacing(30);
        root.getChildren().addAll(task1, task2);

        Scene scene = new Scene(root, 320, 200);
        primaryStage.setTitle("Lab 4");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}


text:
package com.manning.hip.ch3;

import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.Text;

public class TextArrayWritable extends ArrayWritable {
  public TextArrayWritable() {
    super(Text.class);
  }

  public TextArrayWritable(Text[] strings) {
    super(Text.class, strings);
  }
}