text:
package SaplingSubsys;

    use strict;
    use Tracer;
    use PageBuilder;
    use FIG;
    use Sprout;
    use Data::Dumper;

=head1 Sapling Subsystem Object

=head2 Introduction

This object emulates the capabilities of the FIG-style C<Subsystem> object, but
uses Sapling methods to retrieve the data. This object can be dropped in place of
the UnvSubsys object to create subsystem displays for the Sapling rather than the
SEED.

The structure created by the constructor contains the following data members.

=over 4

=item name

Name of the subsystem. This is needed for any further database accesses required.

=item curator

Name of the subsystem's official curator.

=item notes

General notes about the subsystem.

=item sapling

Sapling object for accessing the database. This is a genuine Sapling object, not
an SFXlate object.

=item genomeHash

Map of genome IDs to row indices.

=item genomes

List of [genomeID, variantCode] tuples in row order.

=item roleHash

Map of role IDs and abbreviations to column indices. In other words, plugging
either a full-blown role ID or its abbreviation into this hash will return
the role's column index.

=item roles

List of [roleID, abbreviation] tuples in column order.

=item dir

Directory root for the diagram and image files.

=item reactionHash

Map of role IDs to a list of the reactions catalyzed by the role.

=item hopeReactions

Map of roles to EC numbers for the Hope reactions. This object is not loaded
until it is needed.

=item rows

Map of spreadsheet rows, keyed by genome ID. Each row is a list of cells. Each
cell is a list of feature ID.

=item featureData

Hash mapping feature IDs to assigned functions.

=back

=cut

#: Constructor SaplingSubsys->new();

=head2 Public Methods

=head3 new

    my $sub = SaplingSubsys->new($subName, $sapling);

Load the subsystem.

=over 4

=item subName

Name of the desired subsystem.

=item sapling

Sapling object for accessing the Sapling data store.

=back

=cut

