text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FlatRedBall.Content.AnimationChain;
using FlatRedBall.Glue.Controls;
using System.Diagnostics;
using FlatRedBall.AnimationEditorForms.Controls;
using FlatRedBall.AnimationEditorForms.Preview;
using FlatRedBall.IO;

namespace FlatRedBall.AnimationEditorForms
{
    public partial class TreeViewManager
    {
        #region Fields

        ContextMenuStrip mMenu;

        #endregion

        #region Initialize

        void InitializeRightClick()
        {
            mMenu = this.mTreeView.ContextMenuStrip;

        }

        #endregion

        public void HandleRightClick()
        {
            mMenu.Items.Clear();

            SelectedState state = SelectedState.Self;

            // If a frame is not null, then the chain will always be not null,
            // so check the frame first
            if (state.SelectedFrame != null)
            {
                mMenu.Items.Add("Copy", null, CopyClick);
                mMenu.Items.Add("Paste", null, PasteClick);
                mMenu.Items.Add("View Texture in Explorer", null, ViewTextureInExplorer);

                mMenu.Items.Add("Delete AnimationFrame", null, DeleteAnimationFrameClick);

            }
            else if (state.SelectedChain != null)
            {
                mMenu.Items.Add("Adjust All Frame Time", null, AdjustFrameTimeClick);
                mMenu.Items.Add("Adjust Offsets", null, AdjustOffsetsClick);
                mMenu.Items.Add("Flip Horizontally", null, FlipAnimationChainHorizontally);
                mMenu.Items.Add("Flip Vertically", null, FlipAnimationChainVertically);

                mMenu.Items.Add("-");
                mMenu.Items.Add("Add AnimationChain", null, AddChainClick);
                mMenu.Items.Add("Add Frame", null, AddFrameClick);
                mMenu.Items.Add("-");
                mMenu.Items.Add("Copy", null, CopyClick);
                mMenu.Items.Add("Paste", null, PasteClick);
                mMenu.Items.Add("-");
                mMenu.Items.Add("Delete AnimationChain", null, DeleteAnimationChainClick);
            }
            else
            {
                mMenu.Items.Add("Add AnimationChain", null, AddChainClick);
                mMenu.Items.Add("-");
                mMenu.Items.Add("Paste", null, PasteClick);

            }

            if (mMenu.Items.Count != 0)
            {
                mMenu.Items.Add("-");
            }

            mMenu.Items.Add("Sort Animations Alphabetically", null, SortAnimationsAlphabetically );

        }

        private void AdjustOffsetsClick(object sender, EventArgs e)
        {
            AdjustOffsetForm form = new AdjustOffsetForm();
            var result = form.ShowDialog();

            if (result == DialogResult.OK)
            {
                CallAnimationChainsChange();
            }
        }

        private void SortAnimationsAlphabetically(object sender, EventArgs e)
        {
            if (ProjectManager.Self.AnimationChainListSave != null)
            {
                ProjectManager.Self.AnimationChainListSave.AnimationChains.Sort(
                    (first, second) =>
                    {
                        return first.Name.CompareTo(second.Name);
                    }
                    );
                TreeViewManager.Self.RefreshTreeView();
                CallAnimationChainsChange();

            }
        }

        private void FlipAnimationChainVertically(object sender, EventArgs e)
        {
            AnimationChainSave acs = SelectedState.Self.SelectedChain;

            if (acs != null)
            {
                foreach (AnimationFrameSave afs in acs.Frames)
                {
                    afs.RelativeY *= -1;
                    afs.FlipVertical = !afs.FlipVertical;
                }

                WireframeManager.Self.RefreshAll();
                PreviewManager.Self.RefreshAll();
                CallAnimationChainsChange();

            }
        }

        private void FlipAnimationChainHorizontally(object sender, EventArgs e)
        {
            AnimationChainSave acs = SelectedState.Self.SelectedChain;

            if (acs != null)
            {
                foreach (AnimationFrameSave afs in acs.Frames)
                {
                    afs.RelativeX *= -1;
                    afs.FlipHorizontal = !afs.FlipHorizontal;
                }

                WireframeManager.Self.RefreshAll();
                PreviewManager.Self.RefreshAll();
                CallAnimationChainsChange();
            }
        }

        public void AddChainClick(object sender, EventArgs args)
        {
            if (ProjectManager.Self.AnimationChainListSave == null)
            {
                MessageBox.Show("You must first save a file before working in the Animation Editor");
            }
            else
            {
                TextInputWindow tiw = new TextInputWindow();
                tiw.DisplayText = "Enter new AnimationChain name";

                if (tiw.ShowDialog() == DialogResult.OK)
                {
                    string result = tiw.Result;

                    string whyIsntValid = GetWhyNameIsntValid(result);

                    if (!string.IsNullOrEmpty(whyIsntValid))
                    {
                        MessageBox.Show(whyIsntValid);
                    }
                    else
                    {
                        AnimationChainSave acs = new AnimationChainSave();
                        acs.Name = result;

                        ProjectManager.Self.AnimationChainListSave.AnimationChains.Add(acs);

                        TreeViewManager.Self.RefreshTreeView();
                        SelectedState.Self.SelectedChain = acs;

                        CallAnimationChainsChange();
                    }
                }
            }
        }

        public void AddFrameClick(object sender, EventArgs args)
        {
            AnimationChainSave chain = SelectedState.Self.SelectedChain;

            if (string.IsNullOrEmpty(ProjectManager.Self.FileName))
            {
                MessageBox.Show("You must first save this file before adding frames");
            }
            else if (chain == null)
            {
                MessageBox.Show("First select an Animation to add a frame to");
            }
            else
            {
                AnimationFrameSave afs = new AnimationFrameSave();

                if (chain.Frames.Count != 0)
                {
                    AnimationFrameSave copyFrom = chain.Frames[0];

                    afs.TextureName = copyFrom.TextureName;
                    afs.FrameLength = copyFrom.FrameLength;
                    afs.LeftCoordinate = copyFrom.LeftCoordinate;
                    afs.RightCoordinate = copyFrom.RightCoordinate;
                    afs.TopCoordinate = copyFrom.TopCoordinate;
                    afs.BottomCoordinate = copyFrom.BottomCoordinate;
                }
                else
                {
                    afs.FrameLength = .1f; // default to .1 seconds.
                }

                chain.Frames.Add(afs);

                TreeViewManager.Self.RefreshTreeNode(chain);

                SelectedState.Self.SelectedFrame = afs;

                CallAnimationChainsChange();
            }
        }

        void AdjustFrameTimeClick(object sender, EventArgs args)
        {
            float oldTotalLength = 0;
            AnimationChainSave animation = SelectedState.Self.SelectedChain;
            foreach (var frame in animation.Frames)
            {
                oldTotalLength += frame.FrameLength;
            }

            AnimationChainTimeScaleWindow window = new AnimationChainTimeScaleWindow();
            window.Value = oldTotalLength;
            window.FrameCount = animation.Frames.Count;
            DialogResult result = window.ShowDialog();

            if (result == DialogResult.OK && animation.Frames.Count != 0)
            {
                float newValue = window.Value;

                if (window.ScaleMode == ScaleMode.KeepProportional)
                {
                    float scaleValue = window.Value / oldTotalLength;

                    foreach (var frame in animation.Frames)
                    {
                        frame.FrameLength *= scaleValue;
                    }
                }
                else // value is to set all frames
                {
                    int frameCount = animation.Frames.Count;

                    foreach (var frame in animation.Frames)
                    {
                        frame.FrameLength = window.Value / frameCount;
                    }
                }

                PropertyGridManager.Self.Refresh();
                PreviewManager.Self.RefreshAll();
                this.CallAnimationChainsChange();
            }
        }

        void DeleteAnimationChainClick(object sender, EventArgs args)
        {
            if (SelectedState.Self.SelectedChain != null)
            {
                DialogResult result =
                    MessageBox.Show("Delete AnimationChain " + SelectedState.Self.SelectedChain + "?", "Delete?", MessageBoxButtons.YesNo);

                if (result == DialogResult.Yes)
                {
                    ProjectManager.Self.AnimationChainListSave.AnimationChains.Remove(SelectedState.Self.SelectedChain);

                    TreeViewManager.Self.RefreshTreeView();

                    CallAnimationChainsChange();

                    WireframeManager.Self.RefreshAll();
                }
            }
        }

        void DeleteAnimationFrameClick(object sender, EventArgs args)
        {
            if (SelectedState.Self.SelectedFrame != null)
            {
                DialogResult result =
                    MessageBox.Show("Delete Frame?", "Delete?", MessageBoxButtons.YesNo);

                if (result == DialogResult.Yes)
                {
                    SelectedState.Self.SelectedChain.Frames.Remove(SelectedState.Self.SelectedFrame);

                    TreeViewManager.Self.RefreshTreeNode(SelectedState.Self.SelectedChain);

                    CallAnimationChainsChange();
                }

            }
        }

        void ViewTextureInExplorer(object sender, EventArgs args)
        {

            string fileName = WireframeManager.Self.GetTextureFileNameForFrame(SelectedState.Self.SelectedFrame);

            if (!string.IsNullOrEmpty(fileName))
            {
                fileName = fileName.Replace("/", "\\");

                if (!string.IsNullOrEmpty(fileName) && System.IO.File.Exists(fileName))
                {
                    Process.Start("explorer.exe", "/select," + "\"" + fileName + "\"");

                }
            }
            else
            {
                MessageBox.Show("No texture set");
            }
        }

        string GetWhyNameIsntValid(string animationChainName)
        {
            foreach (var animationChain in ProjectManager.Self.AnimationChainListSave.AnimationChains)
            {
                if(animationChain.Name == animationChainName)
                {
                    return "The name " + animationChainName + " is already being used by another AnimationChain";
                }

            }
            if (string.IsNullOrEmpty(animationChainName))
            {
                return "The name can not be empty.";
            }

            return null;

        }

        void CopyClick(object sender, EventArgs args)
        {
            CopyManager.Self.HandleCopy();
        }