sub new {
    # Get the parameters.
    my ($class, $subName, $sapling) = @_;
    # Declare the return value.
    my $retVal;
    # Get the subsystem's object.
    my $subsystemObject = $sapling->GetEntity('Subsystem', $subName);
    # Only proceed if we found it.
    if (defined $subsystemObject) {
        # We've found it, so get the major data.
        my ($curator, $notes, $description, $version) = $subsystemObject->Values(['Subsystem(curator)', 'Subsystem(notes)',
                                                            'Subsystem(description)', 'Subsystem(version)']);
        # Get the genome IDs and variant codes for the rows. The list returned
        # by GetAll will be a list of 2-tuples, each consisting of a genome ID
        # and a subsystem variant code.
        my @genomes = $sapling->GetAll("Genome Uses MolecularMachine Implements Variant IsDescribedBy Subsystem",
                               'Subsystem(id) = ? ORDER BY Variant(id), Genome(id)',
                               [$subName], [qw(Genome(id) Variant(id))]);

        # Remove the subsystem name from the variant code.
        @genomes = map { my ($x, $y) = @$_; $y =~s/^.*://; [$x, $y] } @genomes;

        #Sprout version
        #my @genomes = $sprout->GetAll(['ParticipatesIn'],
        #                              'ParticipatesIn(to-link) = ? ORDER BY ParticipatesIn(variant-code), ParticipatesIn(from-link)',
        #                              [$subName], ['ParticipatesIn(from-link)',
        #                                           'ParticipatesIn(variant-code)']);

        # Create the genome ID directory. This is a hash that maps a genome ID to its
        # row index.
        my $idx = 0;
        my %genomeHash = map { $_->[0] => $idx++ } @genomes;
        # Get the role IDs and abbreviations. The list returned by GetAll will be
        # a list of 2-tuples, each consisting of a role ID and abbreviation. The
        # 2-tuples will be ordered by the spreadsheet column number.

        my @roles = $sapling->GetAll("Subsystem Includes Role",
                               'Subsystem(id) = ? ORDER BY Includes(sequence)',
                               [$subName], [qw(Role(id) Includes(abbreviation))]);

        #Sprout Version
        #my @roles = $sprout->GetAll(['OccursInSubsystem'],
        #                            'OccursInSubsystem(to-link) = ? ORDER BY OccursInSubsystem(column-number)',
        #                            [$subName], ['OccursInSubsystem(from-link)', 'OccursInSubsystem(abbr)',
        #                                         'OccursInSubsystem(auxiliary)']);

        # Now we need to create the role ID directory, which maps role IDs and their
        # abbreviations to column numbers.
        my %roleHash = ();
        my %abbrHash = ();
        my %auxHash = ();
        for ($idx = 0; $idx <= $#roles; $idx++) {
            # Get the role ID, aux flag, and abbreviation for this column's role.
            my ($roleID, $abbr, $aux) = @{$roles[$idx]};
            # Put the ID and abbreviation in the role directory.
            $roleHash{$roleID} = $idx;
            $roleHash{$abbr} = $idx;
            # Put the aux flag in the aux hash.
            $auxHash{$roleID} = $aux;
            # Put the full name in the abbreviation directory.
            $abbrHash{$abbr} = $roleID;
        }
        # Find the subsystem directory.
        my $subDir = Subsystem::get_dir_from_name($subName);
        Trace("Subsystem directory is $subDir.") if T(3);
        # Create the subsystem object.
        $retVal = {
                    # Name of the subsystem. This is needed for any further database
                    # accesses required.
                    name => $subName,
                    # Directory root for diagram and image files.
                    dir => $subDir,
                    # Name of the subsystem's official curator.
                    curator => $curator,
                    # General notes about the subsystem.
                    notes => $notes,
                    # Sprout object for accessing the database.
                    sapling => $sapling,
                    # Map of genome IDs to row indices.
                    genomeHash => \%genomeHash,
                    # List of [genomeID, variantCode] tuples in row order.
                    genomes => \@genomes,
                    # Map of role IDs and abbreviations to column indices.
                    roleHash => \%roleHash,
                    # List of [roleID, abbreviation] tuples in column order.
                    roles => \@roles,
                    # Map of abbreviations to role names.
                    abbrHash => \%abbrHash,
                    # Map of auxiliary rols.
                    auxHash => \%auxHash,
                    # Map of role IDs to reactions.
                    reactionHash => undef,
                    # Version number.
                    version => $version,
                    # Row hash, initially undefined.
                    rows => undef,
                    # Map of feature IDs to functional assignments
                    featureData => {},
                };
        # Bless and return it.
        bless $retVal, $class;
    }
    return $retVal;
}

=head3 is_aux_role

    my $flag = $sub->is_aux_role($roleID);

Return TRUE if the specified role is auxiliary to this subsystem, FALSE
if it is essential to it.

=over 4

=item roleID

ID of the relevant role.

=item RETURN

Returns TRUE if the specified role is auxiliary, else FALSE.

=back

=cut

sub is_aux_role {
    # Get the parameters.
    my ($self, $roleID) = @_;
    # Declare the return variable.
    my $retVal = $self->{auxHash}->{$roleID};
    # Return the result.
    return $retVal;
}

=head3 get_row

    my $rowData = $sub->get_row($rowIndex);

Return the specified row in the subsystem spreadsheet. The row consists
of a list of lists. Each position in the major list represents the role
for that position, and contains a list of the IDs for the features that
perform the role.

=over 4

=item rowIndex

Index of the row to return. A row contains data for a single genome.

=item RETURN

Returns a reference to a list of lists. Each element in the list represents
a spreadsheet column (role) and contains a list of features that perform the
role.

=back

=cut

sub get_row {
    # Get the parameters.
    my ($self, $rowIndex) = @_;
    # Get the genome ID for the specified row's genome.
    my $genomeID = $self->{genomes}->[$rowIndex]->[0];
    # Get the row hash.
    my $rowHash = $self->_get_spreadsheet();
    # Declare the return variable.
    my @retVal;
    # If this genome does not exist for the subsystem, all the cells are empty.
    if (! exists $rowHash->{$genomeID}) {
        @retVal = map { [] } @{$self->{roles}};
    } else {
        # Here we just return the row.
        push @retVal, @{$rowHash->{$genomeID}};
    }
    # Return the result.
    return \@retVal;
}

=head3 get_roles_for_genome

    my @roles = $sub->get_roles_for_genome($genome_id);

Return a list of the roles in this subsystem that have nonempty
spreadsheet cells for the given genome.

=over 4

=item genome_id

ID of the relevant genome.

=item RETURN

Returns a list of role IDs.

=back

=cut

sub get_roles_for_genome {
    # Get the parameters.
    my ($self, $genome_id, $peg) = @_;
    # Get the subsystem's spreadsheet.
    my $rowHash = $self->_get_spreadsheet();
    # Declare the return variable.
    my @retVal;
    # Only proceed if this genome exists for this subsyste,
    if (exists $rowHash->{$genome_id}) {
        # Get the role list.
        my $roles = $self->{roles};
        # Get the row's cell list.
        my $row = $rowHash->{$genome_id};
        # Loop through the cells. We'll save the role name for each
        # nonempty cell.
        my $cols = scalar @$roles;
        for (my $i = 0; $i < $cols; $i++) {
            my $cell = $row->[$i];
#print STDERR Dumper $cell;
            if (scalar @$cell) {
		if (defined($peg)) {
			push @retVal, [$roles->[$i][0], $cell];
		} else {
			push @retVal, $roles->[$i][0];
		}
            }
        }
    }
    # Return the result.
    return @retVal;
}

=head3 get_abbr_for_role

    my $abbr = $sub->get_abbr_for_role($name);

Get this subsystem's abbreviation for the specified role.

=over 4

=item name

Name of the relevant role.

=item RETURN

Returns the abbreviation for the role. Each subsystem has its own abbreviation
system; the abbreviations make it easier to display the subsystem spreadsheet.

=back

=cut

sub get_abbr_for_role {
    # Get the parameters.
    my ($self, $name) = @_;
    # Get the index for this role.
    my $idx = $self->get_role_index($name);
    # Return the abbreviation.
    return $self->get_role_abbr($idx);
}

=head3 get_genomes

    my @genomeList = $sub->get_genomes();

Return a list of the genome IDs for this subsystem. Each genome corresponds to a row
in the subsystem spreadsheet. Indexing into this list returns the ID of the genome
in the specified row.

=cut

sub get_genomes {
    # Get the parameters.
    my ($self) = @_;
    # Return a list of the genome IDs. The "genomes" member contains a 2-tuple
    # with the genome ID followed by the variant code. We only return the
    # genome IDs.
    my @retVal = map { $_->[0] } @{$self->{genomes}};
    return @retVal;
}

=head3 get_variant_code

    my $code = $sub->get_variant_code($gidx);

Return the variant code for the specified genome. Each subsystem has multiple
variants which involve slightly different chemical reactions, and each variant
has an associated variant code. When a genome is connected to the spreadsheet,
the subsystem variant used by the genome must be specified.

=over 4

=item gidx

Row index for the genome whose variant code is desired.

=item RETURN

Returns the variant code for the specified genome.

=back

=cut

sub get_variant_code {
    # Get the parameters.
    my ($self, $gidx) = @_;
    # Extract the variant code for the specified row index. It is the second
    # element of the tuple from the "genomes" member.
    my $retVal = $self->{genomes}->[$gidx]->[1];
    return $retVal;
}

=head3 get_curator

    my $userName = $sub->get_curator();

Return the name of this subsystem's official curator.

=cut

sub get_curator {
    # Get the parameters.
    my ($self) = @_;
    # Return the curator member.
    return $self->{curator};
}

=head3 get_notes

    my $text = $sub->get_notes();

Return the descriptive notes for this subsystem.

=cut

sub get_notes {
    # Get the parameters.
    my ($self) = @_;
    # Return the notes member.
    return $self->{notes};
}

=head3 get_description

    my $text = $sub->get_description();

Return the description for this subsystem.

=cut

sub get_description
{
    my($self) = @_;
    return $self->{description};
}

=head3 get_roles

    my @roles = $sub->get_roles();

Return a list of the subsystem's roles. Each role corresponds to a column
in the subsystem spreadsheet. The list entry at a specified position in
the list will contain the ID of that column's role.

=cut

sub get_roles {
    # Get the parameters.
    my ($self) = @_;
    # Return the list of role IDs. The role IDs are stored as the first
    # element of each 2-tuple in the "roles" member.
    my @retVal = map { $_->[0] } @{$self->{roles}};
    return @retVal;
}

=head3 get_reactions

    my $reactHash = $sub->get_reactions();

Return a reference to a hash that maps each role ID to a list of the reactions
catalyzed by the role.

=cut

sub get_reactions {
    # Get the parameters.
    my ($self) = @_;
    # Do we already have a reaction hash?
    my $retVal = $self->{reactionHash};
    if (! $retVal) {
        # No, so we'll build it.
        $retVal = {};
        my $sapling = $self->{sapling};
        for my $roleID ($self->get_roles()) {
            # Get this role's reactions.
	    my @reactions = $sapling->GetFlat("Role IsInCombination RoleSet Triggers Reaction",
                               'Role(id) = ?',
                               [$roleID],
                               'Reaction(id)');
            #sprout version
   	    #my @reactions = $sprout->GetFlat(['Catalyzes'], 'Catalyzes(from-link) = ?',
            #                                 [$roleID], 'Catalyzes(to-link)');
            # Put them in the reaction hash.
            if (@reactions > 0) {
                $retVal->{$roleID} = \@reactions;
            }
        }
        # Save it for future use.
        $self->{reactionHash} = $retVal;
    }
    # Return the reaction hash.
    return $retVal;
}

=head3 geo_role_abbr

    my $abbr = $sub->get_role_abbr($ridx);

Return the abbreviation for the role in the specified column. The abbreviation
is a shortened identifier that is not necessarily unique, but is more likely to
fit in a column heading.

=over 4

=item ridx

Column index for the role whose abbreviation is desired.

=item RETURN

Returns an abbreviated name for the role corresponding to the indexed column.

=back

=cut

sub get_role_abbr {
    # Get the parameters.
    my ($self, $ridx) = @_;
    # Return the role abbreviation. The abbreviation is the second element
    # in the 2-tuple for the specified column in the "roles" member.
    my $retVal = $self->{roles}->[$ridx]->[1];
    return $retVal;
}

=head3 get_hope_reactions_for_genome

    my %ss_reactions = $subsys->get_hope_reactions_for_genome($genome);

This method returns a hash that maps reactions to the pegs that catalyze
them for the specified genome. For each role in the subsystem, the pegs
are computed, and these are attached to the reactions for the role.

=over 4

=item genome

ID of the genome whose reactions are to be put into the hash.

=item RETURN

Returns a hash mapping reactions in the subsystem to pegs in the
specified genome, or an empty hash if the genome is not found in the
subsystem.

=back

=cut

sub get_hope_reactions_for_genome {
    # Get the parameters.
    my($self, $genome) = @_;
    # Declare the return variable.
    my %retVal;
    # Look for the genome in our spreadsheet.
    my $index = $self->get_genome_index($genome);
    # Only proceed if we found it.
    if (defined $index) {
        # Extract the roles.
        my @roles = $self->get_roles;
        # Get the hope reaction hash. For each role, this gives us a list
        # of reactions.
        my %hope_reactions = $self->get_hope_reactions();
        # Loop through the cells in this genome's role.
        for my $role (@roles) {
            # Get the features in this role's cell.
            my @peg_list = $self->get_pegs_from_cell($genome,$role);
            # Only proceed if we have hope reactions AND pegs for this role.
            if (defined $hope_reactions{$role} && scalar @peg_list > 0) {
                # Loop through the reactions, pushing the pegs in this cell onto
                # the reaction's peg list.
                for my $reaction (@{$hope_reactions{$role}}) {
                    push @{$retVal{$reaction}}, @peg_list;
                }
            }
        }
    }
    # Return the result.
    return %retVal;
}

=head3 get_hope_additional_reactions

    my %ss_reactions = $subsys->get_hope_additional_reactions($scenario_name);

Return a list of the additional reactions for the specified scenario.

=over 4

=item scenario_name

Name of the scenario whose additional reactions are desired.

=item RETURN

Returns a list of the additional reactions attached to the named scenario.

=back

=cut

sub get_hope_additional_reactions {
    # Get the parameters.
    my($self, $scenario_name) = @_;
    # Ask the database for this scenario's additional reactions.

    my @retVal = $self->{sapling}->GetFlat("Scenario HasParticipant Reaction",
                               'Scenario(id) = ?', [$scenario_name], [qw(Scenario(id)
                               Reaction(id))]);

    #sprout version
    #my @retVal = $self->{sprout}->GetFlat(['IncludesReaction'], "IncludesReaction(from-link) = ?",
    #                                      [$scenario_name], 'IncludesReaction(to-link)');

    return @retVal;
}

=head3 get_hope_reactions

    my %reactionHash = $subsys->get_hope_reactions();

Return a hash mapping the roles of this subsystem to the EC numbers for
the reactions used in scenarios (if any). It may return an empty hash
if the Hope reactions are not yet known.

=cut

sub get_hope_reactions {
    # Get the parameters.
    my ($self) = @_;
    # Try to get the hope reactions from the object.
    my $retVal = $self->{hopeReactions};
    if (! defined($retVal)) {
        # They do not exist, so we must create them. Make a copy of the role-to-reaction
        # hash.
        my %hopeHash = %{$self->get_reactions()};
        # Insure we have it if we need it again.
        $retVal = \%hopeHash;
        $self->{hopeReactions} = $retVal;
    }
    # Return the result.
    return %{$retVal};
}

=head3 get_hope_reaction_notes

    my %roleHash = $sub->get_hope_reaction_notes();

Return a hash mapping the roles of the subsystem to any existing notes
about the relevant reactions.

=cut

sub get_hope_reaction_notes {
    # Get the parameters.
    my ($self) = @_;
    # Declare the return variable.
    my %retVal;
    # Get the database object.
    my $sapling = $self->{sapling};
    # Get our name.
    my $ssName = $self->{name};
    # Loop through the roles, getting each role's hope notes.
    for my $role ($self->get_roles()) {
        my ($note) = $self->get_hope_reaction_note($role);
        # If this role had a nonempty note, stuff it in the hash.
        if ($note) {
            $retVal{$role} = $note;
        }
    }
    # Return the result.
    return %retVal;
}

=head3 get_hope_reaction_note

    my $note = $sub->get_hope_reaction_note($role);

Return the text note about the curation of the scenario reactions
relating to this role.

=over 4

=item role

ID of the role whose note is desired.

=item RETURN

Returns the relevant role's note for this subsystem's hope reactions, or FALSE (empty string
or undefined) if no such note was found.

=back

=cut

sub get_hope_reaction_note {
    # Get the parameters.
    my ($self, $role) = @_;
    # Ask the database for the note.

    #no Sapling equivalent
    return undef;

    #sprout version
    #my ($retVal) = $self->{sprout}->GetFlat(['OccursInSubsystem'],
    #                                        "OccursInSubsystem(from-link) = ? AND OccursInSubsystem(to-link) = ?",
    #                                        [$role, $self->{name}], 'OccursInSubsystem(hope-reaction-note)');
    # Return the result.
    #return $retVal;
}

=head3 get_role_index

    my $idx = $sub->get_role_index($role);

Return the column index for the role with the specified ID.

=over 4

=item role

ID (full name) or abbreviation of the role whose column index is desired.

=item RETURN

Returns the column index for the role with the specified name or abbreviation.

=back

=cut

sub get_role_index {
    # Get the parameters.
    my ($self, $role) = @_;
    # The role index is directly available from the "roleHash" member.
    my $retVal = $self->{roleHash}->{$role};
    return $retVal;
}

=head3 pegs_for_role

    my @pegs = $sub->pegs_for_role($role);

This method will return a list of the features in the cells for the
specified role.

=over 4

=item role

Name of the role whose pegs are desired.

=item RETURN

Returns a list of the features in the role's column of the spreadsheet.
If the role does not exist, an empty list will be returned.

=back

=cut

sub pegs_for_role {
    # Get the parameters.
    my ($self, $role) = @_;
    # Declare the return variable.
    my @retVal;
    # Compute the column number for this role.
    my $idx = $self->get_role_index($role);
    Trace("Role index for \"$role\" is $idx.") if T(3);
    # Only proceed if we actually found the role.
    if (defined $idx) {
        # Get all the cells in the role's column.
        my $cells = $self->get_col($idx);
        # Loop through the cells, returning the pegs.
        for my $cell (@$cells) {
                push @retVal, @$cell;
        }
    }
    # Return the result.
    return @retVal;
}

=head3 get_genome_index

    my $idx = $sub->get_genome_index($genome);

Return the row index for the genome with the specified ID.

=over 4

=item genome

ID of the genome whose row index is desired.

=item RETURN

Returns the row index for the genome with the specified ID, or an undefined
value if the genome does not participate in the subsystem.

=back

=cut

sub get_genome_index {
    # Get the parameters.
    my ($self, $genome) = @_;
    # Get the genome row index from the "genomeHash" member.
    my $retVal = $self->{genomeHash}->{$genome};
    return $retVal;
}

=head3 get_pegs_from_cell

    my @pegs = $sub->get_pegs_from_cell($rowstr, $colstr);

Return a list of the peg IDs for the features in the specified spreadsheet cell.

=over 4

=item rowstr

Genome row, specified either as a row index or a genome ID.

=item colstr

Role column, specified either as a column index, a role name, or a role
abbreviation.

=item RETURN

Returns a list of PEG IDs. The PEGs in the list belong to the genome in the
specified row and perform the role in the specified column. If the indicated
row and column does not exist, returns an empty list.

=back

=cut

sub get_pegs_from_cell {
    # Get the parameters.
    my ($self, $rowstr, $colstr) = @_;
    # Get the sprout object for accessing the database.
    my $sapling = $self->{sapling};
    # We need to convert the incoming row and column identifiers. We need a
    # numeric column index and a character genome ID to create the ID for the
    # subsystem spreadsheet cell. First, the column index: note that our version
    # of "get_role_index" conveniently works for both abbreviations and full role IDs.
    my $colIdx = ($colstr =~ /^(\d+)$/ ? $colstr : $self->get_role_index($colstr));
    # Next the genome ID. In this case, we convert any number we find to a string.
    # This requires a little care to avoid a run-time error if the row number is
    # out of range.
    my $genomeID = $rowstr;
    if ($rowstr =~ /^(\d+)$/) {
        # Here we need to convert the row number to an ID. Insure the number is in
        # range. Note that if we do have a row number out of range, the genome ID
        # will be invalid, and our attempt to read from the database will return an
        # empty list.
        my $genomeList = $self->{genomes};
        if ($rowstr >= 0 && $rowstr < @{$genomeList}) {
            $genomeID = $genomeList->[$rowstr]->[0];
        }
    }
    # Get the spreadsheet.
    my $rowHash = $self->_get_spreadsheet();
    # Delcare the return variable.
    my @retVal;
    # Only proceed if this genome is in this subsystem.
    if (exists $rowHash->{$genomeID}) {
        # Push the cell's contents into the return list.
        push @retVal, @{$rowHash->{$genomeID}->[$colIdx]};
    }
    # Return the list. If the spreadsheet cell was empty or non-existent, we'll end
    # up returning an empty list.
    return @retVal;
}

=head3 get_diagrams

    my @list = $sub->get_diagrams();

Return a list of the diagrams associated with this subsystem. Each diagram
is represented in the return list as a 4-tuple C<[diagram_id, diagram_name,
page_link, img_link]> where

=over 4

=item diagram_id

ID code for this diagram.

=item diagram_name

Displayable name of the diagram.

=item page_link

URL of an HTML page containing information about the diagram.

=item img_link

URL of an HTML page containing an image for the diagram.

=back

Note that the URLs are in fact for CGI scripts with parameters that point them
to the correct place. Though Sprout has diagram information in it, it has
no relationship to the diagrams displayed in SEED, so the work is done entirely
on the SEED side.

=cut

sub get_diagrams {
    # Get the parameters.
    my ($self) = @_;
    # Get the diagram IDs.
    my @diagramIDs = Subsystem::GetDiagramIDs($self->{dir});
    Trace("Diagram IDs are " . join(", ", @diagramIDs)) if T(3);
    # Create the return variable.
    my @retVal = ();
    # Loop through the diagram IDs.
    for my $diagramID (@diagramIDs) {
        Trace("Processing diagram $diagramID.") if T(3);
        my ($name, $link, $imgLink) = $self->get_diagram($diagramID);
        Trace("Diagram $name URLs are \"$link\" and \"$imgLink\".") if T(3);
        push @retVal, [$diagramID, $name, $link, $imgLink];
    }
    # Return the result.
    return @retVal;
}

=head3 get_diagram

    my ($name, $pageURL, $imgURL) = $sub->get_diagram($id);

Get the information (if any) for the specified diagram. The diagram corresponds
to a subdirectory of the subsystem's C<diagrams> directory. For example, if the
diagram ID is C<d03>, the diagram's subdirectory would be C<$dir/diagrams/d03>,
where I<$dir> is the subsystem directory. The diagram's name is extracted from
a tiny file containing the name, and then the links are computed using the
subsystem name and the diagram ID. The parameters are as follows.

=over 4

=item id

ID code for the desired diagram.

=item RETURN

Returns a three-element list. The first element is the diagram name, the second
a URL for displaying information about the diagram, and the third a URL for
displaying the diagram image.

=back

=cut

sub get_diagram {
    my($self, $id) = @_;
    my $name = Subsystem::GetDiagramName($self->{dir}, $id);
    my ($link, $img_link) = Subsystem::ComputeDiagramURLs($self, $self->{name}, $id, 1);
    return($name, $link, $img_link);
}

=head3 get_diagram_html_file

    my $fileName = $sub->get_diagram_html_file($id);

Get the HTML file (if any) for the specified diagram. The diagram corresponds
to a subdirectory of the subsystem's C<diagrams> directory. For example, if the
diagram ID is C<d03>, the diagram's subdirectory would be C<$dir/diagrams/d03>,
where I<$dir> is the subsystem directory. If an HTML file exists, it will be
named C<diagram.html> in the diagram directory.  The parameters are as follows.

=over 4

=item id

ID code for the desired diagram.

=item RETURN

Returns the name of an HTML diagram file, or C<undef> if no such file exists.

=back

=cut

sub get_diagram_html_file {
    my ($self, $id) = @_;
    my $retVal;
    my $ddir = "$self->{dir}/diagrams/$id";
    Trace("Looking for diagram file at $ddir.") if T(3);
    if (-d $ddir) {
        my $html = "$ddir/diagram.html";
        if (-f $html) {
            $retVal = $html;
        }
    }
    return $retVal;
}

=head3 is_new_diagram

    my $flag = $sub->is_new_diagram($id);

Return TRUE if the specified diagram is in the new format, else FALSE.

=over 4

=item id

ID code (e.g. C<d03>) of the relevant diagram.

=item RETURN

Returns TRUE if the diagram is in the new format, else FALSE.

=back

=cut

sub is_new_diagram {
  my ($self, $id) = @_;

  my $image_map = $self->get_diagram_html_file($id);
  if ($image_map) {
    Trace("Image map found for diagram $id at $image_map.") if T(3);
    Open(\*IN, "<$image_map");
    my $header = <IN>;
    close(IN);

    if ($header =~ /\<map name=\"GraffleExport\"\>/) {
      return 1;
    }
  }

  return undef;
}

=head3 get_role_from_abbr

    my $roleName = $sub->get_role_from_abbr($abbr);

Return the role name corresponding to an abbreviation.

=over 4

=item abbr

Abbreviation name of the relevant role.

=item RETURN

Returns the full name of the specified role.

=back

=cut

sub get_role_from_abbr {
    # Get the parameters.
    my($self, $abbr) = @_;
    # Get the role name from the abbreviation hash.
    my $retVal = $self->{abbrHash}->{$abbr};
    # Check for a case incompatability.
    if (! defined $retVal) {
        $retVal = $self->{abbrHash}->{lcfirst $abbr};
    }
    # Return the result.
    return $retVal;
}

=head3 get_name

    my $name = $sub->get_name();

Return the name of this subsystem.

=cut

sub get_name {
    # Get the parameters.
    my ($self) = @_;
    # Return the result.
    return $self->{name};
}

=head3 open_diagram_image

    my ($type, $fh) = $sub->open_diagram_image($id);

Open a diagram's image file and return the type and file handle.

=over 4

=item id

ID of the desired diagram

=item RETURN

Returns a 2-tuple containing the diagram's MIME type and an open filehandle
for the diagram's data. If the diagram does not exist, the type will be
returned as <undef>.

=back

=cut

sub open_diagram_image {
    # Get the parameters.
    my ($self, $id) = @_;
    # Declare the return variables.
    my ($type, $fh);
    # Get the diagram directory.
    my $img_base = "$self->{dir}/diagrams/$id/diagram";
    # Get a list of file extensions and types.
    my %types = (png => "image/png",
                 gif => "image/gif",
                 jpg => "image/jpeg");
    # This is my new syntax for the for-each-while loop.
    # We loop until we run out of keys or come up with a type value.
    for my $ext (keys %types) { last if (defined $type);
        my $myType = $types{$ext};
        # Compute a file name for this diagram.
        my $file = "$img_base.$ext";
        # If it exists, try to open it.
        if (-f $file) {
            $fh = Open(undef, "<$file");
            $type = $myType;
        }
    }
    # Return the result.
    return ($type, $fh);
}

=head3 get_hope_scenario_names

    my @names = $sub->get_hope_scenario_names();

Return a list of the names for the scenarios associated with this
subsystem.

=cut

sub get_hope_scenario_names {
    # Get the parameters.
    my ($self) = @_;
    # Get the names from the database.
    my $sapling = $self->{sapling};

    my @retVal = $sapling->GetFlat("Scenario", 'ORDER BY Scenario(id)', [],
                                'Scenario(id)');

    #my @retVal = $sprout->GetFlat("HasScenario",
    #                              "HasScenario(from-link) = ? ORDER BY HasScenario(to-link)",
                                  #[$self->{name}], 'to-link');
    # Return the result.
    return @retVal;
}

=head3 get_hope_input_compounds

    my @compounds = $sub->get_hope_input_compounds($name);

Return a list of the input compounds for the named hope scenario.

=over 4

=item name

Name of a Hope scenario attached to this subsystem.

=item RETURN

Returns a list of compound IDs.

=back

=cut

sub get_hope_input_compounds {
    # Get the parameters.
    my ($self, $name) = @_;
    # Ask for the compounds.

    my @retVal = $self->{sapling}->GetFlat("Compound IsTerminusFor Scenario",
	    ' IsTerminusFor(group-number) = ? AND Scenario(id) = ?',
                               ['0', $name], 'Compound(id)');

    #my @retVal = $self->{sprout}->GetFlat("IsInputFor", "IsInputFor(to-link) = ?",
    #                                      [$name], "IsInputFor(from-link)");
    # Return the result.
    return @retVal;
}

=head3 get_hope_output_compounds

    my ($main, $aux) = $sub->get_hope_output_compounds($name);

Return a list of the output compounds for the named hope scenario.

=over 4

=item name

Name of the relevant scenario.

=item RETURN

Returns two lists of compound IDs: one for the main outputs and one for the
auxiliary outputs.

=back

=cut

sub get_hope_output_compounds {
    # Get the parameters.
    my ($self, $name) = @_;
    # Ask for the compounds.

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

    my @pairs = $sapling->GetAll("Compound IsTerminusFor Scenario",
                               'Scenario(id) = ?', [$name],
                               [qw(Compound(id) IsTerminusFor(group-number))]);

    #my @pairs = $sprout->GetAll("IsOutputOf", "IsOutputOf(to-link) = ?",
    #                            [$name], "from-link auxiliary");
    # We now have a list of pairs in the form [name, aux-flag]. We put each
    # name in the list indicated by its aux-flag.

    my @retVal = ([], []);
    for my $pair (@pairs) {
        if ($pair->[1] > 0) {
            push @{$retVal[$pair->[1]]}, $pair->[0];
        }
    }
    # Return the result.
    return @retVal;
}

=head3 get_hope_map_ids

    my @mapIDs = $sub->get_hope_map_ids($name);

Return a list of the ID numbers for the diagrams associated with the named
scenario.

=over 4

=item name

Name of the relevant scenario.

=item RETURN

Returns a list of the ID numbers for the KEGG diagrams associated with this
scenario. These are different from the diagram IDs, all of which begin with
the string "map". This recognizes a design incompatability between SEED and
Sprout.

=back

=cut

sub get_hope_map_ids {
    # Get the parameters.
    my ($self, $name) = @_;
    # Get the map IDs.

    my @diagrams = $self->{sapling}->GetFlat("Scenario Overlaps Diagram",
                                'Scenario(id) = ?', [$name],
                                'Diagram(id)');

    #my @diagrams = $self->{sprout}->GetFlat('IsOnDiagram', "IsOnDiagram(from-link) = ?",
                                            #[$name], 'to-link');
    # Modify and return the result.
    my @retVal = map { /(\d+)/ } @diagrams;
    return @retVal;
}

=head3 all_functions

    my $pegRoles = $sub->all_functions();

Return a hash of all the features in the subsystem. The hash maps each
feature ID to its functional assignment.

=cut

sub all_functions {
    # Get the parameters.
    my ($self) = @_;
    # Insure we have a spreadsheet.
    $self->_get_spreadsheet();
    # Return the feature hash.
    return $self->{featureData};
}

=head3 get_col

    my $cellArray = $sub->get_col($idx);

Return an array of the cells in the specified column of the subsystem
spreadsheet. Each cell is a reference to a list of the features for the
corresponding row in the specified column.

=over 4

=item idx

Index of the desired column.

=item RETURN

Returns a reference to a list containing the spreadsheet column's cells, in
row order.

=back

=cut

sub get_col {
    # Get the parameters.
    my ($self, $idx) = @_;
    # Declare the return variable.
    my @retVal;
    # Get the subsystem spreadsheet.
    my $sheet = $self->_get_spreadsheet();
    # Loop through the row list.
    for my $rowPair (@{$self->{genomes}}) {
        # Get the genome for this row. Each row pair is [genomeID, variantCode].
        my ($genomeID) = @$rowPair;
        # Get the genome's row in the spreadsheet.
        my $rowList = $sheet->{$genomeID};
        # Get the cell.
        my $cell = $rowList->[$idx];
        # If the cell exists, put it into the output list.
        if (defined $cell) {
            push @retVal, $rowList->[$idx];
        }
    }
    # Return the result.
    return \@retVal;
}

=head2 Internal Utility Methods

=head3 _get_spreadsheet

    my $hash = $sub->_get_spreadsheet();

Return a reference to a hash mapping each of the subsystem's genomes to
their spreadsheet rows. Each row is a list of cells, and each cell is a
list of feature IDs.

=cut

sub _get_spreadsheet {
    # Get the parameters.
    my ($self) = @_;
    # Do we already have a spreadsheet?
    my $retVal = $self->{rows};
    if (! defined $retVal) {
        # We don't, so we have to create one. Start with an empty hash.
        $retVal = {};
        # Get the sapling database.
        my $sapling = $self->{sapling};
        # Get the subsystem ID.
        my $subsysID = $self->{name};
        # Compute the pattern that matches all of this subsystem's machine roles.
        my $subsysCellPattern = ERDB::DigestKey($subsysID) . ':%';
        # Ask for all the subsystem's cells and their features.
        my @resultRows = $sapling->GetAll("Contains", 'Contains(from-link) LIKE ?',
                                          [$subsysCellPattern],
                                          [qw(Contains(to-link) Contains(from-link))]);
        # Loop through the features.
        for my $feature (@resultRows) {
            # Get the machine-role and feature IDs.
            my ($featureID, $machineRoleID) = @$feature;
            # We need the column number and the role ID. These can be computed
            # from the role abbreviation at the end of the machine role ID.
            my (undef, $genomeID, undef, $roleAbbr) = split /:/, $machineRoleID;
            my $column = $self->{roleHash}->{$roleAbbr};
            my $role = $self->{abbrHash}->{$roleAbbr};
            # If we don't have this genome in the hash, create it.
            if (! exists $retVal->{$genomeID}) {
                # The initial value is a list of empty lists. Features
                # are then pushed into each individual list.
                my @row = map { [] } @{$self->{roles}};
                # Put this list of null lists in the hash.
                $retVal->{$genomeID} = \@row;
            }
            # Get this row. We know now that it exists.
            my $row = $retVal->{$genomeID};
            # Add this feature to the appropriate cell in the row.
            push @{$row->[$column]}, $featureID;
            # Put it in the feature data hash.
            $self->{featureData}->{$featureID} = $role;
        }
        # Save the row hash.
        $self->{rows} = $retVal;
    }
    # Return the result.
    return $retVal;
}

1;


text:
require 'openssl'

module Trustev
  class Authenticate

    SERVICE_URL = 'AuthenticationService.svc/rest/Token'

    def self.retrieve_token

      raise Error.new('No Username provided.') unless Trustev.username
      raise Error.new('No Password provided.') unless Trustev.password
      raise Error.new('No Shared Secret provided.') unless Trustev.shared_secret

      time = Time.now.utc

      body = {
        UserName: Trustev.username,
        Password: password(time),
        Sha256Hash: sha256hash(time),
        Timestamp: "\/Date(#{time.to_i*1000})\/"
      }

      response = Trustev.send_request SERVICE_URL, body, 'POST', true, false
      Trustev.token = response[:Token][:APIToken]
      Trustev.token_expire = response[:Token][:ExpireAt][/\((.*)\)/m, 1].to_i/1000
    end

    private

    def self.password(time)
      generate_hash Trustev.password, time
    end

    def self.sha256hash(time)
      generate_hash Trustev.username, time
    end

    def self.generate_hash(modifier, time)
      sha256 = OpenSSL::Digest::SHA256.new
      sha256 << "#{time.strftime '%Y%m%d%H%M%S'}.#{modifier}"
      hash_part_1 = sha256.hexdigest
      sha256 = OpenSSL::Digest::SHA256.new
      sha256 << "#{hash_part_1}.#{Trustev.shared_secret}"
      sha256.hexdigest
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
//
// Pusher.cs
//
// Author:
//	Zachary Gramana  <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
using System.Threading.Tasks;
using System.Net.Http;
using System.Web;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.Linq;

namespace Couchbase.Lite.Replicator
{
    internal class Pusher : Replication
	{
        readonly string Tag = "Pusher";

		private bool observing;

		private FilterDelegate filter;

		/// Constructor
        public Pusher(Database db, Uri remote, bool continuous, TaskFactory workExecutor) : this(db, remote, continuous, null, workExecutor)
		{
		}

		/// Constructor
        public Pusher(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory
            , TaskFactory workExecutor) : base(db, remote, continuous, clientFactory
			, workExecutor)
		{
			CreateTarget = false;
			observing = false;
		}

        #region implemented abstract members of Replication

        public override IEnumerable<String> Channels { get; set; }

        public override IEnumerable<String> DocIds { get; set; }

        public override Dictionary<String, String> Headers { get; set; }

        public override Boolean CreateTarget { get; set; }

        public override bool IsPull { get { return false; } }

        #endregion

        protected internal override void MaybeCreateRemoteDB()
		{
            if (!CreateTarget)
            {
                return;
            }

            Log.V(Tag, this + ": Remote db might not exist; creating it...");
            Log.D(Tag, this + "|" + Thread.CurrentThread() + ": maybeCreateRemoteDB() calling asyncTaskStarted()");
            SendAsyncRequest(HttpMethod.Put, String.Empty, null, (result, e) =>
                {
                    try
                    {
                        if (e is HttpException && ((HttpException)e).ErrorCode != 412)
                        {
                            // this is fatal: no db to push to!
                            Log.E(Tag, this + ": Failed to create remote db", e);
                            LastError = e;
                            Stop();
                        }
                        else
                        {
                            Log.V (Tag, this + ": Created remote db");
                            CreateTarget = false;
                            BeginReplicating ();
                        }
                    }
                    finally
                    {
                        Log.D(Tag, this + "|" +  Thread.CurrentThread() + ": maybeCreateRemoteDB.onComplete() calling asyncTaskFinished()");
                        AsyncTaskFinished(1);
                    }
                });
		}

        internal override void BeginReplicating()
		{
            // If we're still waiting to create the remote db, do nothing now. (This method will be
            // re-invoked after that request finishes; see maybeCreateRemoteDB() above.)
            Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": beginReplicating() called");

            if (CreateTarget)
            {
                Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": creatingTarget == true, doing nothing");
                return;
            }
            else
            {
                Log.D(Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": creatingTarget != true, continuing");
            }

            if (Filter != null)
            {
                filter = LocalDatabase.GetFilter(Filter);
            }
            if (Filter != null && filter == null)
            {
                Log.W(Tag, string.Format("{0}: No ReplicationFilter registered for filter '{1}'; ignoring"
                    , this, Filter));
            }
            // Process existing changes since the last push:
            long lastSequenceLong = 0;
            if (LastSequence != null)
            {
                lastSequenceLong = long.Parse(LastSequence);
            }

            var options = new ChangesOptions();
            options.SetIncludeConflicts(true);
            var changes = LocalDatabase.ChangesSince(lastSequenceLong, options, filter);
            if (changes.Count > 0)
            {
                Batcher.QueueObjects(changes);
                Batcher.Flush();
            }
            // Now listen for future changes (in continuous mode):
            if (continuous)
            {
                observing = true;
                LocalDatabase.Changed += OnChanged;
                Log.D(Tag, this + "|" + Thread.CurrentThread() + ": pusher.beginReplicating() calling asyncTaskStarted()");
                AsyncTaskStarted();
            }
		}

		// prevents stopped() from being called when other tasks finish
		public override void Stop()
		{
			StopObserving();
			base.Stop();
		}

		private void StopObserving()
		{
			if (observing)
			{
                try
                {
                    observing = false;
                    LocalDatabase.Changed -= OnChanged;
                }
                finally
                {
                    AsyncTaskFinished(1);
                }
			}
		}

        internal void OnChanged(Object sender, Database.DatabaseChangeEventArgs args)
		{
            var changes = args.Changes;
            foreach (DocumentChange change in changes)
            {
                // Skip revisions that originally came from the database I'm syncing to:
                var source = change.SourceUrl;
                if (source != null && source.Equals(RemoteUrl))
                {
                    return;
                }

                var rev = change.AddedRevision;
                IDictionary<String, Object> paramsFixMe = null;

                // TODO: these should not be null
                if (LocalDatabase.RunFilter(filter, paramsFixMe, rev))
                {
                    AddToInbox(rev);
                }
            }
		}

        internal override void ProcessInbox(RevisionList inbox)
		{
            var lastInboxSequence = inbox[inbox.Count - 1].GetSequence();
            // Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
            // <http://wiki.apache.org/couchdb/HttpPostRevsDiff>
            var diffs = new Dictionary<String, IList<String>>();
            foreach (var rev in inbox)
            {
                var docID = rev.GetDocId();
                var revs = diffs.Get(docID);
                if (revs == null)
                {
                    revs = new AList<String>();
                    diffs[docID] = revs;
                }
                revs.AddItem(rev.GetRevId());
            }

            // Call _revs_diff on the target db:
            Log.D(Tag, this + "|" + Thread.CurrentThread() + ": processInbox() calling asyncTaskStarted()");
            Log.D(Tag, this + "|" + Thread.CurrentThread() + ": posting to /_revs_diff: " + diffs);

            AsyncTaskStarted();
            SendAsyncRequest(HttpMethod.Post, "/_revs_diff", diffs, (response, e) =>
            {
                try {
                    Log.D(Tag, this + "|" + Thread.CurrentThread() + ": /_revs_diff response: " + response);

                    var responseData = (JObject)response;
                    var results = responseData.ToObject<IDictionary<string, object>>();

                    if (e != null) {
                        LastError = e;
                        RevisionFailed();
                        //Stop ();
                    } else {
                        if (results.Count != 0) {
                            // Go through the list of local changes again, selecting the ones the destination server
                            // said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
                            var docsToSend = new AList<object> ();

                            foreach (var rev in inbox) {
                                IDictionary<string, object> properties = null;
                                var resultDocData = (JObject)results.Get (rev.GetDocId ());
                                var resultDoc = resultDocData.ToObject<IDictionary<String, Object>>();
                                if (resultDoc != null) {
                                    var revs = ((JArray)resultDoc.Get ("missing")).Values<String>().ToList();
                                    if (revs != null && revs.Contains (rev.GetRevId ())) {
                                        //remote server needs this revision
                                        // Get the revision's properties
                                        if (rev.IsDeleted ()) {
                                            properties = new Dictionary<string, object> ();
                                            properties.Put ("_id", rev.GetDocId ());
                                            properties.Put ("_rev", rev.GetRevId ());
                                            properties.Put ("_deleted", true);
                                        } else {
                                            // OPT: Shouldn't include all attachment bodies, just ones that have changed
                                            var contentOptions = EnumSet.Of (TDContentOptions.TDIncludeAttachments, TDContentOptions.TDBigAttachmentsFollow);
                                            try {
                                                LocalDatabase.LoadRevisionBody (rev, contentOptions);
                                            } catch (CouchbaseLiteException e1) {
                                                Log.W(Tag, string.Format("%s Couldn't get local contents of %s", rev, this));
                                                RevisionFailed();
                                                continue;
                                            }
                                            properties = new Dictionary<String, Object> (rev.GetProperties ());
                                        }
                                        if (properties.ContainsKey ("_attachments")) {
                                            if (UploadMultipartRevision (rev)) {
                                                continue;
                                            }
                                        }
                                        if (properties != null) {
                                            // Add the _revisions list:
                                            properties.Put ("_revisions", LocalDatabase.GetRevisionHistoryDict (rev));
                                            //now add it to the docs to send
                                            docsToSend.AddItem (properties);
                                        }
                                    }
                                }
                            }
                            // Post the revisions to the destination. "new_edits":false means that the server should
                            // use the given _rev IDs instead of making up new ones.
                            var numDocsToSend = docsToSend.Count;
                            if (numDocsToSend > 0)
                            {
                                var bulkDocsBody = new Dictionary<String, Object> ();
                                bulkDocsBody.Put ("docs", docsToSend);
                                bulkDocsBody.Put ("new_edits", false);

                                Log.V(Tag, string.Format("%s: POSTing " + numDocsToSend + " revisions to _bulk_docs: %s", this, docsToSend));

                                ChangesCount += numDocsToSend;

                                Log.D(Tag, this + "|" + Thread.CurrentThread() + ": processInbox-before_bulk_docs() calling asyncTaskStarted()");

                                AsyncTaskStarted ();
                                SendAsyncRequest (HttpMethod.Post, "/_bulk_docs", bulkDocsBody, (result, ex) => {
                                    try
                                    {
                                        if (ex != null) {
                                            LastError = ex;
                                            RevisionFailed();
                                        } else {
                                            Log.V(Tag, string.Format("%s: POSTed to _bulk_docs: %s", this, docsToSend));
                                            LastSequence = string.Format ("{0}", lastInboxSequence);
                                        }
                                        CompletedChangesCount  += numDocsToSend;
                                    }
                                    finally
                                    {
                                        AsyncTaskFinished (1);
                                    }
                                });
                            }
                        } else {
                            // If none of the revisions are new to the remote, just bump the lastSequence:
                            LastSequence = string.Format ("{0}", lastInboxSequence);
                        }
                    }
                }
                finally
                {
                    Log.D(Tag, this + "|" + Thread.CurrentThread() + ": processInbox() calling asyncTaskFinished()");
                    AsyncTaskFinished (1);
                }
            });
		}

		private bool UploadMultipartRevision(RevisionInternal revision)
		{
            MultipartFormDataContent multiPart = null;
            var revProps = revision.GetProperties();
            revProps.Put("_revisions", LocalDatabase.GetRevisionHistoryDict(revision));

            var attachments = (IDictionary<string, object>)revProps.Get("_attachments");

            foreach (var attachmentKey in attachments.Keys)
            {
                var attachment = (IDictionary<String, Object>)attachments.Get(attachmentKey);
                if (attachment.ContainsKey("follows"))
                {
                    if (multiPart == null)
                    {
                        multiPart = new MultipartFormDataContent();
                        try
                        {
                            var json = Manager.GetObjectMapper().WriteValueAsString(revProps);
                            var utf8charset = Encoding.UTF8;
                            multiPart.Add(new StringContent(json, utf8charset, "application/json"), "param1");
                        }
                        catch (IOException e)
                        {
                            throw new ArgumentException("Not able to serialize revision properties into a multipart request content.", e);
                        }
                    }

                    var blobStore = LocalDatabase.Attachments;
                    var base64Digest = (string)attachment.Get("digest");

                    var blobKey = new BlobKey(base64Digest);
                    var inputStream = blobStore.BlobStreamForKey(blobKey);

                    if (inputStream == null)
                    {
                        Log.W(Tag, "Unable to find blob file for blobKey: " + blobKey + " - Skipping upload of multipart revision.");
                        multiPart = null;
                    }
                    else
                    {
                        string contentType = null;
                        if (attachment.ContainsKey("content_type"))
                        {
                            contentType = (string)attachment.Get("content_type");
                        }
                        else
                        {
                            if (attachment.ContainsKey("content-type"))
                            {
                                var message = string.Format("Found attachment that uses content-type"
                                    + " field name instead of content_type (see couchbase-lite-android"
                                    + " issue #80): " + attachment);
                                Log.W(Tag, message);
                            }
                        }

                        var content = new StreamContent(inputStream);
                        content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                        multiPart.Add(content, attachmentKey);
                    }
                }
            }

            if (multiPart == null)
            {
                return false;
            }

            var path = string.Format("/{0}?new_edits=false", revision.GetDocId());

            // TODO: need to throttle these requests
            Log.D(Tag, "Uploadeding multipart request.  Revision: " + revision);
            Log.D(Tag, this + "|" + Thread.CurrentThread() + ": uploadMultipartRevision() calling asyncTaskStarted()");

            AsyncTaskStarted();

            SendAsyncMultipartRequest(HttpMethod.Put, path, multiPart, (result, e) => {
                try
                {
                    if (e != null)
                    {
                        Log.E (Tag, "Exception uploading multipart request", e);
                        LastError = e;
                        RevisionFailed();
                    }
                    else
                    {
                        Log.D (Tag, "Uploaded multipart request.  Result: " + result);
                    }
                }
                finally
                {
                    AsyncTaskFinished (1);
                }
            });
            return true;
		}
	}
}


text: Added **Microsoft Defender For Endpoint - Collect Investigation Package** to the playbook flow.


text:
package org.springframework.jdbc.datasource;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.transaction.support.ResourceTransactionManager;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionSynchronizationUtils;
import org.springframework.util.Assert;

/**
 * {@link org.springframework.transaction.PlatformTransactionManager}
 * implementation for a single JDBC {@link javax.sql.DataSource}. This class is
 * capable of working in any environment with any JDBC driver, as long as the setup
 * uses a {@code javax.sql.DataSource} as its {@code Connection} factory mechanism.
 * Binds a JDBC Connection from the specified DataSource to the current thread,
 * potentially allowing for one thread-bound Connection per DataSource.
 *
 *
Note: The DataSource that this transaction manager operates on needs
 * to return independent Connections. The Connections may come from a pool
 * (the typical case), but the DataSource must not return thread-scoped /
 * request-scoped Connections or the like. This transaction manager will
 * associate Connections with thread-bound transactions itself, according
 * to the specified propagation behavior. It assumes that a separate,
 * independent Connection can be obtained even during an ongoing transaction.
 *
 *
Application code is required to retrieve the JDBC Connection via
 * {@link DataSourceUtils#getConnection(DataSource)} instead of a standard
 * Jakarta EE-style {@link DataSource#getConnection()} call. Spring classes such as
 * {@link org.springframework.jdbc.core.JdbcTemplate} use this strategy implicitly.
 * If not used in combination with this transaction manager, the
 * {@link DataSourceUtils} lookup strategy behaves exactly like the native
 * DataSource lookup; it can thus be used in a portable fashion.
 *
 *
Alternatively, you can allow application code to work with the standard
 * Jakarta EE-style lookup pattern {@link DataSource#getConnection()}, for example for
 * legacy code that is not aware of Spring at all. In that case, define a
 * {@link TransactionAwareDataSourceProxy} for your target DataSource, and pass
 * that proxy DataSource to your DAOs, which will automatically participate in
 * Spring-managed transactions when accessing it.
 *
 *
Supports custom isolation levels, and timeouts which get applied as
 * appropriate JDBC statement timeouts. To support the latter, application code
 * must either use {@link org.springframework.jdbc.core.JdbcTemplate}, call
 * {@link DataSourceUtils#applyTransactionTimeout} for each created JDBC Statement,
 * or go through a {@link TransactionAwareDataSourceProxy} which will create
 * timeout-aware JDBC Connections and Statements automatically.
 *
 *
Consider defining a {@link LazyConnectionDataSourceProxy} for your target
 * DataSource, pointing both this transaction manager and your DAOs to it.
 * This will lead to optimized handling of "empty" transactions, i.e. of transactions
 * without any JDBC statements executed. A LazyConnectionDataSourceProxy will not fetch
 * an actual JDBC Connection from the target DataSource until a Statement gets executed,
 * lazily applying the specified transaction settings to the target Connection.
 *
 *
This transaction manager supports nested transactions via the JDBC 3.0
 * {@link java.sql.Savepoint} mechanism. The
 * {@link #setNestedTransactionAllowed "nestedTransactionAllowed"} flag defaults
 * to "true", since nested transactions will work without restrictions on JDBC
 * drivers that support savepoints (such as the Oracle JDBC driver).
 *
 *
This transaction manager can be used as a replacement for the
 * {@link org.springframework.transaction.jta.JtaTransactionManager} in the single
 * resource case, as it does not require a container that supports JTA, typically
 * in combination with a locally defined JDBC DataSource (e.g. an Apache Commons
 * DBCP connection pool). Switching between this local strategy and a JTA
 * environment is just a matter of configuration!
 *
 *
As of 4.3.4, this transaction manager triggers flush callbacks on registered
 * transaction synchronizations (if synchronization is generally active), assuming
 * resources operating on the underlying JDBC {@code Connection}. This allows for
 * setup analogous to {@code JtaTransactionManager}, in particular with respect to
 * lazily registered ORM resources (e.g. a Hibernate {@code Session}).
 *
 *
NOTE: As of 5.3, {@link org.springframework.jdbc.support.JdbcTransactionManager}
 * is available as an extended subclass which includes commit/rollback exception
 * translation, aligned with {@link org.springframework.jdbc.core.JdbcTemplate}.
 *
 * @author Juergen Hoeller
 * @since 02.05.2003
 * @see #setNestedTransactionAllowed
 * @see java.sql.Savepoint
 * @see DataSourceUtils#getConnection(javax.sql.DataSource)
 * @see DataSourceUtils#applyTransactionTimeout
 * @see DataSourceUtils#releaseConnection
 * @see TransactionAwareDataSourceProxy
 * @see LazyConnectionDataSourceProxy
 * @see org.springframework.jdbc.core.JdbcTemplate
 */