        void PasteClick(object sender, EventArgs args)
        {
            CopyManager.Self.HandlePaste();
            CallAnimationChainsChange();

        }
    }
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

# Parse UniProt (SwissProt & SPTrEMBL) files to create xrefs.
#
# Files actually contain both types of xref, distinguished by ID line;
#
# ID   CYC_PIG                 Reviewed;         104 AA.  Swissprot
# ID   Q3ASY8_CHLCH            Unreviewed;     36805 AA.  SPTrEMBL

package XrefParser::UniProtParser;

use strict;
use warnings;
use Carp;
use POSIX qw(strftime);
use File::Basename;

use base qw( XrefParser::BaseParser );

sub run {

  my ($self, $ref_arg) = @_;
  my $source_id    = $ref_arg->{source_id};
  my $species_id   = $ref_arg->{species_id};
  my $species_name = $ref_arg->{species};
  my $files        = $ref_arg->{files};
  my $release_file = $ref_arg->{rel_file};
  my $verbose      = $ref_arg->{verbose};
  my $dbi          = $ref_arg->{dbi};
  $dbi = $self->dbi unless defined $dbi;

  if((!defined $source_id) or (!defined $species_id) or (!defined $files)){
    croak "Need to pass source_id, species_id, files and rel_file as pairs";
  }
  $verbose |=0;

  my $file = @{$files}[0];

  my ( $sp_source_id, $sptr_source_id, $sp_release, $sptr_release, $sptr_non_display_source_id, $sp_direct_source_id, $sptr_direct_source_id, $isoform_source_id );

  $sp_source_id =
    $self->get_source_id_for_source_name('Uniprot/SWISSPROT','sequence_mapped', $dbi);
  $sptr_source_id =
    $self->get_source_id_for_source_name('Uniprot/SPTREMBL', 'sequence_mapped', $dbi);

  $sptr_non_display_source_id =
    $self->get_source_id_for_source_name('Uniprot/SPTREMBL', 'protein_evidence_gt_2', $dbi);

  $sp_direct_source_id = $self->get_source_id_for_source_name('Uniprot/SWISSPROT', 'direct', $dbi);
  $sptr_direct_source_id = $self->get_source_id_for_source_name('Uniprot/SPTREMBL', 'direct', $dbi);

  $isoform_source_id = $self->get_source_id_for_source_name('Uniprot_isoform');

  print "SwissProt source id for $file: $sp_source_id\n" if ($verbose);
  print "SpTREMBL source id for $file: $sptr_source_id\n" if ($verbose);
  print "SpTREMBL protein_evidence > 2 source id for $file: $sptr_non_display_source_id\n" if ($verbose);
  print "SwissProt direct source id for $file: $sp_direct_source_id\n" if ($verbose);
  print "SpTREMBL direct source id for $file: $sptr_direct_source_id\n" if ($verbose);

  $self->create_xrefs( $sp_source_id, $sptr_source_id, $sptr_non_display_source_id, $species_id,
      $file, $verbose, $sp_direct_source_id, $sptr_direct_source_id, $isoform_source_id, $dbi );

    if ( defined $release_file ) {
        # Parse Swiss-Prot and SpTrEMBL release info from
        # $release_file.
        my $release_io = $self->get_filehandle($release_file);
        while ( defined( my $line = $release_io->getline() ) ) {
            if ( $line =~ m#(UniProtKB/Swiss-Prot Release .*)# ) {
                $sp_release = $1;
                print "Swiss-Prot release is '$sp_release'\n" if($verbose);
            } elsif ( $line =~ m#(UniProtKB/TrEMBL Release .*)# ) {
                $sptr_release = $1;
                print "SpTrEMBL release is '$sptr_release'\n" if($verbose);
            }
        }
        $release_io->close();

        # Set releases
        $self->set_release( $sp_source_id,        $sp_release, $dbi );
        $self->set_release( $sptr_source_id,      $sptr_release, $dbi );
	$self->set_release( $sptr_non_display_source_id, $sptr_release, $dbi );
        $self->set_release( $sp_direct_source_id, $sp_release, $dbi );
        $self->set_release( $sptr_direct_source_id,$sptr_release, $dbi );
    }

  return 0; # successfull
}

# --------------------------------------------------------------------------------
# Parse file into array of xref objects

sub create_xrefs {
  my ($self, $sp_source_id, $sptr_source_id, $sptr_non_display_source_id, $species_id, $file, $verbose, $sp_direct_source_id, $sptr_direct_source_id, $isoform_source_id, $dbi ) = @_;

  my $num_sp = 0;
  my $num_sptr = 0;
  my $num_sp_pred = 0;
  my $num_sptr_pred = 0;
  my $num_sptr_non_display = 0;
  my $num_direct_sp = 0;
  my $num_direct_sptr = 0;

  my %dependent_sources = $self->get_xref_sources($dbi);

    my (%genemap) =
      %{ $self->get_valid_codes( "mim_gene", $species_id, $dbi ) };
    my (%morbidmap) =
      %{ $self->get_valid_codes( "mim_morbid", $species_id, $dbi ) };

    my $uniprot_io = $self->get_filehandle($file);
    if ( !defined $uniprot_io ) { return }

  my @xrefs;

  local $/ = "//\n";

  # Create a hash of all valid taxon_ids for this species
  my %species2tax = $self->species_id2taxonomy($dbi);
  push @{$species2tax{$species_id}}, $species_id;
  my @tax_ids = @{$species2tax{$species_id}};
  my %taxonomy2species_id = map{ $_=>$species_id } @tax_ids;

  my %dependent_xrefs;
  my $ensembl_derived_protein_count = 0;

  # Counter to process file in batches
  my $count = 0;

  while ( $_ = $uniprot_io->getline() ) {

    # if an OX line exists, only store the xref if the taxonomy ID that the OX
    # line refers to is in the species table
    # due to some records having more than one tax_id, we need to check them
    # all and only proceed if one of them matches.
    #OX   NCBI_TaxID=158878, 158879;
    #OX   NCBI_TaxID=103690;

    my ($ox) = $_ =~ /OX\s+[a-zA-Z_]+=([0-9 ,]+).*;/;
    my @ox = ();
    my $found = 0;

    if ( defined $ox ) {
        @ox = split /\, /, $ox;

        # my %taxonomy2species_id = $self->taxonomy2species_id();

        foreach my $taxon_id_from_file (@ox) {
          $taxon_id_from_file =~ s/\s//;
          if ( exists $taxonomy2species_id{$taxon_id_from_file} ){
            $found = 1;
            $count++;
          }
        }
    }

    next if (!$found); # no taxon_id's match, so skip to next record
    my $xref;

    # set accession (and synonyms if more than one)
    # AC line may have primary accession and possibly several ; separated synonyms
    # May also be more than one AC line
    my ($acc) = $_ =~ /(\nAC\s+.+)/s; # will match first AC line and everything else

    my @all_lines = split /\n/, $acc;

    # Check for CC (caution) lines containing certain text
    # If sequence is from Ensembl, do not use
    my $ensembl_derived_protein = 0;
    if ($_ =~ /CAUTION: The sequence shown here is derived from an Ensembl/) {
      $ensembl_derived_protein = 1;
      $ensembl_derived_protein_count++;
    }

    # extract ^AC lines only & build list of accessions
    my @accessions;
    foreach my $line (@all_lines) {
      my ($accessions_only) = $line =~ /^AC\s+(.+)/;
      push(@accessions, (split /;\s*/, $accessions_only)) if ($accessions_only);

    }

    if(lc($accessions[0]) eq "unreviewed"){
      print "WARNING: entries with accession of $acc not allowed will be skipped\n";
      next;
    }
    $xref->{INFO_TYPE} = "SEQUENCE_MATCH";
    $xref->{ACCESSION} = $accessions[0];
    for (my $a=1; $a <= $#accessions; $a++) {
      push(@{$xref->{"SYNONYMS"} }, $accessions[$a]);
    }

    my ($label, $sp_type) = $_ =~ /ID\s+(\w+)\s+(\w+)/;
    my ($protein_evidence_code) = $_ =~ /PE\s+(\d+)/;
    # Capture line with entry version
    # Example: DT   22-APR-2020, entry version 1.
    my ($version) = $_ =~ /DT\s+\d+-\w+-\d+, entry version (\d+)/;

    # SwissProt/SPTrEMBL are differentiated by having STANDARD/PRELIMINARY here
    if ($sp_type =~ /^Reviewed/i) {

      $xref->{SOURCE_ID} = $sp_source_id;
      $num_sp++;
    } elsif ($sp_type =~ /Unreviewed/i) {

    #Use normal source only if it is PE levels 1 & 2
      if (defined($protein_evidence_code) && $protein_evidence_code < 3) {
          $xref->{SOURCE_ID} = $sptr_source_id;
          $num_sptr++;
      } else {
          $xref->{SOURCE_ID} = $sptr_non_display_source_id;
          $num_sptr_non_display++;
      }

    } else {

      next; # ignore if it's neither one nor t'other

    }

    # some straightforward fields
    # the previous $label flag of type BRCA2_HUMAN is not used in Uniprot any more, use accession instead
    $xref->{LABEL} = $accessions[0] ."." . $version;
    $xref->{VERSION} = $version;
    $xref->{SPECIES_ID} = $species_id;
    $xref->{SEQUENCE_TYPE} = 'peptide';
    $xref->{STATUS} = 'experimental';

    # May have multi-line descriptions
    my ($description_and_rest) = $_ =~ /(DE\s+.*)/s;
    @all_lines = split /\n/, $description_and_rest;

    # extract ^DE lines only & build cumulative description string
    my $description = "";
    my $name        = "";
    my $sub_description = "";

    foreach my $line (@all_lines) {

      next if(!($line =~ /^DE/));

      # get the data
      if($line =~ /^DE   RecName: Full=(.*);/){
        $name .= '; ' if $name ne q{}; #separate multiple sub-names with a '; '
        $name .= $1;
      }
      elsif($line =~ /RecName: Full=(.*);/){
        $description .= ' ' if $description ne q{}; #separate the description bit with just a space
        $description .= $1;
      }
      elsif($line =~ /SubName: Full=(.*);/){
        $name .= '; ' if $name ne q{}; #separate multiple sub-names with a '; '
        $name .= $1;
      }

      $description =~ s/^\s*//g;
      $description =~ s/\s*$//g;

      my $desc = $name.' '.$description;
      if(!length($desc)){
	$desc = $sub_description;
      }

      $desc =~ s/\s*\{ECO:.*?\}//g;
      $xref->{DESCRIPTION} = $desc;

      # Parse the EC_NUMBER line, only for S.cerevisiae for now

      if (($line =~ /EC=/) && ($species_id == 4932)) {

	  #print STDERR "EC Number line: $line\n";

	  $line =~ /^DE\s+EC=([^;]+);/;

	  # Get the EC Number and make it an xref for S.cer if any

	  my $EC = $1;

	  #print STDERR "EC after processing: $EC\n";

	  my %depe;
	  $depe{LABEL} = $EC;
	  $depe{ACCESSION} = $EC;

	  $depe{SOURCE_NAME} = "EC_NUMBER";

	  $depe{SOURCE_ID} = $dependent_sources{"EC_NUMBER"};
	  $depe{LINKAGE_SOURCE_ID} = $xref->{SOURCE_ID};
	  push @{$xref->{DEPENDENT_XREFS}}, \%depe;
	  $dependent_xrefs{"EC_NUMBER"}++;
      }

    }

    # extract sequence
    my ($seq) = $_ =~ /SQ\s+(.+)/s; # /s allows . to match newline
      my @seq_lines = split /\n/, $seq;
    my $parsed_seq = "";
    foreach my $x (@seq_lines) {
      $parsed_seq .= $x;
    }
    $parsed_seq =~ s/\/\///g;   # remove trailing end-of-record character
    $parsed_seq =~ s/\s//g;     # remove whitespace
    $parsed_seq =~ s/^.*;//g;   # remove everything before last ;

    $xref->{SEQUENCE} = $parsed_seq;
    #print "Adding " . $xref->{ACCESSION} . " " . $xref->{LABEL} ."\n";

    my ($gns) = $_ =~ /(GN\s+.+)/s;
    my @gn_lines = ();
    if ( defined $gns ) { @gn_lines = split /;/, $gns }

    # Do not allow the addition of UniProt Gene Name dependent Xrefs
    # if the protein was imported from Ensembl. Otherwise we will
    # re-import previously set symbols
    if(! $ensembl_derived_protein) {
      my %depe;
      foreach my $gn (@gn_lines){
# Make sure these are still lines with Name or Synonyms
        if (($gn !~ /^GN/ || $gn !~ /Name=/) && $gn !~ /Synonyms=/) { last; }
        my $gene_name = undef;

        if ($gn =~ / Name=([A-Za-z0-9_\-\.\s]+)/s) { #/s for multi-line entries ; is the delimiter
# Example line
# GN   Name=ctrc {ECO:0000313|Xenbase:XB-GENE-5790348};
          my $name = $1;
          $name =~ s/\s+$//g; # Remove white spaces that are left over at the end if there was an evidence code
          $depe{LABEL} = $name; # leave name as is, upper/lower case is relevant in gene names
          $depe{ACCESSION} = $self->get_name($xref->{ACCESSION},$depe{LABEL});
          $gene_name = $depe{ACCESSION};

          $depe{SOURCE_NAME} = "Uniprot_gn";
          $depe{SOURCE_ID} = $dependent_sources{"Uniprot_gn"};
          $depe{LINKAGE_SOURCE_ID} = $xref->{SOURCE_ID};
          push @{$xref->{DEPENDENT_XREFS}}, \%depe;
          $dependent_xrefs{"Uniprot_gn"}++;
        }
        my @syn;
        if($gn =~ /Synonyms=(.*)/s){ # use of /s as synonyms can be across more than one line
# Example line
# GN   Synonyms=cela2a {ECO:0000313|Ensembl:ENSXETP00000014934},
# GN   MGC79767 {ECO:0000313|EMBL:AAH80976.1}
          my $syn = $1;
          $syn =~ s/{.*}//g;  # Remove any potential evidence codes
          $syn =~ s/\n//g;    # Remove return carriages, as entry can span several lines
          $syn =~ s/\s+$//g;  # Remove white spaces that are left over at the end if there was an evidence code
          #$syn =~ s/^\s+//g;  # Remove white spaces that are left over at the beginning if there was an evidence code
          $syn =~ s/\s+,/,/g;  # Remove white spaces that are left over before the comma if there was an evidence code
          @syn = split(/, /,$syn);
          push (@{$depe{"SYNONYMS"}}, @syn);
        }
      }
    }

    # dependent xrefs - only store those that are from sources listed in the source table
    my ($deps) = $_ =~ /(DR\s+.+)/s; # /s allows . to match newline

    my @dep_lines = ();
    if ( defined $deps ) { @dep_lines = split /\n/, $deps }

    my %seen=();  # per record basis

    foreach my $dep (@dep_lines) {
      #both GO and UniGene have the own sources so ignore those in the uniprot files
      #as the uniprot data should be older
      if($dep =~ /GO/ || $dep =~ /UniGene/){
	next;
      }
      if ($dep =~ /^DR\s+(.+)/) {
        my ($source, $acc, @extra) = split /;\s*/, $1;
        if($source =~ "RGD"){  #using RGD file now instead.
      	  next;
      	}
        if($source =~ "CCDS"){
          next;
        }
      	if($source =~ "IPI"){
      	  next;
      	}
      	if($source =~ "UCSC"){
      	  next;
      	}
      	if($source =~ "SGD"){
      	  next;
      	}
      	if($source =~ "HGNC"){
      	  next;
      	}
        # We get the mappings directly from the source
        if($source =~ "MGI"){
          next;
        }
        # Nomenclature data is imported directly from the source
        if($source =~ "VGNC"){
          next;
        }
      	if($source =~ "Orphanet"){
      	  #we don't want to parse Orphanet xrefs via Uniprot, we get them from Orphanet with descriptions
      	  next;
      	}
      	if($source =~ "ArrayExpress"){
      	    next;
      	}
        if($source =~ "GenomeRNAi" || $source =~ "EPD"){
            next;
        }
        if($source =~ "Xenbase"){
            next;
        }
# Uniprot get Reactome links from Reactome, so we want to get the info from Reactome directly
        if($source =~ "Reactome"){
            next;
        }
# MIM xrefs are already imported separately, ignore from Uniprot
# Also, Uniprot deals with proteins, not appropriate for gene level xrefs
        if ($source =~ "MIM_GENE" || $source =~ "MIM_MORBID" || $source =~ "MIM") {
            next;
        }
# If mapped to Ensembl, add as direct xref
        if ($source eq "Ensembl") {
# Example line:
# DR   Ensembl; ENST00000380152; ENSP00000369497; ENSG00000139618.
# DR   Ensembl; ENST00000372839; ENSP00000361930; ENSG00000166913. [P31946-1]
# $source is Ensembl, $acc is ENST00000380152 and @extra is the rest of the line
# If the UniProt accession is repeated here, it links to a specific isoform
          my %direct;
          my $isoform;
          $direct{STABLE_ID} = $extra[0];
          $direct{ENSEMBL_TYPE} = 'Translation';
          $direct{LINKAGE_TYPE} = 'DIRECT';
          if ($xref->{SOURCE_ID} == $sp_source_id) {
            $direct{SOURCE_ID} = $sp_direct_source_id;
            $num_direct_sp++;
          } else {
            $direct{SOURCE_ID} = $sptr_direct_source_id;
            $num_direct_sptr++;
          }
          push @{$xref->{DIRECT_XREFS}}, \%direct;

          my $uniprot_acc = $accessions[0];
          if ($extra[1] =~ /($accessions[0]-[0-9]+)/) {
            $isoform = $1;
            $self->add_to_direct_xrefs({
              stable_id  => $extra[0],
              type       => 'translation',
              acc        => $isoform,
              label      => $isoform,
              dbi        => $dbi,
              source_id  => $isoform_source_id,
              linkage    => 'DIRECT',
              species_id => $species_id
            });
          }
        }
	   if (exists $dependent_sources{$source} ) {
	  # create dependent xref structure & store it
	  my %dep;
          $dep{SOURCE_NAME} = $source;
          $dep{LINKAGE_SOURCE_ID} = $xref->{SOURCE_ID};
          $dep{SOURCE_ID} = $dependent_sources{$source};

	  if($source =~ /HGNC/){
	    $acc =~ s/HGNC://;
	    $extra[0] =~ s/[.]//;
	    $dep{LABEL} = $extra[0];
	  }
	  $dep{ACCESSION} = $acc;

#	  $dep{ACCESSION} = $acc;
	  $dependent_xrefs{ $dep{SOURCE_NAME} }++; # get count of depenent xrefs.
	  if(!defined($seen{$dep{SOURCE_NAME}.":".$dep{ACCESSION}})){
	    push @{$xref->{DEPENDENT_XREFS}}, \%dep; # array of hashrefs
	    $seen{$dep{SOURCE_NAME}.":".$dep{ACCESSION}} =1;
	  }
	  if($dep =~ /EMBL/ && !($dep =~ /ChEMBL/)){
	    my ($protein_id) = $extra[0];
	    if(($protein_id ne "-") and (!defined($seen{$source.":".$protein_id}))){
	      my %dep2;
	      $dep2{SOURCE_NAME} = $source;
	      $dep2{SOURCE_ID} = $dependent_sources{"protein_id"};
	      $dep2{LINKAGE_SOURCE_ID} = $xref->{SOURCE_ID};
	      # store accession unversioned
	      $dep2{LABEL} = $protein_id;
	      my ($prot_acc, $prot_version) = $protein_id =~ /([^.]+)\.([^.]+)/;
	      $dep2{ACCESSION} = $prot_acc;
	      $dependent_xrefs{ $dep2{SOURCE_NAME} }++; # get count of dependent xrefs.
	      $seen{$source.":".$protein_id} = 1;
	      push @{$xref->{DEPENDENT_XREFS}}, \%dep2; # array of hashrefs
	    }
	  }
	}
      }
    }

    push @xrefs, $xref;

    if ($count > 1000) {
      $self->upload_xref_object_graphs(\@xrefs, $dbi);
      $count = 0;
      undef @xrefs;
    }

  }

  $self->upload_xref_object_graphs(\@xrefs, $dbi) if scalar(@xrefs) > 0;

  $uniprot_io->close();

  print "Read $num_sp SwissProt xrefs, $num_sptr SPTrEMBL xrefs with protein evidence codes 1-2, and $num_sptr_non_display SPTrEMBL xrefs with protein evidence codes > 2 from $file\n" if($verbose);
  print "Added $num_direct_sp direct SwissProt xrefs and $num_direct_sptr direct SPTrEMBL xrefs\n" if ($verbose);
  print "Found $num_sp_pred predicted SwissProt xrefs and $num_sptr_pred predicted SPTrEMBL xrefs\n" if (($num_sp_pred > 0 || $num_sptr_pred > 0) and $verbose);
  print "Skipped $ensembl_derived_protein_count ensembl annotations as Gene names\n";

#  print "$kount gene anmes added\n";

  print "Added the following dependent xrefs:-\n" if($verbose);
  foreach my $key (keys %dependent_xrefs){
    print $key."\t".$dependent_xrefs{$key}."\n" if($verbose);
  }
  print "End.\n" if ($verbose);

  #TODO - currently include records from other species - filter on OX line??
}

sub get_name {
  my $self = shift;
  my $acc  = shift;
  my $label = shift;

  return $acc;
}
1;

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using Unitilities.Timers;

public class DestroyAfterTimerEnds : MonoBehaviour
{
    Timer autodestructTimer;