@SuppressWarnings("serial")
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager
		implements ResourceTransactionManager, InitializingBean {

	@Nullable
	private DataSource dataSource;

	private boolean enforceReadOnly = false;

	/**
	 * Create a new DataSourceTransactionManager instance.
	 * A DataSource has to be set to be able to use it.
	 * @see #setDataSource
	 */
	public DataSourceTransactionManager() {
		setNestedTransactionAllowed(true);
	}

	/**
	 * Create a new DataSourceTransactionManager instance.
	 * @param dataSource the JDBC DataSource to manage transactions for
	 */
	public DataSourceTransactionManager(DataSource dataSource) {
		this();
		setDataSource(dataSource);
		afterPropertiesSet();
	}

	/**
	 * Set the JDBC DataSource that this instance should manage transactions for.
	 *
This will typically be a locally defined DataSource, for example an
	 * Apache Commons DBCP connection pool. Alternatively, you can also drive
	 * transactions for a non-XA J2EE DataSource fetched from JNDI. For an XA
	 * DataSource, use JtaTransactionManager.
	 *
The DataSource specified here should be the target DataSource to manage
	 * transactions for, not a TransactionAwareDataSourceProxy. Only data access
	 * code may work with TransactionAwareDataSourceProxy, while the transaction
	 * manager needs to work on the underlying target DataSource. If there's
	 * nevertheless a TransactionAwareDataSourceProxy passed in, it will be
	 * unwrapped to extract its target DataSource.
	 *
The DataSource passed in here needs to return independent Connections.
	 * The Connections may come from a pool (the typical case), but the DataSource
	 * must not return thread-scoped / request-scoped Connections or the like.
	 * @see TransactionAwareDataSourceProxy
	 * @see org.springframework.transaction.jta.JtaTransactionManager
	 */
	public void setDataSource(@Nullable DataSource dataSource) {
		if (dataSource instanceof TransactionAwareDataSourceProxy) {
			// If we got a TransactionAwareDataSourceProxy, we need to perform transactions
			// for its underlying target DataSource, else data access code won't see
			// properly exposed transactions (i.e. transactions for the target DataSource).
			this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
		}
		else {
			this.dataSource = dataSource;
		}
	}

	/**
	 * Return the JDBC DataSource that this instance manages transactions for.
	 */
	@Nullable
	public DataSource getDataSource() {
		return this.dataSource;
	}

	/**
	 * Obtain the DataSource for actual use.
	 * @return the DataSource (never {@code null})
	 * @throws IllegalStateException in case of no DataSource set
	 * @since 5.0
	 */
	protected DataSource obtainDataSource() {
		DataSource dataSource = getDataSource();
		Assert.state(dataSource != null, "No DataSource set");
		return dataSource;
	}

	/**
	 * Specify whether to enforce the read-only nature of a transaction
	 * (as indicated by {@link TransactionDefinition#isReadOnly()})
	 * through an explicit statement on the transactional connection:
	 * "SET TRANSACTION READ ONLY" as understood by Oracle, MySQL and Postgres.
	 *
The exact treatment, including any SQL statement executed on the connection,
	 * can be customized through {@link #prepareTransactionalConnection}.
	 *
This mode of read-only handling goes beyond the {@link Connection#setReadOnly}
	 * hint that Spring applies by default. In contrast to that standard JDBC hint,
	 * "SET TRANSACTION READ ONLY" enforces an isolation-level-like connection mode
	 * where data manipulation statements are strictly disallowed. Also, on Oracle,
	 * this read-only mode provides read consistency for the entire transaction.
	 *
Note that older Oracle JDBC drivers (9i, 10g) used to enforce this read-only
	 * mode even for {@code Connection.setReadOnly(true}. However, with recent drivers,
	 * this strong enforcement needs to be applied explicitly, e.g. through this flag.
	 * @since 4.3.7
	 * @see #prepareTransactionalConnection
	 */
	public void setEnforceReadOnly(boolean enforceReadOnly) {
		this.enforceReadOnly = enforceReadOnly;
	}

	/**
	 * Return whether to enforce the read-only nature of a transaction
	 * through an explicit statement on the transactional connection.
	 * @since 4.3.7
	 * @see #setEnforceReadOnly
	 */
	public boolean isEnforceReadOnly() {
		return this.enforceReadOnly;
	}

	@Override
	public void afterPropertiesSet() {
		if (getDataSource() == null) {
			throw new IllegalArgumentException("Property 'dataSource' is required");
		}
	}

	@Override
	public Object getResourceFactory() {
		return obtainDataSource();
	}

	@Override
	protected Object doGetTransaction() {
		DataSourceTransactionObject txObject = new DataSourceTransactionObject();
		txObject.setSavepointAllowed(isNestedTransactionAllowed());
		ConnectionHolder conHolder =
				(ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
		txObject.setConnectionHolder(conHolder, false);
		return txObject;
	}

	@Override
	protected boolean isExistingTransaction(Object transaction) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
		return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
	}

	@Override
	protected void doBegin(Object transaction, TransactionDefinition definition) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
		Connection con = null;

		try {
			if (!txObject.hasConnectionHolder() ||
					txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
				Connection newCon = obtainDataSource().getConnection();
				if (logger.isDebugEnabled()) {
					logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
				}
				txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
			}

			txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
			con = txObject.getConnectionHolder().getConnection();

			Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
			txObject.setPreviousIsolationLevel(previousIsolationLevel);
			txObject.setReadOnly(definition.isReadOnly());

			// Switch to manual commit if necessary. This is very expensive in some JDBC drivers,
			// so we don't want to do it unnecessarily (for example if we've explicitly
			// configured the connection pool to set it already).
			if (con.getAutoCommit()) {
				txObject.setMustRestoreAutoCommit(true);
				if (logger.isDebugEnabled()) {
					logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
				}
				con.setAutoCommit(false);
			}

			prepareTransactionalConnection(con, definition);
			txObject.getConnectionHolder().setTransactionActive(true);

			int timeout = determineTimeout(definition);
			if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
				txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
			}

			// Bind the connection holder to the thread.
			if (txObject.isNewConnectionHolder()) {
				TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
			}
		}

		catch (Throwable ex) {
			if (txObject.isNewConnectionHolder()) {
				DataSourceUtils.releaseConnection(con, obtainDataSource());
				txObject.setConnectionHolder(null, false);
			}
			throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
		}
	}

	@Override
	protected Object doSuspend(Object transaction) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
		txObject.setConnectionHolder(null);
		return TransactionSynchronizationManager.unbindResource(obtainDataSource());
	}

	@Override
	protected void doResume(@Nullable Object transaction, Object suspendedResources) {
		TransactionSynchronizationManager.bindResource(obtainDataSource(), suspendedResources);
	}

	@Override
	protected void doCommit(DefaultTransactionStatus status) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
		Connection con = txObject.getConnectionHolder().getConnection();
		if (status.isDebug()) {
			logger.debug("Committing JDBC transaction on Connection [" + con + "]");
		}
		try {
			con.commit();
		}
		catch (SQLException ex) {
			throw translateException("JDBC commit", ex);
		}
	}

	@Override
	protected void doRollback(DefaultTransactionStatus status) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
		Connection con = txObject.getConnectionHolder().getConnection();
		if (status.isDebug()) {
			logger.debug("Rolling back JDBC transaction on Connection [" + con + "]");
		}
		try {
			con.rollback();
		}
		catch (SQLException ex) {
			throw translateException("JDBC rollback", ex);
		}
	}

	@Override
	protected void doSetRollbackOnly(DefaultTransactionStatus status) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();
		if (status.isDebug()) {
			logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() +
					"] rollback-only");
		}
		txObject.setRollbackOnly();
	}

	@Override
	protected void doCleanupAfterCompletion(Object transaction) {
		DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;

		// Remove the connection holder from the thread, if exposed.
		if (txObject.isNewConnectionHolder()) {
			TransactionSynchronizationManager.unbindResource(obtainDataSource());
		}

		// Reset connection.
		Connection con = txObject.getConnectionHolder().getConnection();
		try {
			if (txObject.isMustRestoreAutoCommit()) {
				con.setAutoCommit(true);
			}
			DataSourceUtils.resetConnectionAfterTransaction(
					con, txObject.getPreviousIsolationLevel(), txObject.isReadOnly());
		}
		catch (Throwable ex) {
			logger.debug("Could not reset JDBC Connection after transaction", ex);
		}

		if (txObject.isNewConnectionHolder()) {
			if (logger.isDebugEnabled()) {
				logger.debug("Releasing JDBC Connection [" + con + "] after transaction");
			}
			DataSourceUtils.releaseConnection(con, this.dataSource);
		}

		txObject.getConnectionHolder().clear();
	}

	/**
	 * Prepare the transactional {@code Connection} right after transaction begin.
	 *
The default implementation executes a "SET TRANSACTION READ ONLY" statement
	 * if the {@link #setEnforceReadOnly "enforceReadOnly"} flag is set to {@code true}
	 * and the transaction definition indicates a read-only transaction.
	 *
The "SET TRANSACTION READ ONLY" is understood by Oracle, MySQL and Postgres
	 * and may work with other databases as well. If you'd like to adapt this treatment,
	 * override this method accordingly.
	 * @param con the transactional JDBC Connection
	 * @param definition the current transaction definition
	 * @throws SQLException if thrown by JDBC API
	 * @since 4.3.7
	 * @see #setEnforceReadOnly
	 */
	protected void prepareTransactionalConnection(Connection con, TransactionDefinition definition)
			throws SQLException {

		if (isEnforceReadOnly() && definition.isReadOnly()) {
			try (Statement stmt = con.createStatement()) {
				stmt.executeUpdate("SET TRANSACTION READ ONLY");
			}
		}
	}

	/**
	 * Translate the given JDBC commit/rollback exception to a common Spring
	 * exception to propagate from the {@link #commit}/{@link #rollback} call.
	 *
The default implementation throws a {@link TransactionSystemException}.
	 * Subclasses may specifically identify concurrency failures etc.
	 * @param task the task description (commit or rollback)
	 * @param ex the SQLException thrown from commit/rollback
	 * @return the translated exception to throw, either a
	 * {@link org.springframework.dao.DataAccessException} or a
	 * {@link org.springframework.transaction.TransactionException}
	 * @since 5.3
	 */
	protected RuntimeException translateException(String task, SQLException ex) {
		return new TransactionSystemException(task + " failed", ex);
	}

	/**
	 * DataSource transaction object, representing a ConnectionHolder.
	 * Used as transaction object by DataSourceTransactionManager.
	 */
	private static class DataSourceTransactionObject extends JdbcTransactionObjectSupport {

		private boolean newConnectionHolder;

		private boolean mustRestoreAutoCommit;

		public void setConnectionHolder(@Nullable ConnectionHolder connectionHolder, boolean newConnectionHolder) {
			super.setConnectionHolder(connectionHolder);
			this.newConnectionHolder = newConnectionHolder;
		}

		public boolean isNewConnectionHolder() {
			return this.newConnectionHolder;
		}

		public void setMustRestoreAutoCommit(boolean mustRestoreAutoCommit) {
			this.mustRestoreAutoCommit = mustRestoreAutoCommit;
		}

		public boolean isMustRestoreAutoCommit() {
			return this.mustRestoreAutoCommit;
		}

		public void setRollbackOnly() {
			getConnectionHolder().setRollbackOnly();
		}

		@Override
		public boolean isRollbackOnly() {
			return getConnectionHolder().isRollbackOnly();
		}

		@Override
		public void flush() {
			if (TransactionSynchronizationManager.isSynchronizationActive()) {
				TransactionSynchronizationUtils.triggerFlush();
			}
		}
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>se.redmind</groupId>
    <artifactId>rmgrid-queryservlet</artifactId>
    <version>1.0.0</version>
    <name>rmgrid -> queryservlet</name>
    <dependencies>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
</dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.3.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.yaml</groupId>
                    <artifactId>snakeyaml</artifactId>
                </exclusion>
            </exclusions>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
{% extends "contacts/company/base.html" %}
{% load i18n %}

{% block title %}{{ block.super }}: {% trans "Delete" %} {{ object.name }}{% endblock %}

{% block content_title %}

{% trans "Delete" %} {{ object.name }}

{% endblock %}

{% block content %}
	<form action="." method="post" accept-charset="utf-8">
        {% csrf_token %}

			<select name="delete_company" id="delete_company" size="1">
				<option value="No">{% trans "No" %}</option>
				<option value="Yes">{% trans "Yes" %}</option>
			</select>
			<input type="submit" value="{% trans "Submit" %}">

	</form>
{% endblock %}


text:
namespace net {

namespace {

bool AppendArgumentFromJSONValue(const std::string& key,
                                 const base::Value& value_node,
                                 CommandLine* command_line) {
  std::string argument_name = "--" + key;
  switch (value_node.GetType()) {
    case base::Value::TYPE_NULL:
      command_line->AppendArg(argument_name);
      break;
    case base::Value::TYPE_INTEGER: {
      int value;
      bool result = value_node.GetAsInteger(&value);
      DCHECK(result);
      command_line->AppendArg(argument_name + "=" + base::IntToString(value));
      break;
    }
    case Value::TYPE_STRING: {
      std::string value;
      bool result = value_node.GetAsString(&value);
      if (!result || value.empty())
        return false;
      command_line->AppendArg(argument_name + "=" + value);
      break;
    }
    case base::Value::TYPE_BOOLEAN:
    case base::Value::TYPE_DOUBLE:
    case base::Value::TYPE_LIST:
    case base::Value::TYPE_DICTIONARY:
    case base::Value::TYPE_BINARY:
    default:
      NOTREACHED() << "improper json type";
      return false;
  }
  return true;
}

}  // namespace

LocalTestServer::LocalTestServer(Type type,
                                 const std::string& host,
                                 const FilePath& document_root)
    : BaseTestServer(type, host) {
  if (!Init(document_root))
    NOTREACHED();
}

LocalTestServer::LocalTestServer(const HTTPSOptions& https_options,
                                 const FilePath& document_root)
    : BaseTestServer(https_options) {
  if (!Init(document_root))
    NOTREACHED();
}

LocalTestServer::~LocalTestServer() {
  Stop();
}

// static
bool LocalTestServer::GetTestServerDirectory(FilePath* directory) {
  // Get path to python server script.
  FilePath testserver_dir;
  if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_dir)) {
    LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
    return false;
  }

  testserver_dir = testserver_dir
      .Append(FILE_PATH_LITERAL("net"))
      .Append(FILE_PATH_LITERAL("tools"))
      .Append(FILE_PATH_LITERAL("testserver"));
  *directory = testserver_dir;
  return true;
}