    public float targetTime = 1f;

	// Use this for initialization
	void Start ()
    {
        autodestructTimer = new Timer(targetTime);
	}

	// Update is called once per frame
	void Update ()
    {
        if (autodestructTimer.Update() == TimerState.FINISHED)
            Destroy(gameObject);
	}
}


text:
// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package routines.system;

import java.util.ArrayList;
import java.util.List;

/**
 * created by bchen on Jul 24, 2013 Detailled comment
 *
 */
public class SparkStreamingRunStat extends MRRunStat {

    protected List<StatBean> messages = new ArrayList<>();

    public SparkStreamingRunStat() {
        super();
    }

    public class StatBean {

        private String subjobId;

        private int batchCompleted;

        private int batchStarted;

        private String lastProcessingDelay;

        private String lastSchedulingDelay;

        private String lastTotalDelay;

        public String getSubjobId() {
            return this.subjobId;
        }

        public void setSubjobId(String subjobId) {
            this.subjobId = subjobId;
        }

        public int getBatchCompleted() {
            return this.batchCompleted;
        }

        public void setBatchCompleted(int batchCompleted) {
            this.batchCompleted = batchCompleted;
        }

        public int getBatchStarted() {
            return this.batchStarted;
        }

        public void setBatchStarted(int batchStarted) {
            this.batchStarted = batchStarted;
        }