bool LocalTestServer::Start() {
  // Get path to Python server script.
  FilePath testserver_path;
  if (!GetTestServerDirectory(&testserver_path))
    return false;
  testserver_path =
      testserver_path.Append(FILE_PATH_LITERAL("testserver.py"));

  if (!SetPythonPath())
    return false;

  if (!LaunchPython(testserver_path))
    return false;

  if (!WaitToStart()) {
    Stop();
    return false;
  }

  return SetupWhenServerStarted();
}

bool LocalTestServer::Stop() {
  CleanUpWhenStoppingServer();

  if (!process_handle_)
    return true;

  // First check if the process has already terminated.
  bool ret = base::WaitForSingleProcess(process_handle_, base::TimeDelta());
  if (!ret)
    ret = base::KillProcess(process_handle_, 1, true);

  if (ret) {
    base::CloseProcessHandle(process_handle_);
    process_handle_ = base::kNullProcessHandle;
  } else {
    VLOG(1) << "Kill failed?";
  }

  return ret;
}

bool LocalTestServer::Init(const FilePath& document_root) {
  if (document_root.IsAbsolute())
    return false;

  // At this point, the port that the test server will listen on is unknown.
  // The test server will listen on an ephemeral port, and write the port
  // number out over a pipe that this TestServer object will read from. Once
  // that is complete, the host port pair will contain the actual port.
  DCHECK(!GetPort());
  process_handle_ = base::kNullProcessHandle;

  FilePath src_dir;
  if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir))
    return false;
  SetResourcePath(src_dir.Append(document_root),
                  src_dir.AppendASCII("net")
                          .AppendASCII("data")
                          .AppendASCII("ssl")
                          .AppendASCII("certificates"));
  return true;
}