        public String getLastProcessingDelay() {
            return this.lastProcessingDelay;
        }

        public void setLastProcessingDelay(String lastProcessingDelay) {
            this.lastProcessingDelay = lastProcessingDelay;
        }

        public String getLastSchedulingDelay() {
            return this.lastSchedulingDelay;
        }

        public void setLastSchedulingDelay(String lastSchedulingDelay) {
            this.lastSchedulingDelay = lastSchedulingDelay;
        }

        public String getLastTotalDelay() {
            return this.lastTotalDelay;
        }

        public void setLastTotalDelay(String lastTotalDelay) {
            this.lastTotalDelay = lastTotalDelay;
        }

        public String toStatFormat() {
            String stats = rootPid + "|" + fatherPid + "|" + pid + "|" + this.subjobId + "|" + this.batchCompleted + "|"
                    + this.batchStarted + "|" + this.lastProcessingDelay + "|" + this.lastSchedulingDelay + "|"
                    + this.lastTotalDelay;

            return stats;
        }
    }

    public StatBean createSparkStreamingStatBean() {
        return new StatBean();
    }

    @Override
    public void sendMessages() {
        for (StatBean message : messages) {
            pred.println(message.toStatFormat());
        }
        messages.clear();
    }

    public synchronized void updateSparkStreamingData(StatBean message) {
        messages.add(message);
    }

    // for feature:10589
    private String rootPid = null;

    private String fatherPid = null;

    private String pid = "0";

    // Notice: this API should be invoked after startThreadStat() closely.
    public void setAllPID(String rootPid, String fatherPid, String pid) {
        this.rootPid = rootPid;
        this.fatherPid = fatherPid;
        this.pid = pid;
    }
}


text:
require 'delegate'
require_relative 'pdflib_mini/info'
require_relative 'pdflib_mini/info_reader'
require_relative 'pdflib_mini/handle'
require_relative 'pdflib_mini/handle/base'
require_relative 'pdflib_mini/handle/action'
require_relative 'pdflib_mini/handle/asset'
require_relative 'pdflib_mini/handle/bookmark'
require_relative 'pdflib_mini/handle/color'
require_relative 'pdflib_mini/handle/data3d'
require_relative 'pdflib_mini/handle/data3d_view'
require_relative 'pdflib_mini/handle/folder'
require_relative 'pdflib_mini/handle/font'
require_relative 'pdflib_mini/handle/graphics'
require_relative 'pdflib_mini/handle/image'
require_relative 'pdflib_mini/handle/item'
require_relative 'pdflib_mini/handle/layer'
require_relative 'pdflib_mini/handle/path'
require_relative 'pdflib_mini/handle/pattern'
require_relative 'pdflib_mini/handle/pdf'
require_relative 'pdflib_mini/handle/pdf/document'
require_relative 'pdflib_mini/handle/pdf/page'
require_relative 'pdflib_mini/handle/profile'
require_relative 'pdflib_mini/handle/shading'
require_relative 'pdflib_mini/handle/table_cell'
require_relative 'pdflib_mini/handle/template'
require_relative 'pdflib_mini/handle/textflow'
require_relative 'pdflib_mini/handle/textline'
require_relative 'pdflib_mini/pdflib'
require_relative "pdflib_mini/version"

module PdflibMini
  def self.new
    PdflibMini::Pdflib.new(Kernel.const_get(:PDFlib).new)
  end
end

PDFlibMini = PdflibMini


text:
require 'rubygems/test_case'

class TestGemImpossibleDependenciesError < Gem::TestCase

  def test_message_conflict
    request = dependency_request dep('net-ssh', '>= 2.0.13'), 'rye', '0.9.8'

    conflicts = []

    # These conflicts are lies as their dependencies does not have the correct
    # requested-by entries, but they are suitable for testing the message.
    # See #485 to construct a correct conflict.
    net_ssh_2_2_2 =
      dependency_request dep('net-ssh', '>= 2.6.5'), 'net-ssh', '2.2.2', request
    net_ssh_2_6_5 =
      dependency_request dep('net-ssh', '~> 2.2.2'), 'net-ssh', '2.6.5', request

    conflict1 = Gem::Resolver::Conflict.new \
      net_ssh_2_6_5, net_ssh_2_6_5.requester

    conflict2 = Gem::Resolver::Conflict.new \
      net_ssh_2_2_2, net_ssh_2_2_2.requester

    conflicts << [net_ssh_2_6_5.requester.spec, conflict1]
    conflicts << [net_ssh_2_2_2.requester.spec, conflict2]

    error = Gem::ImpossibleDependenciesError.new request, conflicts

    expected = <<-EXPECTED
rye-0.9.8 requires net-ssh (>= 2.0.13) but it conflicted:
  Activated net-ssh-2.6.5
  which does not match conflicting dependency (~> 2.2.2)

  Conflicting dependency chains:
    rye (= 0.9.8), 0.9.8 activated, depends on
    net-ssh (>= 2.0.13), 2.6.5 activated

  versus:
    rye (= 0.9.8), 0.9.8 activated, depends on
    net-ssh (>= 2.0.13), 2.6.5 activated, depends on
    net-ssh (~> 2.2.2)

  Activated net-ssh-2.2.2
  which does not match conflicting dependency (>= 2.6.5)

  Conflicting dependency chains:
    rye (= 0.9.8), 0.9.8 activated, depends on
    net-ssh (>= 2.0.13), 2.2.2 activated

  versus:
    rye (= 0.9.8), 0.9.8 activated, depends on
    net-ssh (>= 2.0.13), 2.2.2 activated, depends on
    net-ssh (>= 2.6.5)

    EXPECTED

    assert_equal expected, error.message
  end

end


text:
'use strict';

/**
 * @ngdoc service
 * @name uiApp.sharedProperty
 * @description
 * # sharedProperty
 * Factory in the uiApp.
 */
angular.module('uiApp')
  .factory('sharedProperty', [function () {
    var propertyObject = {property: {}};
    propertyObject.clear = function () {
        angular.copy({}, this.property);
    };
    return propertyObject;
}]);


text:
@interface MQNotification() <MQJsonParsable>

+ (NSArray *) parseArray:(NSArray *)src;
+ (instancetype) instantiateFromJSON:(id)json;

@end


text:
package net.larry1123.util.api.database;

import net.canarymod.database.DataAccess;
import net.canarymod.database.Database;
import net.canarymod.database.exceptions.DatabaseReadException;
import net.canarymod.database.exceptions.DatabaseWriteException;

import java.util.ArrayList;
import java.util.Map;

public abstract class Data extends DataAccess {

    public Data(String tableName) {
        super(tableName);
    }

    public Data(String tableName, String tableSuffix) {
        super(tableName, tableSuffix);
    }

    protected void load(Map<String, Object> filter) throws DatabaseReadException {
        Database.get().load(this, filter);
    }

    protected void update(Map<String, Object> filter) throws DatabaseWriteException {
        Database.get().update(this, filter);
    }

    protected void insert() throws DatabaseWriteException {
        Database.get().insert(this);
    }

    protected ArrayList<DataAccess> loadAll(Map<String, Object> filter) throws DatabaseReadException {
        ArrayList<DataAccess> ret = new ArrayList<DataAccess>();
        Database.get().loadAll(this, ret, filter);
        return ret;
    }

    protected void remove(Map<String, Object> filter) throws DatabaseWriteException {
        Database.get().remove(this, filter);
    }

    protected void updateSchema() throws DatabaseWriteException {
        Database.get().updateSchema(this);
    }

}


text:
package com.tinkerpop.gremlin.neo4j.structure;

import com.tinkerpop.gremlin.neo4j.process.graph.Neo4jTraversal;
import com.tinkerpop.gremlin.neo4j.process.graph.Neo4jVertexTraversal;
import com.tinkerpop.gremlin.neo4j.process.graph.util.Neo4jGraphTraversal;
import com.tinkerpop.gremlin.process.T;
import com.tinkerpop.gremlin.process.graph.step.sideEffect.StartStep;
import com.tinkerpop.gremlin.structure.Direction;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Property;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.VertexProperty;
import com.tinkerpop.gremlin.structure.util.ElementHelper;
import com.tinkerpop.gremlin.structure.util.StringFactory;
import com.tinkerpop.gremlin.structure.util.wrapped.WrappedVertex;
import com.tinkerpop.gremlin.util.StreamFactory;
import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.graphdb.Relationship;

import java.util.Iterator;
import java.util.stream.Stream;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class Neo4jVertex extends Neo4jElement implements Vertex, Vertex.Iterators, WrappedVertex<Node>, Neo4jVertexTraversal {

    public Neo4jVertex(final Node node, final Neo4jGraph graph) {
        super(graph);
        this.baseElement = node;
    }

    @Override
    public <V> VertexProperty<V> property(final String key) {
        this.graph.tx().readWrite();
        if (!this.graph.supportsMultiProperties) {
            return existsInNeo4j(key) ? new Neo4jVertexProperty<V>(this, key, (V) this.getBaseVertex().getProperty(key)) : VertexProperty.<V>empty();
        } else {
            if (existsInNeo4j(key)) {
                if (this.getBaseVertex().getProperty(key).equals(Neo4jVertexProperty.VERTEX_PROPERTY_TOKEN)) {
                    if (this.getBaseVertex().getDegree(DynamicRelationshipType.withName(Neo4jVertexProperty.VERTEX_PROPERTY_PREFIX.concat(key)), org.neo4j.graphdb.Direction.OUTGOING) > 1)
                        throw Vertex.Exceptions.multiplePropertiesExistForProvidedKey(key);
                    else
                        return new Neo4jVertexProperty<>(this, this.getBaseVertex().getRelationships(org.neo4j.graphdb.Direction.OUTGOING, DynamicRelationshipType.withName(Neo4jVertexProperty.VERTEX_PROPERTY_PREFIX.concat(key))).iterator().next().getEndNode());
                } else {
                    return new Neo4jVertexProperty<>(this, key, (V) this.getBaseVertex().getProperty(key));
                }
            } else
                return VertexProperty.<V>empty();
        }
    }

    @Override
    public <V> VertexProperty<V> property(final String key, final V value) {
        ElementHelper.validateProperty(key, value);
        this.graph.tx().readWrite();
        try {
            if (!this.graph.supportsMultiProperties) {
                this.getBaseVertex().setProperty(key, value);
                return new Neo4jVertexProperty<>(this, key, value);
            } else {
                final String prefixedKey = Neo4jVertexProperty.VERTEX_PROPERTY_PREFIX.concat(key);
                if (this.getBaseVertex().hasProperty(key)) {
                    if (this.getBaseVertex().getProperty(key).equals(Neo4jVertexProperty.VERTEX_PROPERTY_TOKEN)) {
                        final Node node = this.graph.getBaseGraph().createNode(Neo4jVertexProperty.VERTEX_PROPERTY_LABEL, DynamicLabel.label(Graph.Key.unHide(key)));
                        node.setProperty(T.key.getAccessor(), key);
                        node.setProperty(T.value.getAccessor(), value);
                        this.getBaseVertex().createRelationshipTo(node, DynamicRelationshipType.withName(prefixedKey));
                        return new Neo4jVertexProperty<>(this, node);
                    } else {
                        Node node = this.graph.getBaseGraph().createNode(Neo4jVertexProperty.VERTEX_PROPERTY_LABEL, DynamicLabel.label(Graph.Key.unHide(key)));
                        node.setProperty(T.key.getAccessor(), key);
                        node.setProperty(T.value.getAccessor(), this.getBaseVertex().removeProperty(key));
                        this.getBaseVertex().createRelationshipTo(node, DynamicRelationshipType.withName(prefixedKey));
                        this.getBaseVertex().setProperty(key, Neo4jVertexProperty.VERTEX_PROPERTY_TOKEN);
                        node = this.graph.getBaseGraph().createNode(Neo4jVertexProperty.VERTEX_PROPERTY_LABEL, DynamicLabel.label(Graph.Key.unHide(key)));
                        node.setProperty(T.key.getAccessor(), key);
                        node.setProperty(T.value.getAccessor(), value);
                        this.getBaseVertex().createRelationshipTo(node, DynamicRelationshipType.withName(prefixedKey));
                        return new Neo4jVertexProperty<>(this, node);
                    }
                } else {
                    this.getBaseVertex().setProperty(key, value);
                    return new Neo4jVertexProperty<>(this, key, value);
                }
            }
        } catch (IllegalArgumentException iae) {
            throw Property.Exceptions.dataTypeOfPropertyValueNotSupported(value);
        }
    }

    @Override
    public <V> VertexProperty<V> singleProperty(final String key, final V value, final Object... keyValues) {
        if (!this.graph.supportsMultiProperties) {
            this.getBaseVertex().setProperty(key, value);
            return new Neo4jVertexProperty<>(this, key, value);
        } else {
            ElementHelper.legalPropertyKeyValueArray(keyValues);
            this.graph.tx().readWrite();
            final String prefixedKey = Neo4jVertexProperty.VERTEX_PROPERTY_PREFIX.concat(key);
            this.getBaseVertex().getRelationships(org.neo4j.graphdb.Direction.OUTGOING, DynamicRelationshipType.withName(prefixedKey)).forEach(relationship -> {
                final Node multiPropertyNode = relationship.getEndNode();
                relationship.delete();
                multiPropertyNode.delete();
            });
            if (keyValues.length == 0) {
                this.getBaseVertex().setProperty(key, value);
                return new Neo4jVertexProperty<>(this, key, value);
            } else {
                this.getBaseVertex().setProperty(key, Neo4jVertexProperty.VERTEX_PROPERTY_TOKEN);
                final Node node = this.graph.getBaseGraph().createNode(Neo4jVertexProperty.VERTEX_PROPERTY_LABEL, DynamicLabel.label(Graph.Key.unHide(key)));
                node.setProperty(T.key.getAccessor(), key);
                node.setProperty(T.value.getAccessor(), value);
                for (int i = 0; i < keyValues.length; i = i + 2) {
                    node.setProperty((String) keyValues[i], keyValues[i + 1]);
                }
                this.getBaseVertex().createRelationshipTo(node, DynamicRelationshipType.withName(prefixedKey));
                return new Neo4jVertexProperty<>(this, node);
            }
        }
    }

    @Override
    public void remove() {
        if (this.removed) throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.getBaseVertex().getId());
        this.removed = true;
        this.graph.tx().readWrite();
        try {
            final Node node = this.getBaseVertex();
            for (final Relationship relationship : node.getRelationships(org.neo4j.graphdb.Direction.BOTH)) {
                final Node otherNode = relationship.getOtherNode(node);
                if (otherNode.hasLabel(Neo4jVertexProperty.VERTEX_PROPERTY_LABEL)) {
                    otherNode.getRelationships().forEach(Relationship::delete);
                    otherNode.delete(); // meta property node
                } else
                    relationship.delete();
            }
            node.delete();
        } catch (final NotFoundException ignored) {
            // this one happens if the vertex is committed
        } catch (final IllegalStateException ignored) {
            // this one happens if the vertex is still chilling in the tx
        }
    }

    @Override
    public Edge addEdge(final String label, final Vertex inVertex, final Object... keyValues) {
        ElementHelper.validateLabel(label);
        ElementHelper.legalPropertyKeyValueArray(keyValues);
        if (ElementHelper.getIdValue(keyValues).isPresent())
            throw Edge.Exceptions.userSuppliedIdsNotSupported();

        this.graph.tx().readWrite();
        final Node node = (Node) this.baseElement;
        final Neo4jEdge edge = new Neo4jEdge(node.createRelationshipTo(((Neo4jVertex) inVertex).getBaseVertex(),
                DynamicRelationshipType.withName(label)), this.graph);
        ElementHelper.attachProperties(edge, keyValues);
        return edge;
    }

    @Override
    public Neo4jTraversal<Vertex, Vertex> start() {
        final Neo4jTraversal<Vertex, Vertex> traversal = new Neo4jGraphTraversal<>(this.graph);
        return (Neo4jTraversal) traversal.addStep(new StartStep<>(traversal, this));
    }

    @Override
    public Node getBaseVertex() {
        return (Node) this.baseElement;
    }

    @Override
    public String label() {
        this.graph.tx().readWrite();
        return this.getBaseVertex().getLabels().iterator().next().name();
    }

    @Override
    public String toString() {
        return StringFactory.vertexString(this);
    }

    @Override
    public Vertex.Iterators iterators() {
        return this;
    }

    @Override
    public Iterator<Vertex> vertexIterator(final Direction direction, final String... labels) {
        graph.tx().readWrite();
        return (Iterator) Neo4jHelper.getVertices(Neo4jVertex.this, direction, labels).iterator();
    }

    @Override
    public Iterator<Edge> edgeIterator(final Direction direction, final String... edgeLabels) {
        graph.tx().readWrite();
        return (Iterator) Neo4jHelper.getEdges(Neo4jVertex.this, direction, edgeLabels).iterator();
    }

    @Override
    public <V> Iterator<VertexProperty<V>> propertyIterator(final String... propertyKeys) {
        graph.tx().readWrite();
        return (Iterator) StreamFactory.stream(getBaseVertex().getPropertyKeys())
                .filter(key -> propertyKeys.length == 0 || Stream.of(propertyKeys).filter(k -> k.equals(key)).findAny().isPresent())
                .filter(key -> !Graph.Key.isHidden(key))
                .flatMap(key -> {
                    if (getBaseVertex().getProperty(key).equals(Neo4jVertexProperty.VERTEX_PROPERTY_TOKEN))
                        return StreamFactory.stream(getBaseVertex().getRelationships(org.neo4j.graphdb.Direction.OUTGOING, DynamicRelationshipType.withName(Neo4jVertexProperty.VERTEX_PROPERTY_PREFIX.concat(key))))
                                .map(relationship -> new Neo4jVertexProperty(Neo4jVertex.this, relationship.getEndNode()));
                    else
                        return Stream.of(new Neo4jVertexProperty<>(Neo4jVertex.this, key, (V) getBaseVertex().getProperty(key)));
                }).iterator();
    }