// static
bool LocalTestServer::SetPythonPath() {
  FilePath third_party_dir;
  if (!PathService::Get(base::DIR_SOURCE_ROOT, &third_party_dir)) {
    LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
    return false;
  }
  third_party_dir = third_party_dir.AppendASCII("third_party");

  // For simplejson. (simplejson, unlike all the other Python modules
  // we include, doesn't have an extra 'simplejson' directory, so we
  // need to include its parent directory, i.e. third_party_dir).
  AppendToPythonPath(third_party_dir);

  AppendToPythonPath(third_party_dir.AppendASCII("tlslite"));
  AppendToPythonPath(
      third_party_dir.AppendASCII("pyftpdlib").AppendASCII("src"));

  // Locate the Python code generated by the protocol buffers compiler.
  FilePath pyproto_dir;
  if (!GetPyProtoPath(&pyproto_dir)) {
    LOG(WARNING) << "Cannot find pyproto dir for generated code. "
                 << "Testserver features that rely on it will not work";
    return true;
  }

  AppendToPythonPath(pyproto_dir);
  AppendToPythonPath(pyproto_dir.AppendASCII("sync").AppendASCII("protocol"));
  AppendToPythonPath(pyproto_dir.AppendASCII("chrome")
                                .AppendASCII("browser")
                                .AppendASCII("policy")
                                .AppendASCII("proto"));

  return true;
}