    @Override
    public <V> Iterator<VertexProperty<V>> hiddenPropertyIterator(final String... propertyKeys) {
        graph.tx().readWrite();
        return (Iterator) StreamFactory.stream(getBaseVertex().getPropertyKeys())
                .filter(Graph.Key::isHidden)
                .filter(key -> propertyKeys.length == 0 || Stream.of(propertyKeys).filter(k -> k.equals(Graph.Key.unHide(key))).findAny().isPresent())
                .flatMap(key -> {
                    if (getBaseVertex().getProperty(key).equals(Neo4jVertexProperty.VERTEX_PROPERTY_TOKEN))
                        return StreamFactory.stream(getBaseVertex().getRelationships(org.neo4j.graphdb.Direction.OUTGOING, DynamicRelationshipType.withName(Neo4jVertexProperty.VERTEX_PROPERTY_PREFIX.concat(key))))
                                .map(relationship -> new Neo4jVertexProperty(Neo4jVertex.this, relationship.getEndNode()));
                    else
                        return Stream.of(new Neo4jVertexProperty<>(Neo4jVertex.this, key, (V) getBaseVertex().getProperty(key)));
                }).iterator();
    }

    private boolean existsInNeo4j(final String key) {
        try {
            return this.getBaseVertex().hasProperty(key);
        } catch (IllegalStateException | NotFoundException ex) {
            // if vertex is removed before/after transaction close
            throw Element.Exceptions.elementAlreadyRemoved(Vertex.class, this.id());
        }
    }
}


text:
"""Support for KNX/IP covers."""
import voluptuous as vol

from homeassistant.components.cover import (
    ATTR_POSITION, ATTR_TILT_POSITION, PLATFORM_SCHEMA, SUPPORT_CLOSE,
    SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION,
    SUPPORT_STOP, CoverDevice)
from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_utc_time_change

CONF_MOVE_LONG_ADDRESS = 'move_long_address'
CONF_MOVE_SHORT_ADDRESS = 'move_short_address'
CONF_POSITION_ADDRESS = 'position_address'
CONF_POSITION_STATE_ADDRESS = 'position_state_address'
CONF_ANGLE_ADDRESS = 'angle_address'
CONF_ANGLE_STATE_ADDRESS = 'angle_state_address'
CONF_TRAVELLING_TIME_DOWN = 'travelling_time_down'
CONF_TRAVELLING_TIME_UP = 'travelling_time_up'
CONF_INVERT_POSITION = 'invert_position'
CONF_INVERT_ANGLE = 'invert_angle'

DEFAULT_TRAVEL_TIME = 25
DEFAULT_NAME = 'KNX Cover'
DEPENDENCIES = ['knx']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_MOVE_LONG_ADDRESS): cv.string,
    vol.Optional(CONF_MOVE_SHORT_ADDRESS): cv.string,
    vol.Optional(CONF_POSITION_ADDRESS): cv.string,
    vol.Optional(CONF_POSITION_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_ANGLE_ADDRESS): cv.string,
    vol.Optional(CONF_ANGLE_STATE_ADDRESS): cv.string,
    vol.Optional(CONF_TRAVELLING_TIME_DOWN, default=DEFAULT_TRAVEL_TIME):
        cv.positive_int,
    vol.Optional(CONF_TRAVELLING_TIME_UP, default=DEFAULT_TRAVEL_TIME):
        cv.positive_int,
    vol.Optional(CONF_INVERT_POSITION, default=False): cv.boolean,
    vol.Optional(CONF_INVERT_ANGLE, default=False): cv.boolean,
})

async def async_setup_platform(
        hass, config, async_add_entities, discovery_info=None):
    """Set up cover(s) for KNX platform."""
    if discovery_info is not None:
        async_add_entities_discovery(hass, discovery_info, async_add_entities)
    else:
        async_add_entities_config(hass, config, async_add_entities)

@callback
def async_add_entities_discovery(hass, discovery_info, async_add_entities):
    """Set up covers for KNX platform configured via xknx.yaml."""
    entities = []
    for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
        device = hass.data[DATA_KNX].xknx.devices[device_name]
        entities.append(KNXCover(device))
    async_add_entities(entities)

@callback
def async_add_entities_config(hass, config, async_add_entities):
    """Set up cover for KNX platform configured within platform."""
    import xknx
    cover = xknx.devices.Cover(
        hass.data[DATA_KNX].xknx,
        name=config.get(CONF_NAME),
        group_address_long=config.get(CONF_MOVE_LONG_ADDRESS),
        group_address_short=config.get(CONF_MOVE_SHORT_ADDRESS),
        group_address_position_state=config.get(
            CONF_POSITION_STATE_ADDRESS),
        group_address_angle=config.get(CONF_ANGLE_ADDRESS),
        group_address_angle_state=config.get(CONF_ANGLE_STATE_ADDRESS),
        group_address_position=config.get(CONF_POSITION_ADDRESS),
        travel_time_down=config.get(CONF_TRAVELLING_TIME_DOWN),
        travel_time_up=config.get(CONF_TRAVELLING_TIME_UP),
        invert_position=config.get(CONF_INVERT_POSITION),
        invert_angle=config.get(CONF_INVERT_ANGLE))

    hass.data[DATA_KNX].xknx.devices.add(cover)
    async_add_entities([KNXCover(cover)])

class KNXCover(CoverDevice):
    """Representation of a KNX cover."""

    def __init__(self, device):
        """Initialize the cover."""
        self.device = device
        self._unsubscribe_auto_updater = None

    @callback
    def async_register_callbacks(self):
        """Register callbacks to update hass after device was changed."""
        async def after_update_callback(device):
            """Call after device was updated."""
            await self.async_update_ha_state()
        self.device.register_device_updated_cb(after_update_callback)

    async def async_added_to_hass(self):
        """Store register state change callback."""
        self.async_register_callbacks()

    @property
    def name(self):
        """Return the name of the KNX device."""
        return self.device.name

    @property
    def available(self):
        """Return True if entity is available."""
        return self.hass.data[DATA_KNX].connected

    @property
    def should_poll(self):
        """No polling needed within KNX."""
        return False

    @property
    def supported_features(self):
        """Flag supported features."""
        supported_features = SUPPORT_OPEN | SUPPORT_CLOSE | \
            SUPPORT_SET_POSITION | SUPPORT_STOP
        if self.device.supports_angle:
            supported_features |= SUPPORT_SET_TILT_POSITION
        return supported_features

    @property
    def current_cover_position(self):
        """Return the current position of the cover."""
        return self.device.current_position()

    @property
    def is_closed(self):
        """Return if the cover is closed."""
        return self.device.is_closed()

    async def async_close_cover(self, **kwargs):
        """Close the cover."""
        if not self.device.is_closed():
            await self.device.set_down()
            self.start_auto_updater()

    async def async_open_cover(self, **kwargs):
        """Open the cover."""
        if not self.device.is_open():
            await self.device.set_up()
            self.start_auto_updater()

    async def async_set_cover_position(self, **kwargs):
        """Move the cover to a specific position."""
        if ATTR_POSITION in kwargs:
            position = kwargs[ATTR_POSITION]
            await self.device.set_position(position)
            self.start_auto_updater()

    async def async_stop_cover(self, **kwargs):
        """Stop the cover."""
        await self.device.stop()
        self.stop_auto_updater()

    @property
    def current_cover_tilt_position(self):
        """Return current tilt position of cover."""
        if not self.device.supports_angle:
            return None
        return self.device.current_angle()

    async def async_set_cover_tilt_position(self, **kwargs):
        """Move the cover tilt to a specific position."""
        if ATTR_TILT_POSITION in kwargs:
            tilt_position = kwargs[ATTR_TILT_POSITION]
            await self.device.set_angle(tilt_position)

    def start_auto_updater(self):
        """Start the autoupdater to update HASS while cover is moving."""
        if self._unsubscribe_auto_updater is None:
            self._unsubscribe_auto_updater = async_track_utc_time_change(
                self.hass, self.auto_updater_hook)

    def stop_auto_updater(self):
        """Stop the autoupdater."""
        if self._unsubscribe_auto_updater is not None:
            self._unsubscribe_auto_updater()
            self._unsubscribe_auto_updater = None

    @callback
    def auto_updater_hook(self, now):
        """Call for the autoupdater."""
        self.async_schedule_update_ha_state()
        if self.device.position_reached():
            self.stop_auto_updater()

        self.hass.add_job(self.device.auto_stop_if_necessary())


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Is it coffee time?</title>
<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAACJqckAAAAAAP///wBZeJYAJ01zAJHd6wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERERERERERERERERERERERERERERERERERREREERERERQiIiJBERERQlJSUlQRERFFJSUlJBEREUJSUlJURBERQiIiIiQUERFCREREJEQREUQAAABEERERFEREREERERERERERERERERExExExERERExExExERERERMRMRMRERH//wAA//8AAP//AADgfwAAwD8AAIAfAACAHwAAgAcAAIAXAACABwAAgB8AAMA/AAD//wAA7b8AANt/AADtvwAA" rel="icon" type="image/x-icon" />
<link rel=stylesheet href=//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css>

Is it coffee time?

  Why?
  | @maedox
  | GitHub


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>de.unibi.cebitec.bibiserv</groupId>
    <artifactId>JobProxy</artifactId>
    <version>0.1.0.beta.1.11</version>
    <packaging>pom</packaging>

    <repositories>
        <repository>
            <id>snapshot-repository.java.net</id>
            <name>Java.net Snapshot Repository for Maven</name>
            <url>https://maven.java.net/content/repositories/snapshots/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.4.1</version>
                <executions>
                    <execution>
                        <id>enforce-maven</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireMavenVersion>
                                    <version>3.2</version>
                                </requireMavenVersion>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <modules>
        <module>JobProxyModel</module>
        <module>JobProxyServer</module>
        <module>JobProxyChronos</module>
        <module>JobProxyLocal</module>
        <module>JobProxyServerCLI</module>
        <module>JobProxyDRMAA</module>
        <module>JobProxyKubernetes</module>
    </modules>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.21</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <name>JobProxy</name>
</project>


text:
namespace WebApiHypermediaExtensionsCore.Util.Repository
{
    public class Pagination
    {
        public Pagination()
        {
        }

        public Pagination(Pagination other)
        {
            PageSize = other.PageSize;
            PageOffset = other.PageOffset;
        }

        public int PageSize { get; set; }

        public int PageOffset { get; set; }

        public bool HasPagination()
        {
            return PageSize > 0;
        }

        public void DisablePagination()
        {
            PageSize = 0;
            PageOffset = 0;
        }
    }
}


text:
package com.sagui.ext.common.render.generic;

import java.io.IOException;

import com.sagui.ext.common.render.IComponentRender;
import com.sagui.ext.common.render.RenderException;
import com.sagui.ext.common.render.util.RenderWriter;
import com.sagui.model.FatuComponent;

public class FatuScriptPropertyRender<T extends FatuComponent> implements IComponentRender<T> {

    private final String scriptToRender;

    public FatuScriptPropertyRender(String scriptToRender) {
        this.scriptToRender = scriptToRender;
    }

    @Override
    public boolean render(T component, RenderWriter out) throws RenderException {
        try {
            out.tab().append(scriptToRender).ln();
        } catch (IOException e) {
            throw new RenderException(e);
        }
        return true;
    }

    @Override
    public void update(T component, RenderWriter out) throws RenderException {
        // TODO Auto-generated method stub

    }

}


text:
import os
import csv

from django.core.management.base import BaseCommand, CommandError
from geopy import geocoders
from optparse import make_option

from roaster.models import BusinessHours, Roaster, Roast, Cafe

IMPORT_TYPES = ('roasters', 'cafes',)

class Command(BaseCommand):
    args = "<filename>"
    help = """\
        Imports a list of roasters from a CSV."""

    option_list = BaseCommand.option_list + (
        make_option('--quiet', action='store_true', dest='quiet',
            default=False, help='Suppress all output except errors'),
        make_option('--import-type', choices=IMPORT_TYPES,
            dest='import_type', default='roasters',
            help='One of the following: %s' % (', '.join(IMPORT_TYPES),)),
        make_option('--geocode', action='store_true', dest='geocode',
            help='Geocode addresses')
    )

    cafe_fields = (
        'roaster',
        'name',
        'address',
        'phone',
        'url',
    )

    roaster_fields = (
        'name',
        'order_online',
        'cafe_on_site',
        'open_to_public',
        'address',
        'mon',
        'tue',
        'wed',
        'thu',
        'fri',
        'sat',
        'sun',
        'phone',
        'url',
        'description',
        'photo_url',
        'video_url',
        'video_embed',
        'roasts',
    )

    def uprint(self, msg):
        """
        Unbuffered print.
        """
        if not self.quiet:
            self.stdout.write("%s\n" % msg)
            self.stdout.flush()

    def import_cafe(self, reader):
        num_created = 0
        for row in reader:
            # Skip the first row
            name = row.get('name').strip()
            roaster = row.get('roaster').strip()
            if name and name != 'Cafe' and roaster and roaster != 'Roaster':
                cafe, created = Cafe.objects.get_or_create(name=name,
                        address=row.get('address'))

                if created:
                    self.uprint('Importing new cafe: %s' % name)
                    num_created += 1
                else:
                    self.uprint('Updating cafe: %s' % name)

                if self.geocode and created:
                    g = geocoders.GoogleV3()

                    try:
                        place, (lat, lng) = g.geocode(row.get('address'))
                        self.uprint('  %s,%s' % (lat, lng))
                        cafe.lat = lat
                        cafe.lng = lng
                    except Exception as e:
                        self.uprint('  Failed to geocode address!')

                cafe.address = row.get('address')
                cafe.phone = row.get('phone')
                cafe.url = row.get('url')
                cafe.active = True
                cafe.save()

                try:
                    # Associate roaster with the cafe
                    Roaster.objects.get(name=roaster).cafes.add(cafe)
                except Roaster.DoesNotExist:
                    self.uprint('Roaster %s does not exist!' % roaster)

        self.uprint('Imported %s new cafes.' % num_created)

    def import_roaster(self, reader):
        num_created = 0
        for row in reader:
            # Skip the first row
            name = row.get('name').strip()
            if name and name != 'Roaster':
                roaster, created = Roaster.objects.get_or_create(
                        name=name)

                if created:
                    self.uprint('Importing new roaster: %s' % name)
                    num_created += 1
                else:
                    self.uprint('Updating roaster: %s' % name)

                if self.geocode and created:
                    g = geocoders.GoogleV3()

                    try:
                        place, (lat, lng) = g.geocode(row.get('address'))
                        self.uprint('  %s,%s' % (lat, lng))
                        roaster.lat = lat
                        roaster.lng = lng
                    except Exception as e:
                        self.uprint('  Failed to geocode address!')

                online_only = row.get('address').lower() == 'online only'
                if not online_only:
                    roaster.address = row.get('address')
                else:
                    roaster.address = ''

                roaster.phone = row.get('phone')
                roaster.description = row.get('description')
                roaster.url = row.get('url').lower()
                roaster.photo_url = row.get('photo_url').lower()
                roaster.video_url = row.get('video_url').lower()
                roaster.online_only = online_only
                roaster.order_online = row.get('order_online') == '1'
                roaster.cafe_on_site = row.get('cafe_on_site') == '1'
                roaster.open_to_public = row.get('open_to_public').lower() == 'yes'
                roaster.active = True
                roaster.save()

                # Remove any existing hours
                BusinessHours.objects.filter(business=roaster).delete()

                # Hours
                hours = [
                    row.get('mon', '').split(','),
                    row.get('tue', '').split(','),
                    row.get('wed', '').split(','),
                    row.get('thu', '').split(','),
                    row.get('fri', '').split(','),
                    row.get('sat', '').split(','),
                    row.get('sun', '').split(','),
                ]

                # Create hours
                for d,h in enumerate(hours):
                    if len(h) is 2:
                        o = h[0]
                        c = h[1]

                        if len(o) < 3:
                            o = '%s:00' % o
                        if len(c) < 3:
                            c = '%s:00' % c

                        # Zulu time
                        tmp = c.split(':')
                        c = '%s:%s' % (int(tmp[0]) + 12, tmp[1])

                        BusinessHours.objects.create(weekday=d,
                                open=o, close=c, business=roaster)

                # Create roasts
                roasts = row.get('roasts', '')
                for r in roasts.split(','):
                    roast_name = r.strip()
                    if roast_name:
                        roast, roast_created = Roast.objects.get_or_create(
                                name=roast_name, roaster=roaster)

                        if roast_created:
                            self.uprint('  %s' % roast_name)

        self.uprint('Imported %s new roasters.' % num_created)

    def handle(self, *args, **options):
        self.quiet = options.get('quiet', False)
        self.geocode = options.get('geocode', False)
        self.import_type = options.get('import_type')

        try:
            path = os.path.abspath(args[0])

            if os.path.isfile(path):
                self.uprint('Importing from "%s"' % path)

                with open(path, 'rb') as f:
                    if self.import_type == 'cafes':
                        reader = csv.DictReader(f, fieldnames=self.cafe_fields)
                        self.import_cafe(reader)
                    else:
                        reader = csv.DictReader(f, fieldnames=self.roaster_fields)
                        self.import_roaster(reader)
            else:
                raise CommandError('The given path is not a valid file!')
        except IndexError:
            raise CommandError('The first argument must be a valid path to a CSV!')


text:
'use strict';

var pg = __dirname + '/__playground'
  , n4 = (process.version.indexOf('v0.4') === 0);

module.exports = function (t, a, d) {
	if (!n4) {
		d();
		return;
	}
	var outorg, errorg;
	outorg = process.stdout._writeOut;
	errorg = process.stderr._writeOut;
	process.stdout._writeOut = function (data) {};
	process.stderr._writeOut = function (data) {};

	t([
		'/wrong/path',
		pg + '/lib/context-error/module.js',
		pg + '/lib/evaluation-error.js',
		pg + '/lib/test-evaluation-error.js',
		pg + '/lib/no-tests.js',
		pg + '/lib/module.js'
	])(function () {
		process.stdout._writeOut = outorg;
		process.stderr._writeOut = errorg;
		a.ok(true);
		d();
	}, function (err) {
		process.stdout._writeOut = outorg;
		process.stderr._writeOut = errorg;
		d(err);
	}).end();
};


text:
package org.springframework.jms.core;

/**
 * @author Juergen Hoeller
 * @since 06.01.2005
 */
public class JmsTemplate102JtaTests extends JmsTemplate102Tests {

	protected boolean useTransactedSession() {
		return true;
	}

	protected boolean useTransactedTemplate() {
		return false;
	}

}


text:
class LearningObjectivesController < ApplicationController

  def new
    @objective = LearningObjective.new
  end

  def index
    @completed_objectives = LearningObjective.where("completed_at IS NOT NULL")
    @objectives = LearningObjective.where("completed_at IS NULL")
  end

  def create
    @objective = LearningObjective.create(objectives_params)
    redirect_to learning_objectives_path
  end

  def destroy

    @objective = LearningObjective.find(params[:id])
    @objective.destroy
    redirect_to learning_objectives_path
  end

  def complete
    @objective = LearningObjective.find(params[:id])
    @objective.update_attribute(:completed_at, Time.now)
    redirect_to learning_objectives_path
  end

  private

  def objectives_params
    params.require(:learning_objective).permit(:title, :description)
  end
end


text:
import { DocumentSessionAttachmentsBase } from "./DocumentSessionAttachmentsBase";
import { IAttachmentsSessionOperations } from "./IAttachmentsSessionOperations";
import { InMemoryDocumentSessionOperations } from "./InMemoryDocumentSessionOperations";
import { HeadAttachmentCommand } from "../Commands/HeadAttachmentCommand";
import { AttachmentResult } from "../Attachments";
import { GetAttachmentOperation } from "../Operations/Attachments/GetAttachmentOperation";