bool LocalTestServer::AddCommandLineArguments(CommandLine* command_line) const {
  base::DictionaryValue arguments_dict;
  if (!GenerateArguments(&arguments_dict))
    return false;

  // Serialize the argument dictionary into CommandLine.
  for (DictionaryValue::Iterator it(arguments_dict); it.HasNext();
       it.Advance()) {
    const base::Value& value = it.value();
    const std::string& key = it.key();

    // Add arguments from a list.
    if (value.IsType(Value::TYPE_LIST)) {
      const base::ListValue* list = NULL;
      if (!value.GetAsList(&list) || !list || list->empty())
        return false;
      for (base::ListValue::const_iterator list_it = list->begin();
           list_it != list->end(); ++list_it) {
        if (!AppendArgumentFromJSONValue(key, *(*list_it), command_line))
          return false;
      }
    } else if (!AppendArgumentFromJSONValue(key, value, command_line)) {
        return false;
    }
  }

  // Append the appropriate server type argument.
  switch (type()) {
    case TYPE_HTTP:
    case TYPE_HTTPS:
      // The default type is HTTP, no argument required.
      break;
    case TYPE_FTP:
      command_line->AppendArg("-f");
      break;
    case TYPE_SYNC:
      command_line->AppendArg("--sync");
      break;
    case TYPE_TCP_ECHO:
      command_line->AppendArg("--tcp-echo");
      break;
    case TYPE_UDP_ECHO:
      command_line->AppendArg("--udp-echo");
      break;
    case TYPE_GDATA:
      command_line->AppendArg(
          std::string("--auth-token") + "=" + BaseTestServer::kGDataAuthToken);
      break;
    default:
      NOTREACHED();
      return false;
  }

  return true;
}

}  // namespace net