export class DocumentSessionAttachments
    extends DocumentSessionAttachmentsBase implements IAttachmentsSessionOperations {

    public constructor(session: InMemoryDocumentSessionOperations) {
        super(session);
    }

    public async exists(documentId: string, name: string): Promise<boolean> {
        const command = new HeadAttachmentCommand(documentId, name, null);
        this._session.incrementRequestCount();
        await this._requestExecutor.execute(command, this._sessionInfo);
        return !!command.result;
    }

    public async get(entity: object, name: string): Promise<AttachmentResult>;
    public async get(documentId: string, name: string): Promise<AttachmentResult>;
    public async get(
        idOrEntity: string | object,
        name: string): Promise<AttachmentResult> {
        let docId;
        if (typeof idOrEntity !== "string") {
            const document = this._session.documentsByEntity.get(idOrEntity);
            if (!document) {
                this._throwEntityNotInSessionOrMissingId(idOrEntity);
            }

            docId = document.id;
        } else {
            docId = idOrEntity;
        }

        const operation: GetAttachmentOperation =
            new GetAttachmentOperation(docId, name, "Document", null);
        this._session.incrementRequestCount();
        return await this._session.operations.send(operation, this._sessionInfo);
    }

    public async getRevision(documentId: string, name: string, changeVector: string): Promise<AttachmentResult> {
        const operation = new GetAttachmentOperation(documentId, name, "Revision", changeVector);
        this._session.incrementRequestCount();
        return this._session.operations.send(operation, this._sessionInfo);
    }
}


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

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"

     >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtCalc"
        android:orientation="vertical" >

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

            <Button
                android:id="@+id/button7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="7"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/button8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="8"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/button9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="9"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/buttonArti"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="+"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                 android:id="@+id/buttonKok"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="√"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
            <Button
                  android:id="@+id/buttonSin"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="sin"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                 android:id="@+id/buttonAsin"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="asin"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                android:id="@+id/buttonXN"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="@string/x_n"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                android:id="@+id/buttonEn"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="@string/e"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
            <Button
                 android:id="@+id/buttonBS"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="←"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

        </LinearLayout>

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

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="4"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/button5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="5"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/button6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="6"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/buttonEksi"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="-"
                android:textColor="#FFFFFF"
                android:textSize="20sp" ></Button>
                <Button
                 android:id="@+id/buttonKokUc"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="³√"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
                <Button
                android:id="@+id/buttonCos"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="cos"
                android:textColor="#FFFFFF"
                android:textSize="20sp"/>

                <Button
                 android:id="@+id/buttonAcos"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="acos"
                android:textColor="#FFFFFF"
                android:textSize="20sp"/>
                <Button
                android:id="@+id/buttonX"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="@string/x_two"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

                 <Button
                android:id="@+id/buttonLog2"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="@string/log"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

                 <Button
                android:id="@+id/buttonRound"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="round"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_above="@+id/linearLayout2"
            android:layout_alignLeft="@+id/linearLayout2"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="1"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="2"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="3"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/buttonCarpma"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="x"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
             <Button
                  android:id="@+id/buttonDot"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="."
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
             <Button
                android:id="@+id/buttonTan"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="tan"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

             <Button
                 android:id="@+id/buttonAtan"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="atan"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

             <Button
                 android:id="@+id/buttonE"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="e"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

           <Button
                android:id="@+id/buttonLog10"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="@string/log10"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_alignLeft="@+id/linearLayout1"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/button0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="0"
                android:textColor="#FFFFFF" />

            <Button
                android:id="@+id/buttonC"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="C"
                android:textColor="#961010" />

            <Button
                android:id="@+id/buttonEsit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_oval"
                android:text="="
                android:textColor="#961010"
                android:textSize="25sp" />

            <Button
                android:id="@+id/buttonBolme"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="/"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
            <Button
                android:id="@+id/buttonSign"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="+/-"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />
            <Button
                android:id="@+id/buttonCot"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="cot"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                  android:id="@+id/buttonAcot"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="acot"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                  android:id="@+id/buttonPi"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="PI"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

            <Button
                android:id="@+id/buttonLn"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/button_operation"
                android:text="@string/ln"
                android:textColor="#FFFFFF"
                android:textSize="20sp" />

        </LinearLayout>
    </LinearLayout>

    <EditText
        android:id="@+id/txtCalc"
        android:layout_width="fill_parent"
        android:layout_height="116dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:background="@drawable/edittext"
        android:editable="false"
        android:ems="10"
        android:gravity="right"
        android:inputType="none"
        android:singleLine="true"
        android:textColor="#FFFFFF"
        android:textSize="42sp"
        android:textStyle="normal"
        android:typeface="normal" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/edittext"
        android:editable="false"
        android:ems="10"
        android:gravity="right"
        android:inputType="none"
        android:textColor="#FFFFFF" >

        <requestFocus />
    </EditText>

</RelativeLayout>


text:
using UnityEngine;
using UnityEditor;
using NUnit.Framework;
using NSubstitute;
public class TestPlayerDirectionUpdate
{

    public playerController playerControllerScript;

    [Test]
    public void TestPlayerDirection()
    {

        //expected position and new position
        Vector3 expectedForwardVector = new Vector3(1.0f, 0, 0.0f);
        Vector3 actualForwardVector;

        //set up new object gameobject
        GameObject testObject = new GameObject();
        //add playercontroller to the object
        testObject.AddComponent<playerController>();
        //get the instance of the playercontroller
        playerControllerScript = testObject.GetComponent<playerController>();
        //set the player gameobject to our new gameobject
        GameObject playerObject = new GameObject();
        playerControllerScript.player = playerObject;
        playerObject.transform.forward = new Vector3(0, 0, 1.0f);
        Debug.Log(playerObject.transform.forward);
        //update the player position
        playerControllerScript.updateDirection(1.0f, 0.0f);
        //get the position
        actualForwardVector = playerObject.transform.forward;
        Debug.Log(playerObject.transform.forward);
        Assert.That(actualForwardVector.x, Is.EqualTo(expectedForwardVector.x).Within(0.1f), "Testing Player Position x: ");
      //  Assert.That(expectedPosition.z, Is.EqualTo(actualPosition.z).Within(0.1f), "Testing Player Position z: ");
      //  Assert.That(0, Is.EqualTo(actualPosition.y).Within(0.1f), "Testing Player Position Y (should always be 0): ");

    }
}


text:
import type { EmberPrecompileOptions } from 'ember-template-compiler';
import { compile } from 'ember-template-compiler';
import { EventDispatcher } from '@ember/-internals/views';
import type { Renderer } from '@ember/-internals/glimmer';
import Component from '@ember/component';
import { _resetRenderers } from '@ember/-internals/glimmer';
import type Resolver from '../test-resolver';
import { ModuleBasedResolver } from '../test-resolver';

import AbstractTestCase from './abstract';
import buildOwner from '../build-owner';
import { runAppend, runDestroy } from '../run';
import type { BootOptions, EngineInstanceOptions } from '@ember/engine/instance';
import type EngineInstance from '@ember/engine/instance';
import type { InternalFactory } from '@ember/-internals/owner';

export default class RouterNonApplicationTestCase extends AbstractTestCase {
  owner: EngineInstance;
  renderer: Renderer;
  element: HTMLElement;
  component: any;

  constructor(assert: QUnit['assert']) {
    super(assert);
    let bootOptions = this.getBootOptions();

    let owner = (this.owner = buildOwner({
      ownerType: 'engine',
      ownerOptions: this.getOwnerOptions(),
      resolver: this.getResolver(),
      bootOptions,
    }));

    owner.register('-view-registry:main', Object.create(null), { instantiate: false });
    owner.register('event_dispatcher:main', EventDispatcher);

    this.renderer = this.owner.lookup('renderer:-dom') as Renderer;
    this.element = document.querySelector('#qunit-fixture')!;
    this.component = null;
  }

  compile(templateString: string, options: Partial<EmberPrecompileOptions> = {}) {
    return compile(templateString, options);
  }

  getOwnerOptions(): EngineInstanceOptions | undefined {
    return undefined;
  }

  getBootOptions(): (BootOptions & { skipEventDispatcher?: boolean }) | undefined {
    return undefined;
  }

  get resolver(): Resolver {
    return (this.owner.__registry__.fallback as any).resolver;
  }

  getResolver() {
    return new ModuleBasedResolver();
  }

  add(specifier: string, factory: InternalFactory<object> | object) {
    this.resolver.add(specifier, factory);
  }

  addTemplate(
    templateName:
      | string
      | { specifier: string; source: unknown; namespace: unknown; moduleName: string },
    templateString: string
  ) {
    if (typeof templateName === 'string') {
      this.resolver.add(
        `template:${templateName}`,
        this.compile(templateString, {
          moduleName: templateName,
        })
      );
    } else {
      this.resolver.add(
        templateName,
        this.compile(templateString, {
          moduleName: templateName.moduleName,
        })
      );
    }
  }

  addComponent(name: string, { ComponentClass = null, template = null }) {
    if (ComponentClass) {
      this.resolver.add(`component:${name}`, ComponentClass);
    }

    if (typeof template === 'string') {
      this.resolver.add(
        `template:components/${name}`,
        this.compile(template, {
          moduleName: `components/${name}`,
        })
      );
    }
  }

  afterEach() {
    try {
      if (this.component) {
        runDestroy(this.component);
      }
      if (this.owner) {
        runDestroy(this.owner);
      }
    } finally {
      _resetRenderers();
    }
  }

  render(templateStr: string, context = {}) {
    let { owner } = this;

    owner.register(
      'template:-top-level',
      this.compile(templateStr, {
        moduleName: '-top-level',
      })
    );

    let attrs = Object.assign({}, context, {
      tagName: '',
      layoutName: '-top-level',
    });

    owner.register('component:-top-level', Component.extend(attrs));

    this.component = owner.lookup('component:-top-level');

    runAppend(this.component);
  }
}


text:
<?php
namespace Dashboard\Entity\Repository;

use Doctrine\ORM\EntityRepository;
/**
 *
 * @author user
 *
 */
class ProductsRepository extends EntityRepository
{
}

?>