text:
package proguard.classfile.editor;

import proguard.classfile.attribute.annotation.*;

/**
 * This class can add annotations to a given parameter annotations attribute.
 * Annotations to be added must have been filled out beforehand.
 *
 * @author Eric Lafortune
 */
public class ParameterAnnotationsAttributeEditor
{
    private ParameterAnnotationsAttribute targetParameterAnnotationsAttribute;

    /**
     * Creates a new ParameterAnnotationsAttributeEditor that will edit
     * annotations in the given parameter annotations attribute.
     */
    public ParameterAnnotationsAttributeEditor(ParameterAnnotationsAttribute targetParameterAnnotationsAttribute)
    {
        this.targetParameterAnnotationsAttribute = targetParameterAnnotationsAttribute;
    }

    /**
     * Adds a given annotation to the annotations attribute.
     */
    public void addAnnotation(int parameterIndex, Annotation annotation)
    {
        int          annotationsCount = targetParameterAnnotationsAttribute.u2parameterAnnotationsCount[parameterIndex];
        Annotation[] annotations      = targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex];

        // Make sure there is enough space for the new annotation.
        if (annotations == null ||
            annotations.length <= annotationsCount)
        {
            targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex] = new Annotation[annotationsCount+1];
            if (annotations != null)
            {
                System.arraycopy(annotations, 0,
                                 targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex], 0,
                                 annotationsCount);
            }
            annotations = targetParameterAnnotationsAttribute.parameterAnnotations[parameterIndex];
        }

        // Add the annotation.
        annotations[targetParameterAnnotationsAttribute.u2parameterAnnotationsCount[parameterIndex]++] = annotation;
    }
}


text:
package io.jooby.i2408;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

import io.jooby.annotations.GET;
import io.jooby.annotations.QueryParam;

public class C2408 {
  @GET("/2408/nonnull")
  public String nonnull(@NonNull @QueryParam String name) {
    return name;
  }

  @GET("/2408/nullable")
  public String nullable(@Nullable @QueryParam String name, @QueryParam String blah) {
    if (name == null) {
      return "nothing";
    }
    return name;
  }
}


text:
#ifndef __ZUISTRING_H__
#define __ZUISTRING_H__

#include <assert.h>
namespace ZuiLib
{
	typedef char ZChar;

	class ZString
	{
	public:
		enum { MAX_LOCAL_STRING_LEN = 63 };

		ZString();
		ZString(const ZChar ch);
		ZString(const ZString& src);
		ZString(const ZChar* str, int nLen = -1);
		~ZString();

		void Empty();
		int GetLength() const;
		bool IsEmpty() const;
		ZChar GetAt(int nIndex) const;
		void Append(const ZChar* pstr);
		void Assign(const ZChar* pstr, int nLength = -1);
		const ZChar* GetString() const;

		void SetAt(int nIndex, ZChar ch);
		operator const ZChar*() const;

		ZChar operator[] (int nIndex) const;
		const ZString& operator=(const ZString& src);
		const ZString& operator=(const ZChar ch);
		const ZString& operator=(const ZChar* pstr);

		ZString operator+(const ZString& src) const;
		ZString operator+(const ZChar* pstr) const;
		const ZString& operator+=(const ZString& src);
		const ZString& operator+=(const ZChar* pstr);
		const ZString& operator+=(const ZChar ch);

		bool operator == (const ZChar* str) const;
		bool operator != (const ZChar* str) const;
		bool operator <= (const ZChar* str) const;
		bool operator <  (const ZChar* str) const;
		bool operator >= (const ZChar* str) const;
		bool operator >  (const ZChar* str) const;

		int Compare(const ZChar* pstr) const;
		int CompareNoCase(const ZChar* pstr) const;

		void MakeUpper();
		void MakeLower();

		ZString Left(int nLength) const;
		ZString Mid(int iPos, int nLength = -1) const;
		ZString Right(int nLength) const;

		int Find(ZChar ch, int iPos = 0) const;
		int Find(const ZChar* pstr, int iPos = 0) const;
		int ReverseFind(ZChar ch) const;
		int Replace(const ZChar* pstrFrom, const ZChar* pstrTo);

		int __cdecl Format(const ZChar* pstrFormat, ...);
        int __cdecl Format(const ZChar* pstrFormat, va_list Args);
		int __cdecl SmallFormat(const ZChar* pstrFormat, ...);

	protected:
		ZChar* m_pstr;
		ZChar m_szBuffer[MAX_LOCAL_STRING_LEN + 1];
	};

}//namespace

#endif //__ZUISTRING_H__


text:
from django.test import SimpleTestCase
from corehq.apps.userreports.exceptions import BadSpecError
from corehq.apps.userreports.transforms.factory import TransformFactory
from corehq.apps.userreports.transforms.specs import CustomTransform

class TransformFactoryTest(SimpleTestCase):

    def testMissingType(self):
        with self.assertRaises(BadSpecError):
            TransformFactory.get_transform({
                "custom_type": "user_display"
            })

    def testInvalidType(self):
        with self.assertRaises(BadSpecError):
            TransformFactory.get_transform({
                "type": "not_a_transform_type",
                "custom_type": "user_display"
            })

class CustomTransformTest(SimpleTestCase):

    def testInvalidCustomType(self):
        with self.assertRaises(BadSpecError):
            TransformFactory.get_transform({
                "type": "custom",
                "custom_type": "not_valid"
            })

    def testValidCustom(self):
        transform = TransformFactory.get_transform({
            "type": "custom",
            "custom_type": "user_display"
        })
        self.assertTrue(isinstance(transform, CustomTransform))


text:
package se.jiderhamn.tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import se.jiderhamn.JUnitClassloaderRunner;
import se.jiderhamn.LeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;

/**
 * @author Mattias Jiderhamn
 */
@RunWith(JUnitClassloaderRunner.class)
@LeakPreventor(BeanValidatorTest.Preventor.class)
public class BeanValidatorTest {

  @Test
  public void  validatorCacheLeaks() {
    javax.validation.Validation.buildDefaultValidatorFactory();
  }

  public static class Preventor implements Runnable {
    public void run() {
      new ClassLoaderLeakPreventor().fixBeanValidationApiLeak();
    }
  }
}


text:
package com.telerik.academy.voiceshoppinglist;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class HelpActivity extends AppCompatActivity {

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;

        Button voiceCommandsBtn = (Button) findViewById(R.id.btn_voice_commands);
        voiceCommandsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, HelpVoiceCommandsActivity.class);
                context.startActivity(intent);
            }
        });

        Button addProductBtn = (Button) findViewById(R.id.btn_add_product);
        addProductBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, HelpAddProductActivity.class);
                context.startActivity(intent);
            }
        });

        Button manipulateProductBtn = (Button) findViewById(R.id.btn_manipulate_product);
        manipulateProductBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, HelpManipulateProductActivity.class);
                context.startActivity(intent);
            }
        });
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>javax.xml.transform.dom</title>

  <meta name="CVS"
        content="$Id: package.html,v 1.3 2005-11-03 19:34:23 jeffsuttor Exp $" />
  <meta name="AUTHOR"
        content="Jeff.Suttor@Sun.com" />

This package implements DOM-specific transformation APIs.

The {@link javax.xml.transform.dom.DOMSource} class allows the
client of the implementation of this API to specify a DOM
{@link org.w3c.dom.Node} as the source of the input tree. The model of
how the Transformer deals with the DOM tree in terms of mismatches with the
XSLT data model or
other data models is beyond the scope of this document. Any of the nodes
derived from {@link org.w3c.dom.Node} are legal input.

The {@link javax.xml.transform.dom.DOMResult} class allows
a {@link org.w3c.dom.Node} to be specified to which result DOM nodes will
be appended. If an output node is not specified, the transformer will use
{@link javax.xml.parsers.DocumentBuilder#newDocument} to create an
output {@link org.w3c.dom.Document} node. If a node is specified, it
should be one of the following: {@link org.w3c.dom.Document},
{@link org.w3c.dom.Element}, or
{@link org.w3c.dom.DocumentFragment}. Specification of any other node
type is implementation dependent and undefined by this API. If the result is a
{@link org.w3c.dom.Document}, the output of the transformation must have
a single element root to set as the document element.

The {@link javax.xml.transform.dom.DOMLocator} node may be passed
to {@link javax.xml.transform.TransformerException} objects, and
retrieved by trying to cast the result of the
{@link javax.xml.transform.TransformerException#getLocator()} method.
The implementation has no responsibility to use a DOMLocator instead of a
{@link javax.xml.transform.SourceLocator} (though line numbers and the
like do not make much sense for a DOM), so the result of getLocator must always
be tested with an instanceof.