text:
require File.dirname(__FILE__) + '/../spec_helper.rb'

def update_cache_columns_jobs
  Delayed::Job.where("handler LIKE '%update_cache_columns_for%'").count
end

describe ListedTaxon do
  elastic_models( Observation, Place )
  it "should be invalid when check list fields set on a non-check list" do
    list = List.make!
    check_list = CheckList.make!
    listed_taxon = ListedTaxon.new(:list => list, :taxon => Taxon.make!,
      :occurrence_status_level => ListedTaxon::OCCURRENCE_STATUS_LEVELS.keys.first)
    expect(listed_taxon).not_to be_valid
    listed_taxon.list = check_list
    expect(listed_taxon).to be_valid
  end

  describe "creation" do
    before(:each) do
      @taxon = Taxon.make!
      @first_observation = Observation.make!(taxon: @taxon, observed_on_string: 1.minute.ago.utc.to_s)
      @user = @first_observation.user
      @last_observation = Observation.make!(taxon: @taxon, user: @user, observed_on_string: Time.now.utc.to_s)
      @list = @user.life_list
      @listed_taxon = ListedTaxon.make!(taxon: @taxon, list: @list)
      @listed_taxon.reload
    end

    it "should set last observation" do
      expect(@listed_taxon.last_observation_id).to eq(@last_observation.id)
    end

    it "should set first observation" do
      expect(@listed_taxon.first_observation_id).to eq(@first_observation.id)
    end

    it "should set observations_count" do
      expect(@listed_taxon.observations_count).to eq(2)
    end

  end

  describe "creation for check lists" do
    before(:each) do
      @place = make_place_with_geom
      @check_list = @place.check_list
      expect(@check_list).to be_is_default
      @user = User.make!
      @user_check_list = @place.check_lists.create(:title => "Foo!", :user => @user, :source => Source.make!)
    end

    describe "cached columns" do
      before do
        @taxon = Taxon.make!(:rank => "species")
        @first_observation = make_research_grade_observation(:observed_on_string => "2009-01-03",
          :taxon => @taxon, :latitude => @place.latitude, :longitude => @place.longitude)
        @inbetween_observation = Observation.make!(:observed_on_string => "2009-02-02",
          :taxon => @taxon, :latitude => @place.latitude, :longitude => @place.longitude)
        @last_observation = make_research_grade_observation(:observed_on_string => "2009-03-05",
          :taxon => @taxon, :latitude => @place.latitude, :longitude => @place.longitude)
        expect(@first_observation.places).to include @place
        expect(@last_observation.places).to include @place
      end
      it "should set first observation to the first research grade observation added" do
        lt = without_delay { ListedTaxon.make!(:list => @check_list, :place => @place, :taxon => @taxon) }
        expect(lt.first_observation).to eq @first_observation
      end
      it "should set last observation to the last research grade observation observed" do
        lt = without_delay { ListedTaxon.make!(:list => @check_list, :place => @place, :taxon => @taxon) }
        expect(lt.last_observation).to eq @last_observation
      end
    end

    it "should make sure the user matches the check list user" do
      lt = @user_check_list.listed_taxa.build(:taxon => Taxon.make!, :user => @user)
      expect(lt).to be_valid
      lt = @user_check_list.listed_taxa.build(:taxon => Taxon.make!, :user => User.make!)
      expect(lt).not_to be_valid
    end

    it "should allow curators to add to owned check lists" do
      lt = @user_check_list.listed_taxa.build(:taxon => Taxon.make!, :user => make_curator)
      expect(lt).to be_valid
    end

    it "should inherit the check list's source" do
      lt = @user_check_list.listed_taxa.create(:taxon => Taxon.make!, :user => @user)
      expect(lt.source_id).to be(@user_check_list.source_id)
    end

    it "should set establishment_means to native if there is a native listing for a child place" do
      child_place = make_place_with_geom(:parent => @place)
      t = Taxon.make!
      child_place.check_list.add_taxon(t, :establishment_means => ListedTaxon::NATIVE)
      lt = @check_list.add_taxon(t)
      expect(lt.establishment_means).to eq(ListedTaxon::NATIVE)
    end

    it "should set establishment_means to introduced if there is a introduced listing for a parent place" do
      parent_place = make_place_with_geom
      place = make_place_with_geom(:parent => parent_place)
      t = Taxon.make!
      parent_place.check_list.add_taxon(t, :establishment_means => ListedTaxon::INTRODUCED)
      lt = place.check_list.add_taxon(t)
      expect(lt.establishment_means).to eq(ListedTaxon::INTRODUCED)
    end

    it "should log listed_taxon_alterations if listed_taxa has_atlas_or_complete_set? on create" do
      taxon = Taxon.make!
      AncestryDenormalizer.denormalize
      atlas_place = make_place_with_geom(admin_level: 0)
      atlas = Atlas.make!(user: @user, taxon: taxon, is_active: true)
      atlas_place_check_list = List.find(atlas_place.check_list_id)
      check_listed_taxon = atlas_place_check_list.add_taxon(taxon, options = {user_id: @user.id})
      expect(check_listed_taxon.has_atlas_or_complete_set?).to be true
      expect(ListedTaxonAlteration.where(
        taxon_id: taxon.id,
        user_id: @user.id,
        place_id: atlas_place.id,
        action: "listed"
      ).first).not_to be_blank
    end
  end

  describe "destroy" do
    it "should log listed_taxon_alterations if listed_taxa has_atlas_or_complete_set? on destroy" do
      taxon = Taxon.make!
      AncestryDenormalizer.denormalize
      atlas_place = make_place_with_geom(admin_level: 0)
      atlas_place_check_list = List.find(atlas_place.check_list_id)
      @user = User.make!
      check_listed_taxon = atlas_place_check_list.add_taxon(taxon, options = {user_id: @user.id})
      expect(check_listed_taxon.has_atlas_or_complete_set?).to be false
      @other_user = User.make!
      atlas = Atlas.make!(user: @other_user, taxon: taxon, is_active: true)
      expect(check_listed_taxon.has_atlas_or_complete_set?).to be true
      @other_user = User.make!
      check_listed_taxon.updater = @other_user
      check_listed_taxon.destroy
      expect(ListedTaxonAlteration.where(
        taxon_id: taxon.id,
        user_id: @other_user.id,
        place_id: atlas_place.id,
        action: "unlisted"
      ).first).not_to be_blank
    end
  end

  describe "check list auto removal" do
    before(:each) do
      @place = make_place_with_geom
      @check_list = @place.check_list
      expect(@check_list).to be_is_default
    end

    it "should work for vanilla" do
      lt = ListedTaxon.make!(:list => @check_list)
      expect(lt).to be_auto_removable_from_check_list
    end

    it "should not work if first observation" do
      lt = ListedTaxon.make!(:list => @check_list, :first_observation => Observation.make!)
      expect(lt).not_to be_auto_removable_from_check_list
    end

    it "should not work if user" do
      lt = ListedTaxon.make!(:list => @check_list, :user => User.make!)
      expect(lt).not_to be_auto_removable_from_check_list
    end

    it "should not work if taxon range" do
      lt = ListedTaxon.make!(:list => @check_list, :taxon_range => TaxonRange.make!)
      expect(lt).not_to be_auto_removable_from_check_list
    end

    it "should not work if source" do
      lt = ListedTaxon.make!(:list => @check_list, :source => Source.make!)
      expect(lt).not_to be_auto_removable_from_check_list
    end
  end

  describe "updating" do
    it "should set cache columns BEFORE validation" do
      lt = ListedTaxon.make!
      good_obs = Observation.make!(:user => lt.list.user, :taxon => lt.taxon)
      bad_obs = Observation.make!(:user => lt.list.user)
      lt.update_attributes(:first_observation => good_obs)
      expect(lt).to be_valid
      ListedTaxon.where(id: lt.id).update_all(first_observation_id: bad_obs.id)
      lt.reload
      expect(lt).to be_valid
      expect(lt.first_observation_id).to be == good_obs.id
    end

    it "should fail if occurrence_status set to absent and there is a confirming observation" do
      l = CheckList.make!
      t = Taxon.make!
      o = make_research_grade_observation(:latitude => l.place.latitude, :longitude => l.place.longitude, :taxon => t)
      lt = ListedTaxon.make!(:list => l, :taxon => t, :first_observation => o)
      expect(lt).to be_valid
      lt.occurrence_status_level = ListedTaxon::ABSENT
      expect(lt).not_to be_valid
      expect(lt.errors[:occurrence_status_level]).not_to be_blank
    end

    it "should not allow endemic taxa for continent-level places" do
      place = make_place_with_geom( admin_level: Place::CONTINENT_LEVEL )
      lt = ListedTaxon.make!( place: place, list: place.check_list )
      lt.establishment_means = ListedTaxon::ENDEMIC
      expect( lt ).not_to be_valid
      expect( lt.errors[:establishment_means] ).not_to be_blank
    end

    it "should not allow endemic taxa for continents" do
      place = make_place_with_geom( place_type: Place::CONTINENT )
      lt = ListedTaxon.make!( place: place, list: place.check_list )
      lt.establishment_means = ListedTaxon::ENDEMIC
      expect( lt ).not_to be_valid
      expect( lt.errors[:establishment_means] ).not_to be_blank
    end
  end

  describe "check list user removal" do
    before(:each) do
      @place = make_place_with_geom
      @check_list = @place.check_list
      expect(@check_list).to be_is_default
      @user = User.make!
    end

    it "should work for user who added" do
      lt = ListedTaxon.make!(:list => @check_list, :user => @user)
      expect(lt).to be_removable_by @user
    end

    it "should work for lists the user owns" do
      list = List.make!(:user => @user)
      lt = ListedTaxon.make!(:list => list)
      expect(lt).to be_removable_by @user
    end

    it "should not work if first observation" do
      lt = ListedTaxon.make!(:list => @check_list, :first_observation => Observation.make!)
      expect(lt).not_to be_removable_by @user
    end

    it "should not work if remover is not user" do
      lt = ListedTaxon.make!(:list => @check_list, :user => User.make!)
      expect(lt).not_to be_removable_by @user
    end

    it "should not work if taxon range" do
      lt = ListedTaxon.make!(:list => @check_list, :taxon_range => TaxonRange.make!)
      expect(lt).not_to be_removable_by @user
    end

    it "should not work if source" do
      lt = ListedTaxon.make!(:list => @check_list, :source => Source.make!)
      expect(lt).not_to be_removable_by @user
    end

    it "should work for admins" do
      lt = ListedTaxon.make!(:list => @check_list, :first_observation => Observation.make!)
      user = make_user_with_role(:admin)
      expect(user).to be_admin
      expect(lt).to be_removable_by user
    end

    it "should work if there's no source" do
      lt = ListedTaxon.make!(:list => @check_list)
      expect(lt.citation_object).to be_blank
      expect(lt).to be_removable_by @user
    end
  end

  describe "citation object" do
    it "should set occurrence_status to present if set"
  end

  describe "merge" do
    before(:each) do
      @keeper = ListedTaxon.make!
      @reject = ListedTaxon.make!
    end

    it "should destroy the reject" do
      @keeper.merge(@reject)
      expect(ListedTaxon.find_by_id(@reject.id)).to be_blank
    end

    it "should add comments from the reject to the keeper" do
      comment = Comment.make!(:parent => @reject)
      expect(@keeper.comments.count).to be(0)
      @keeper.merge(@reject)
      expect(@keeper.comments.count).to be(1)
    end

    it "should add attributes from the reject to the keeper" do
      @reject.update_attribute(:description, "this thing is dust")
      @keeper.merge(@reject)
      expect(@keeper.description).to eq "this thing is dust"
    end

    it "should not override attributes in the keeper" do
      @keeper.update_attribute(:description, "i will survive")
      @reject.update_attribute(:description, "i'm doomed!")
      @keeper.merge(@reject)
      expect(@keeper.description).to eq "i will survive"
    end
  end

  describe "merge_duplicates" do
    it "should keep the earliest listed taxon" do
      keeper = ListedTaxon.make!
      reject = ListedTaxon.make!(:list => keeper.list)
      ListedTaxon.where(id: reject.id).update_all(taxon_id: keeper.taxon_id)
      ListedTaxon.merge_duplicates
      expect(ListedTaxon.find_by_id(keeper.id)).not_to be_blank
      expect(ListedTaxon.find_by_id(reject.id)).to be_blank
    end

    it "should work for multiple duplicates" do
      keeper = ListedTaxon.make!
      rejects = []
      3.times do
        reject = ListedTaxon.make!(:list => keeper.list)
        ListedTaxon.where(id: reject.id).update_all(taxon_id: keeper.taxon_id)
        rejects << reject
      end
      ListedTaxon.merge_duplicates
      expect(ListedTaxon.find_by_id(keeper.id)).not_to be_blank
      rejects.each do |reject|
        expect(ListedTaxon.find_by_id(reject.id)).to be_blank
      end
    end
  end

  describe "cache_columns" do
    before(:each) do
      @place = make_place_with_geom(:name => "foo to the bar")
      @place.save_geom(GeoRuby::SimpleFeatures::MultiPolygon.from_ewkt("MULTIPOLYGON(((-122.247619628906 37.8547693305679,-122.284870147705 37.8490764953623,-122.299289703369 37.8909492165781,-122.250881195068 37.8970452004104,-122.239551544189 37.8719807055375,-122.247619628906 37.8547693305679)))"))
      @check_list = @place.check_list
      @taxon = Taxon.make!(:rank => Taxon::SPECIES)
    end

    it "should set first observation to obs of desc taxa" do
      subspecies = Taxon.make!(:rank => Taxon::SUBSPECIES, :parent => @taxon)
      o = make_research_grade_observation(:taxon => subspecies, :latitude => @place.latitude, :longitude => @place.longitude)
      lt = ListedTaxon.make!(:list => @check_list, :place => @place, :taxon => @taxon)
      without_delay do
        ListedTaxon.update_cache_columns_for(lt)
      end
      lt.reload
      expect(lt.first_observation_id).to eq o.id
    end
  end

  describe "validation for comprehensive check lists" do
    before(:each) do
      @parent = Taxon.make!(rank: Taxon::GENUS)
      @taxon = Taxon.make!(parent: @parent, rank: Taxon::SPECIES)
      @place = make_place_with_geom
      @check_list = CheckList.make!(:place => @place, :taxon => @parent, :comprehensive => true)
      @check_listed_taxon = @check_list.add_taxon(@taxon)
    end

    it "should fail if a comprehensive check list that doesn't contain this taxon exists for a parent taxon" do
      t = Taxon.make!(parent: @parent, rank: Taxon::SPECIES)
      expect(@check_list.taxon_ids).not_to include(t.id)
      lt = @place.check_list.add_taxon(t)
      expect(lt).not_to be_valid
      expect(lt.errors[:taxon_id]).not_to be_blank
    end

    it "should fail if a comprehensive check list that doesn't contain this taxon exists for a parent taxon in an ancestor place" do
      t = Taxon.make!(parent: @parent, rank: Taxon::SPECIES)
      expect(@check_list.taxon_ids).not_to include(t.id)
      p = make_place_with_geom(:parent => @place)
      lt = p.check_list.add_taxon(t)
      expect(lt).not_to be_valid
      expect(lt.errors[:taxon_id]).not_to be_blank
    end

    it "should pass if a comprehensive check lists that does contain this taxon exists for a parent taxon" do
      t = Taxon.make!(parent: @parent, rank: Taxon::SPECIES)
      clt = @check_list.add_taxon(t)
      expect(@check_list.taxon_ids).to include(t.id)
      lt = @place.check_list.add_taxon(t)
      expect(lt).to be_valid
    end

    it "should pass if a comprehensive check list that doesn't contain this taxon exists for a parent taxon and there is a confirming observation" do
      t = Taxon.make!(parent: @parent, rank: Taxon::SPECIES)
      o = make_research_grade_observation(:taxon => t, :latitude => @place.latitude, :longitude => @place.longitude)
      expect(@check_list.taxon_ids).not_to include(t.id)
      lt = @place.check_list.add_taxon(t, :first_observation => o)
      expect(lt).to be_valid
    end
  end

  describe "establishment means propagation" do
    let(:parent) { make_place_with_geom }
    let(:place) { make_place_with_geom(:parent => parent) }
    let(:child) { make_place_with_geom(:parent => place) }
    let(:taxon) { Taxon.make! }
    let(:parent_listed_taxon) { parent.check_list.add_taxon(taxon) }
    let(:place_listed_taxon) { place.check_list.add_taxon(taxon) }
    let(:child_listed_taxon) { child.check_list.add_taxon(taxon) }
    it "should bubble up for native" do
      expect(parent_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::NATIVE)
      parent_listed_taxon.reload
      expect(parent_listed_taxon.establishment_means).to eq(place_listed_taxon.establishment_means)
    end

    it "should bubble up for endemic" do
      expect(parent_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::ENDEMIC)
      parent_listed_taxon.reload
      expect(parent_listed_taxon.establishment_means).to eq(place_listed_taxon.establishment_means)
    end

    it "should not trickle down for native" do
      expect(child_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::NATIVE)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to be_blank
    end

    it "should trickle down for introduced" do
      expect(child_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::INTRODUCED)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to eq(place_listed_taxon.establishment_means)
    end

    it "should not bubble up for introduced" do
      expect(parent_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::INTRODUCED)
      parent_listed_taxon.reload
      expect(parent_listed_taxon.establishment_means).to be_blank
    end

    it "should not alter previous settings" do
      parent_listed_taxon.update_attributes(:establishment_means => ListedTaxon::INTRODUCED)
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::NATIVE)
      parent_listed_taxon.reload
      expect(parent_listed_taxon.establishment_means).to eq(ListedTaxon::INTRODUCED)
    end

    it "should not alter est means of other taxa" do
      new_parent_listed_taxon = parent.check_list.add_taxon(Taxon.make!)
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::NATIVE)
      new_parent_listed_taxon.reload
      expect(new_parent_listed_taxon.establishment_means).to be_blank
    end

    it "trickle down should be forceable" do
      expect(child_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::INTRODUCED)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to eq ListedTaxon::INTRODUCED
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::NATIVE)
      place_listed_taxon.trickle_down_establishment_means(:force => true)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to eq ListedTaxon::NATIVE
    end

    it "trickle down should be forceable based on force_trickle_down_establishment_means" do
      expect(child_listed_taxon.establishment_means).to be_blank
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::INTRODUCED)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to eq ListedTaxon::INTRODUCED
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::NATIVE, :force_trickle_down_establishment_means => true)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to eq ListedTaxon::NATIVE
    end

    it "trickle should not update listed taxa for other places" do
      sibling_place = make_place_with_geom(:parent => parent)
      sibling_lt = sibling_place.check_list.add_taxon(taxon, :establishment_means => ListedTaxon::NATIVE)
      expect(sibling_lt.establishment_means).to eq ListedTaxon::NATIVE
      place_listed_taxon.update_attributes(:establishment_means => ListedTaxon::INTRODUCED)
      place_listed_taxon.trickle_down_establishment_means(:force => true)
      child_listed_taxon.reload
      expect(child_listed_taxon.establishment_means).to eq ListedTaxon::INTRODUCED
      sibling_lt.reload
      expect(sibling_lt.establishment_means).to eq ListedTaxon::NATIVE
    end
  end

  describe "cache column setting for check lists" do
    before do
      without_delay do
        @place = make_place_with_geom
        @check_list = @place.check_list
      end
    end
    it "should be queued" do
      lt = ListedTaxon.make!(:list => @check_list)
      expect(Delayed::Job.where("handler LIKE '%ListedTaxon%update_cache_columns_for%\n- #{lt.id}\n'").exists?).to be true
    end

    it "should not be queued if there's an existing job" do
      lt = ListedTaxon.make!(:list => @check_list)
      expect(Delayed::Job.where("handler LIKE '%ListedTaxon%update_cache_columns_for%\n- #{lt.id}\n'").count).to eq(1)
      lt.update_attributes(:establishment_means => ListedTaxon::NATIVE)
      expect(Delayed::Job.where("handler LIKE '%ListedTaxon%update_cache_columns_for%\n- #{lt.id}\n'").count).to eq(1)
    end
  end

  describe "parent check list syncing" do
    before do
      without_delay do
        @parent = make_place_with_geom
        @place = make_place_with_geom(:parent => @parent)
        @check_list = @place.check_list
      end
    end
    it "should be queued" do
      lt = ListedTaxon.make!(:list => @check_list)
      expect(Delayed::Job.where("handler LIKE '%CheckList\n%id: ''#{@check_list.id}''\n%sync_with_parent%'").exists?).to be true
    end

    it "should not be queued if existing job" do
      lt = ListedTaxon.make!(:list => @check_list)
      expect(Delayed::Job.where("handler LIKE '%CheckList\n%id: ''#{@check_list.id}''\n%sync_with_parent%'").count).to eq(1)
      lt2 = ListedTaxon.make!(:list => @check_list)
      expect(Delayed::Job.where("handler LIKE '%CheckList\n%id: ''#{@check_list.id}''\n%sync_with_parent%'").count).to eq(1)
    end
  end

  describe "a listed taxon on a non checklist" do
    before do
      @taxon = Taxon.make!
      @list = List.make!
      @first_observation = Observation.make!(:taxon => @taxon)
      @user = @first_observation.user
      @last_observation = Observation.make!(:taxon => @taxon, :user => @user, :observed_on_string => 1.minute.ago.to_s)
      @listed_taxon = ListedTaxon.make!(:taxon => @taxon, :list => @list)
      @listed_taxon.reload
    end

    it "should not be a primary listing" do
      @listed_taxon.update_attributes(:primary_listing => true)
      expect(@listed_taxon).not_to be_primary_listing
    end
  end

  describe "primary_listing" do
    before(:each) do
      @taxon = Taxon.make!
      @check_list = CheckList.make!
      @check_list_two = CheckList.make!
      @check_list_two.place = @check_list.place
      @check_list_two.save
      @check_list_two.reload
      @first_observation = Observation.make!(:taxon => @taxon)
      @user = @first_observation.user
      @last_observation = Observation.make!(:taxon => @taxon, :user => @user, :observed_on_string => 1.minute.ago.to_s)
      @listed_taxon = ListedTaxon.make!(:taxon => @taxon, :list => @check_list)
      @listed_taxon.reload

      @first_observation_two = Observation.make!(:taxon => @taxon)
      @user_two = @first_observation_two.user
      @last_observation_two = Observation.make!(:taxon => @taxon, :user => @user_two, :observed_on_string => 1.minute.ago.to_s)
      @listed_taxon_two = ListedTaxon.make!(:taxon => @taxon, :list => @check_list_two)
      @listed_taxon_two.reload

    end

    it "should set as first as primary listing" do
      expect(@listed_taxon.primary_listing).to be(true)
    end
    it "should set second lt as primary listing = false" do
      expect(@listed_taxon_two.primary_listing).to be(false)
    end
    it "should override attributes (like establishment means) of the non-primary listed taxon" do
      expect(@listed_taxon.primary_listing).to be(true)
      @listed_taxon.update_attribute(:establishment_means, "introduced")
      @listed_taxon_two.reload
      expect(@listed_taxon_two.establishment_means).to eq("introduced")
    end
    it "should reassign the primary to the second taxon when the original primary is destroyed" do
      expect(@listed_taxon.primary_listing).to be(true)
      @listed_taxon.destroy
      @listed_taxon_two.reload
      expect(@listed_taxon_two.primary_listing).to be(true)
      @listed_taxon_two.destroy
    end
    it "should set each lt appropriately on update" do
      @listed_taxon_two.update_attribute(:primary_listing, true)
      expect(@listed_taxon_two.primary_listing).to be(true)
      @listed_taxon.reload
      expect(@listed_taxon.primary_listing).to be(false)
    end
  end

  describe "force_update_cache_columns" do
    before do
      @place = make_place_with_geom
      @check_list = CheckList.make!(:place => @place)
      @lt = ListedTaxon.make!(list: @check_list, place: @place, primary_listing: true, taxon: Taxon.make!(rank: Taxon::SPECIES))
      @observation = make_research_grade_observation(:latitude => @place.latitude, :longitude => @place.longitude, :taxon => @lt.taxon)
      expect(Observation.in_place(@place)).to include @observation
      ListedTaxon.where(id: @lt).update_all(
        first_observation_id: nil,
        last_observation_id: nil,
        observations_count: nil)
      Delayed::Job.delete_all
      expect(Delayed::Job.count).to eq 0
      @lt.reload
      expect(@lt.last_observation_id).to be_nil
    end

    it "should queue a job to update cache columns when not set" do
      @lt.save
      expect(update_cache_columns_jobs).to eq 1
      @lt.reload
      expect(@lt.last_observation_id).to be_nil
    end

    it "should not queue a job to update cache columns if a job already exists" do
      @lt.save
      expect(update_cache_columns_jobs).to eq 1
      @lt.reload
      @lt.save
      expect(update_cache_columns_jobs).to eq 1
    end

    it "should not queue a job to update cache columns if set" do
      Delayed::Job.delete_all
      @lt.force_update_cache_columns = true
      @lt.save
      expect(update_cache_columns_jobs).to eq 0
    end

    it "should force cache columns to be set" do
      Delayed::Job.delete_all
      @lt.force_update_cache_columns = true
      @lt.save
      expect(@lt.last_observation_id).to eq @observation.id
    end
  end
end


text:
package com.github.programmerr47.artec_test_task.api.parsers;

import com.github.programmerr47.artec_test_task.api.objects.RequestObject;

import java.util.List;

/**
 * Interface that describes parsing from some {@link RequestObject}
 * to entity of request.
 *
 * @author Michael Spitsin
 * @since 2014-09-13
 */
public interface ParserTo<Obj extends RequestObject, ObjectTag, ArrayTag> {
    ObjectTag parseFromObject(Obj requestObject);
    ArrayTag parseFromList(List<Obj> requestObjects);
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace tippingmedia\venti\bundles;

use craft\web\AssetBundle;
use craft\web\assets\cp\CpAsset;
use craft\web\assets\editentry\EditEntryAsset;

class EventListBundle extends AssetBundle
{
    public function init()
    {
        // define the path that your publishable resources live
        $this->sourcePath = '@tippingmedia/venti/resources';

        // define the dependencies
        $this->depends = [
            CpAsset::class,
            EditEntryAsset::class
        ];

        // define the relative path to CSS/JS files that should be registered with the page
        // when this asset bundle is registered
        $this->js = [
            'js/venti.min.js',
            'lib/fullcalendar/lib/moment.min.js',
            'lib/fullcalendar/lib/moment-php-map.js'
        ];

        $this->css = [
            'css/venti.css'
        ];

        parent::init();
    }
}


text:
/*---------------------------------------------------------------------------*\
 |  search.js                                                                |
\*---------------------------------------------------------------------------*/

import { v4 as uuidv4 } from 'uuid';
import store from '../store';

const setQuery = (query, uuid) => ({ type: 'search/setQuery', query, uuid });
const showResults = (results) => ({ type: 'search/showResults', results });
export const setSelected = (index) => ({ type: 'search/setSelected', index });
export const clearSearch = () => ({ type: 'search/clearSearch' });

const EASTER_EGGS = {
  porn: [
    'https://www.pornhub.com/',
  ],
  rickroll: [
    'https://spool.video/rick-astley/never-gonna-give-you-up',
  ],
  wordle: [
    'https://powerlanguage.co.uk/wordle/',
  ],
};

export const executeSearch = (query) => {
  return async (dispatch) => {
    if (!query) {
      dispatch(clearSearch());
      return;
    }
    const uuid = uuidv4();
    dispatch(setQuery(query, uuid));

    const normalizedQuery = query.normalize();
    if (normalizedQuery in EASTER_EGGS) {
      const webpage = EASTER_EGGS[normalizedQuery].choice();
      window.location.href = webpage;
    }

    const urlQueryString = new URLSearchParams(`q=${query}&uuid=${uuid}`);
    const url = `${process.env.REACT_APP_API}/v1/songs/search?${urlQueryString}`;
    const response = await fetch(url);
    if (response.status !== 200) {
      console.error(`GET ${url} returned ${response.status} status code`)
      dispatch(showResults([]));
      return;
    }
    const data = await response.json();
    if (data.metadata.uuid === store.getState().search.uuid) {
      dispatch(showResults(data.songs));
      recordQuery(query);
    }
  };
};

const recordQuery = (query) => {
  const uuid = uuidv4();
  const urlQueryString = new URLSearchParams(`uuid=${uuid}`);
  const url = `${process.env.REACT_APP_API}/v1/queries?${urlQueryString}`;
  const [method, body] = ['POST', new FormData()];
  body.append('q', query);
  fetch(url, { method, body })
    .catch(console.error);
};


text:
package com.zeppamobile.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.appengine.api.modules.ModulesService;
import com.google.appengine.api.modules.ModulesServiceFactory;

public class ModuleUtils {

	/**
	 * @constructor Private constructor as this is a Utility file
	 */
	private ModuleUtils() {
	}

	/**
	 * Make a URL pointing to the zeppa-api module to make http request
	 *
	 * @param methodName
	 *            for the request
	 * @return URL for request
	 * @throws MalformedURLException
	 * @throws UnsupportedEncodingException
	 */
	public static URL getZeppaModuleUrl(String moduleName, String methodName,
			Map<String, String> params) throws MalformedURLException, UnsupportedEncodingException {

		String paramString = null;

		/*
		 * Append arguments for GET request
		 */
		if (params != null && !params.isEmpty()) {
			StringBuilder paramsBuilder = new StringBuilder();
			paramsBuilder.append("?");
			Set<Entry<String,String>> keySet = params.entrySet();
			Iterator<Entry<String,String>> i = keySet.iterator();
			while (i.hasNext()) {
				Entry<String,String> entry = i.next();

				String key = entry.getKey();
				String param = entry.getValue();

				if (paramsBuilder.length() > 1) { //
					paramsBuilder.append("&");
				}
				paramsBuilder.append(key);
				paramsBuilder.append("=");

				paramsBuilder.append(param);
			}

			paramString = paramsBuilder.toString();
//			paramString.replaceAll(" ", "%20");
//			paramString = URLEncoder.encode(paramString,"UTF-8");
		}

		ModulesService modulesApi = ModulesServiceFactory.getModulesService();

		URL url = new URL("http://"
				+ modulesApi.getVersionHostname(moduleName, "v1") + "/"
				+ methodName + (paramString == null ? "" : paramString));

		return url;
	}

}


text:
{% include vendor/jquery-1.7.1.min.js %}
{% include vendor/underscore-min.js %}
{% include vendor/backbone-min.js %}
{% include vendor/js-yaml.min.js %}
{% include vendor/chrono.js %}
{% include vendor/marked.js %}
{% include vendor/base64.js %}
{% include vendor/github.js %}
{% include vendor/keymaster.js %}
{% include vendor/codemirror/codemirror.js %}
{% include vendor/codemirror/xml.js %}
{% include vendor/codemirror/markdown.js %}
{% include vendor/codemirror/gfm.js %}
{% include vendor/codemirror/javascript.js %}
{% include vendor/codemirror/css.js %}
{% include vendor/codemirror/clojure.js %}
{% include vendor/codemirror/textile.js %}
{% include vendor/codemirror/coffeescript.js %}
{% include vendor/codemirror/less.js %}
{% include vendor/codemirror/htmlmixed.js %}
{% include vendor/codemirror/rst.js %}
{% include vendor/codemirror/clike.js %}
{% include vendor/codemirror/ruby.js %}
{% include vendor/codemirror/yaml.js %}
{% include vendor/jquery.cookie.js %}

window.app = {
    config: {},
    models: {},
    views: {},
    routers: {},
    utils: {},
    templates: _($('script[name]')).reduce(function(memo, el) {
        memo[el.getAttribute('name')] = _(el.innerHTML).template();
        return memo;
    }, {}),
    state: {'repo': ''},
    instance: {}
};

window.args = _(window.app).toArray();

{% include util.js %}
{% include model.js %}
{% include routers/application.js %}
{% include views/application.js %}
{% include views/notification.js %}
{% include views/profile.js %}
{% include views/start.js %}
{% include views/header.js %}
{% include views/posts.js %}
{% include views/post.js %}

// Prevent exit when there are unsaved changes
window.onbeforeunload = function() {
  if (window.app.instance.mainView && window.app.instance.mainView.dirty)
    return "You have unsaved changes. Are you sure you want to leave?";
};

function confirmExit() {
  if (window.app.instance.mainView && window.app.instance.mainView.dirty)
    return confirm("You have unsaved changes. Are you sure you want to leave?");
  return true;
}

(function(config, models, views, routers, utils, templates) {
  $(function() {

    if (authenticate()) {
      loadApplication(function(err, data) {

        // Start the engines
        window.app.instance = new views.Application({ el: '#container', model: data }).render();
        if (err) return app.instance.notify('error', 'Error while loading data from Github. This might be a temporary issue. Please try again later.');

        // TODO: this is silly.
        if (window.location.href.match(/\.html$/)) return;

        // Initialize router
        window.router = new routers.Application({});

        // Start responding to routes
        Backbone.history.start();
      });
    }
  });
}).apply(this, window.args);


text:
Tic-tac-toe is a game for two players, X and O (in our case, we're using blue or red colors), who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game. Can you beat the computer?

## Usage

Play against the computer at [tic-tac-toe](https://billdevcode.github.io/projects/tic-tac-toe/index.html)

## Contributing

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

## License

MIT License


text:
<?php
namespace tests\codeception\unit\modules\redisman;
use tests\codeception\unit\fixtures\RedisFixts;
use Codeception\Util\Debug;

class AddGetTest extends \Codeception\TestCase\Test
{
    /**
     * @var \tests\codeception\unit\UnitTester
     */
    protected $tester;

    /**
     * @var \insolita\redisman\Redisman $module
     **/
    private $module;

    protected function setUp()
    {
        parent::setUp();
        $this->module=\Yii::$app->getModule('redisman');
        $this->module->setConnection('local',0);
    }

    protected function tearDown(){
        parent::tearDown();
    }

    public function testRedisKeysWork(){
        $conn=$this->module->getConnection();
        $conn->set('stest1','stest1val');
        $val=$conn->get('stest1');
        Debug::debug($val);
        $this->assertTrue($val=='stest1val');
        $conn->del('stest1');
        $val=$conn->get('stest1');
        $this->assertEmpty($val);

        $conn->executeCommand('RPUSH',['slist1','A']);
        $conn->rpush('slist1','B');
        $conn->rpush('slist1','C','D','E');
        $val=$conn->lrange('slist1',0,-1);
        $this->assertTrue(is_array($val));
        $this->assertTrue(count($val)==5);
        $this->assertTrue(in_array('B',$val));
        $conn->del('slist1');

        $vals=['k1','k2','k3'];
        $key='slist1';
        array_unshift($vals, $key);
        $conn->executeCommand('RPUSH',$vals);
        $val=$conn->lrange('slist1',0,-1);
        Debug::debug($val);
        $this->assertEquals($val,['k1','k2','k3']);
        $conn->del('slist1');

        $conn->hset('shash1','Gr1', 'd1');
        $conn->hset('shash1','Gr2', 'd2');
        $conn->hmset('shash1','Gr3', 'd3','Gr4', 'd4','Gr5', 'd5');

        $val=$conn->hgetall('shash1');
        Debug::debug($val);
        $this->assertTrue(in_array('d3',$val));
        $val=$conn->hget('shash1', 'Gr3');
        $this->assertTrue($val=='d3');
        Debug::debug($val);
        $conn->del('shash1');

        $conn->sadd('setik1','Gr1');
        $conn->executeCommand('SADD', ['setik1','Gr2']);
        $conn->sadd('setik1','Gr3','Gr4', 'Gr2');
        $conn->executeCommand('SADD', ['setik1','Gr6','Gr7','Gr5']);
        $val=$conn->smembers('setik1');
        Debug::debug($val);
        $this->assertTrue(is_array($val));
        $this->assertTrue(count($val)==7);
        $conn->del('setik1');

        $conn->zadd('zsetik1',1,'Gr1');
        $conn->zadd('zsetik1',4,'Gr2');
        $conn->zadd('zsetik1',2,'Gr3', 3, 'Gr4', 1,'Gr5', 2, 'Gr2');
        $val=$conn->zrange('zsetik1', 0,-1,'withscores');
        $conn->del('zsetik1');
        Debug::debug($val);

        $val=$conn->zrange('zaddik', 0,-1,'withscores');
        Debug::debug($val);

    }

     public function testFixturizer(){

         $fixter=new RedisFixts();
         $fixter->createFixtures();
         $this->module->setConnection('local',1);

         $this->assertEquals(1,$this->module->executeCommand('EXISTS',['tfx_string']));
         $this->assertEquals(1,$this->module->executeCommand('EXISTS',['tfx_hash']));
         $this->assertEquals(1,$this->module->executeCommand('EXISTS',['tfx_list']));
         $this->assertEquals(1,$this->module->executeCommand('EXISTS',['tfx_set']));
         $this->assertEquals(1,$this->module->executeCommand('EXISTS',['tfx_zset']));
         $this->assertEquals(-1,$this->module->executeCommand('TTL',['tfx_hash']));
         $this->assertNotEquals(-1,$this->module->executeCommand('TTL',['tfx_stringexp']));
         $this->assertNotEquals(-1,$this->module->executeCommand('TTL',['tfx_listexp']));

          $fixter->deleteFixtures();

         $this->assertEquals(0,$this->module->executeCommand('EXISTS',['tfx_string']));
         $this->assertEquals(0,$this->module->executeCommand('EXISTS',['tfx_hash']));
         $this->assertEquals(0,$this->module->executeCommand('EXISTS',['tfx_list']));
         $this->assertEquals(0,$this->module->executeCommand('EXISTS',['tfx_set']));
         $this->assertEquals(0,$this->module->executeCommand('EXISTS',['tfx_zset']));
     }

     public function testDiffer(){
         $arr1=['item1','item2','item3','item4'];
         $arr2=['item6','item2','item4','item5','item7','item8'];
         $arr3=['item6','item2','item8'];
         Debug::debug(array_diff_assoc($arr1,$arr2));
         Debug::debug(array_diff_assoc($arr2,$arr1));
         Debug::debug(array_diff_assoc($arr2,$arr3));
         Debug::debug(array_diff_assoc($arr3,$arr2));
     }
}


text:
		<!-- BaseVizXY Defaults -->
		<defaultValue property="measureX">{"fieldType":"position","fieldPosition":0}</defaultValue>
		<defaultValue property="measureY">{"fieldType":"position","fieldPosition":1}</defaultValue>
		<defaultValue property="maxX">0</defaultValue>
		<defaultValue property="maxY">0</defaultValue>
		<defaultValue property="minX">0</defaultValue>
		<defaultValue property="minY">0</defaultValue>
		<!-- End of BaseVizXY Defaults -->


text:
<?php

namespace RcmTest\Acl;

use Rcm\Acl\ResourceProvider;
use Rcm\Entity\Domain;
use Rcm\Entity\Page;
use Rcm\Entity\Site;

require_once __DIR__ . '/../../../autoload.php';

class ResourceProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var
     */
    protected $config;

    /**
     * Setup config for tests
     *
     * @return void
     */
    public function setup()
    {
        $this->config = $this->getConfig();
    }

    /**
     * Get Main Config Array
     *
     * @return array
     */
    protected function getConfig()
    {
        return [
            'sites' => [
                'resourceId' => 'sites',
                'parentResourceId' => null,
                'privileges' => [
                    'read',
                    'edit',
                    'create',
                    'delete',
                    'theme',
                    'admin',
                ],
                'name' => 'sites',
                'description' => 'Global resource for sites',
            ],
            'pages' => [
                'resourceId' => 'pages',
                'parentResourceId' => null,
                'privileges' => [
                    'read',
                    'edit',
                    'create',
                    'delete',
                    'copy',
                    'approve',
                    'layout',
                ],
                'name' => 'pages',
                'description' => 'Global resource for pages',
            ],
        ];
    }

    /**
     * Get resource provider with mocks
     *
     * @param bool $skipSite Skip Site Mock setup
     *
     * @return ResourceProvider
     */
    protected function getProviderWithMocks($skipSite = false)
    {
        $mockReturn = [];

        $currdomain = new Domain();
        $currdomain->setDomainName('curr.reliv.com');

        $currpage = new Page();
        $currpage->setName('curr-page');

        $currsite = new Site();
        $currsite->setDomain($currdomain);
        $currsite->setSiteId(1);
        $currsite->addPage($currpage);

        if (!$skipSite) {
            $domain = new Domain();
            $domain->setDomainName('test.reliv.com');

            $page = new Page();
            $page->setName('test-page');

            $site = new Site();
            $site->setDomain($domain);
            $site->setSiteId(10);
            $site->addPage($page);
            $mockReturn[] = $site;
        }

        $mockSiteRepo = $this->getMockBuilder('\Rcm\Repository\Site')
            ->disableOriginalConstructor()
            ->getMock();

        $mockSiteRepo->expects($this->any())
            ->method('getSites')
            ->will($this->returnValue($mockReturn));

        /** @var \Rcm\Repository\Site $mockSiteRepo */
        /** @var \Rcm\Service\PluginManager $mockPluginManager */
        return new ResourceProvider(
            $this->config,
            $mockSiteRepo,
            $currsite
        );
    }

    /**
     * Test Get Resources Method With Sites And Pages
     *
     * @return void
     * @covers \Rcm\Acl\ResourceProvider::getResources
     * @covers \Rcm\Acl\ResourceProvider::getSiteResources
     * @covers \Rcm\Acl\ResourceProvider::getPageResources
     */
    public function testGetResourcesWithSites()
    {
        $siteExpected = [
            'sites.1.pages.n.curr-page' =>
                [
                    'resourceId' => 'sites.1.pages.n.curr-page',
                    'parentResourceId' => 'sites.1.pages',
                    'privileges' =>
                        [
                            0 => 'read',
                            1 => 'edit',
                            2 => 'create',
                            3 => 'delete',
                            4 => 'copy',
                            5 => 'approve',
                            6 => 'layout',
                        ],
                        'name' => 'curr.reliv.com - pages - curr-page',
                        'description' => 'Global resource for pages',
                ],
                'sites.1' =>
                [
                    'resourceId' => 'sites.1',
                    'parentResourceId' => 'sites',
                    'privileges' =>
                        [
                            0 => 'read',
                            1 => 'edit',
                            2 => 'create',
                            3 => 'delete',
                            4 => 'theme',
                            5 => 'admin',
                        ],
                        'name' => 'curr.reliv.com',
                        'description' => 'Global resource for sites',
                ],
                'sites.1.pages' =>
                [
                    'resourceId' => 'sites.1.pages',
                    'parentResourceId' => 'sites.1',
                    'privileges' =>
                        [
                            0 => 'read',
                            1 => 'edit',
                            2 => 'create',
                            3 => 'delete',
                            4 => 'copy',
                            5 => 'approve',
                            6 => 'layout',
                        ],
                        'name' => 'curr.reliv.com - pages',
                        'description' => 'Global resource for pages',
                ],
                'sites' =>
                [
                    'resourceId' => 'sites',
                    'parentResourceId' => null,
                    'privileges' =>
                        [
                            0 => 'read',
                            1 => 'edit',
                            2 => 'create',
                            3 => 'delete',
                            4 => 'theme',
                            5 => 'admin',
                        ],
                        'name' => 'sites',
                        'description' => 'Global resource for sites',
                ],
                'pages' =>
                [
                    'resourceId' => 'pages',
                    'parentResourceId' => null,
                    'privileges' =>
                        [
                            0 => 'read',
                            1 => 'edit',
                            2 => 'create',
                            3 => 'delete',
                            4 => 'copy',
                            5 => 'approve',
                            6 => 'layout',
                        ],
                        'name' => 'pages',
                        'description' => 'Global resource for pages',
                ],
        ];

        $expected = array_merge($siteExpected, $this->config);

        $resourceProvider = $this->getProviderWithMocks();

        $return = $resourceProvider->getResources();

        foreach ($expected as $key => $expect) {
            $this->assertTrue(array_key_exists($key, $return));
        }
    }

    /**
     * Test Get Resource with resource defined in config
     *
     * @return void
     * @covers \Rcm\Acl\ResourceProvider::getResource
     */
    public function testGetResourceInConfig()
    {
        $resourceProvider = $this->getProviderWithMocks(true);

        $sitesResource = $resourceProvider->getResource('sites');
        $pagesResource = $resourceProvider->getResource('pages');

        $this->assertEquals($this->config['sites'], $sitesResource);
        $this->assertEquals($this->config['pages'], $pagesResource);
    }

    /**
     * Test Get Resource using dynamic site
     *
     * @return void
     * @covers \Rcm\Acl\ResourceProvider::getResource
     * @covers \Rcm\Acl\ResourceProvider::dynamicResourceMapper
     * @covers \Rcm\Acl\ResourceProvider::siteResourceMapper
     */
    public function testGetResourceForSite()
    {
        $expected = [
            'resourceId' => 'sites.10',
            'parentResourceId' => 'sites',
            'privileges' => [
                'read',
                'edit',
                'create',
                'delete',
                'theme',
                'admin',
            ],
            'name' => 'sites',
            'description' => 'Global resource for sites',
        ];

        $resourceProvider = $this->getProviderWithMocks();

        $siteResource = $resourceProvider->getResource('sites.10');

        $this->assertEquals($expected, $siteResource);
    }

    /**
     * Test Get Resource using dynamic site
     *
     * @return void
     * @covers \Rcm\Acl\ResourceProvider::getResource
     * @covers \Rcm\Acl\ResourceProvider::dynamicResourceMapper
     * @covers \Rcm\Acl\ResourceProvider::pageResourceMapper
     */
    public function testGetResourceForPage()
    {
        $expected = [
            'resourceId' => 'sites.10.pages.n.test-page',
            'parentResourceId' => 'sites.10.pages',
            'privileges' => [
                'read',
                'edit',
                'create',
                'delete',
                'copy',
                'approve',
                'layout',
            ],
            'name' => 'pages',
            'description' => 'Global resource for pages',
        ];

        $resourceProvider = $this->getProviderWithMocks();

        $siteResource = $resourceProvider->getResource(
            'sites.10.pages.n.test-page'
        );

        $this->assertEquals($expected, $siteResource);
    }

    /**
     * Test Get Resource Resource Not Found
     *
     * @return void
     * @covers \Rcm\Acl\ResourceProvider::getResource
     * @covers \Rcm\Acl\ResourceProvider::dynamicResourceMapper
     * @covers \Rcm\Acl\ResourceProvider::siteResourceMapper
     * @covers \Rcm\Acl\ResourceProvider::pageResourceMapper
     */
    public function testGetResourceNoMatch()
    {
        $resourceProvider = $this->getProviderWithMocks();

        $siteResource = $resourceProvider->getResource('Does.Not.Match');

        $this->assertNull($siteResource);
    }

    /**
     * Test Set Provider Id
     *
     * @return void
     * @covers \Rcm\Acl\ResourceProvider::setProviderId
     */
    public function testSetProviderId()
    {
        $expected = 'Rcm\Acl\ResourceProvider';

        $resourceProvider = $this->getProviderWithMocks();

        $reflectedClass = new \ReflectionClass(
            get_class($resourceProvider)
        );

        $property = $reflectedClass->getProperty('providerId');
        $property->setAccessible(true);

        $resourceProvider->setProviderId('Does.Not.Match');

        $providerId = $property->getValue($resourceProvider);

        $this->assertEquals($expected, $providerId);
    }
}


text:
var express = require('express');
var router = express.Router();
var isAuthenticated = require('../server.js').isAuthenticated;

var search_documents = require('../controllers/documents/search');
var search_documents_by_user = require('../controllers/documents/search_by_user');
var search_documents_by_course = require('../controllers/documents/search_by_course');
var search_members = require('../controllers/members/search');
var search_members_by_course = require('../controllers/members/search_by_course');
var search_members_by_university = require('../controllers/members/search_by_university');
var search_members_by_institute = require('../controllers/members/search_by_institute');
var search_members_by_working_group = require('../controllers/members/search_by_working_group');
var search_users = require('../controllers/users/search');
var search_users_by_university = require('../controllers/users/search_by_university');
var search_users_by_institute = require('../controllers/users/search_by_institute');
var search_universities = require('../controllers/universities/search');
var search_institutes = require('../controllers/institutes/search');
var search_institutes_by_university = require('../controllers/institutes/search_by_university');
var search_working_groups = require('../controllers/working_groups/search');
var search_working_groups_by_institute = require('../controllers/working_groups/search_by_institute');
var search_courses = require('../controllers/courses/search');
var search_courses_by_institute = require('../controllers/courses/search_by_institute');

// SEARCH DOCUMENTS (ONLY MEMBERS)
router.post('/search/documents', isAuthenticated, search_documents.request);

// SEARCH DOCUMENTS BY USER (ONLY MEMBERS)
router.post('/search/users/:user_id/documents', isAuthenticated, search_documents_by_user.request);

// SEARCH DOCUMENTS BY COURSE (ONLY MEMBERS)
router.post('/search/courses/:course_id/documents', isAuthenticated, search_documents_by_course.request);

// SEARCH MEMBERS
router.post('/search/members', isAuthenticated, search_members.request);

// SEARCH MEMBERS BY COURSE (PUBLIC AND MEMBERS)
router.post('/search/courses/:course_id/members', isAuthenticated, search_members_by_course.request);

// SEARCH MEMBERS BY UNIVERSITY (ADMINS)
router.post('/search/universities/:university_id/members', isAuthenticated, search_members_by_university.request);

// SEARCH MEMBERS BY INSTITUTE (ADMINS)
router.post('/search/institutes/:institute_id/members', isAuthenticated, search_members_by_institute.request);

// SEARCH MEMBERS BY WORKING GROUP (ADMINS)
router.post('/search/working_groups/:working_group_id/members', isAuthenticated, search_members_by_working_group.request);

// SEARCH USERS (MEMBERS)
router.post('/search/users', isAuthenticated, search_users.request);

// SEARCH USERS BY UNIVERSITY (ADMINS)
router.post('/search/universities/:university_id/users', isAuthenticated, search_users_by_university.request);

// SEARCH USERS BY INSTITUTE (ADMINS)
router.post('/search/institutes/:institute_id/users', isAuthenticated, search_users_by_institute.request);

// SEARCH UNIVERSITIES
router.post('/search/universities', search_universities.request);

// SEARCH INSTITUTES
router.post('/search/institutes', search_institutes.request);

// SEARCH INSTITUTES BY UNIVERSITY
router.post('/search/universities/:university_id/institutes', search_institutes_by_university.request);

// SEARCH WORKING GROUPS
router.post('/search/working_groups', search_working_groups.request);

// SEARCH WORKING GROUPS BY INSTITUTE
router.post('/search/institutes/:institute_id/working_groups', search_working_groups_by_institute.request);

// SEARCH COURSES
router.post('/search/courses', search_courses.request);

// SEARCH COURSES BY INSTITUTE
router.post('/search/institutes/:institute_id/courses', search_courses_by_institute.request);

module.exports = router;


text:
<?php
/**
 * @file
 * @author  Lightly Salted Software Ltd
 * @date    March 2015
 */

namespace LSS\Schema\Table\Column;

use LSS\Schema\Table\Column;

/**
 */
class TextColumn extends Column
{
    /** @var string  */
    private $size = ''; // tiny, medium, '' etc

    public function __construct($name, $description = '', $allowNull = false, $size = '')
    {
        $this->size = $size;
        parent::__construct($name, $description, $allowNull);
    }

    public function getSQLType()
    {
        return $this->size . 'text';
    }

    public function getSQLDefault()
    {
        if ($this->isAllowedNull()) {
            return 'default null';
        }
        return 'default \'\'';
    }

    /**
     * @return string
     */
    public function getSize()
    {
        return $this->size;
    }
}


text:
@{
    GUID = "4ae9fd46-338a-459c-8186-07f910774cb8"
    Author = "Microsoft Corporation"
    CompanyName = "Microsoft Corporation"
    Copyright = "(C) Microsoft Corporation. All rights reserved."
    HelpInfoUri = "http://go.microsoft.com/fwlink/?linkid=392040"
    ModuleVersion = "1.0.0.1"
    PowerShellVersion = "3.0"
    ClrVersion = "4.0"
    RootModule = "Microsoft.PowerShell.PackageManagement.dll"
	Description = 'PackageManagement (a.k.a. OneGet) is a new way to discover and install software packages from around the web.
 It is a manager or multiplexor of existing package managers (also called package providers) that unifies Windows package management with a single Windows PowerShell interface. With PackageManagement, you can do the following.
  - Manage a list of software repositories in which packages can be searched, acquired and installed
  - Discover software packages
  - Seamlessly install, uninstall, and inventory packages from one or more software repositories'

    CmdletsToExport = @(
        'Find-Package',
        'Get-Package',
        'Get-PackageProvider',
        'Get-PackageSource',
        'Install-Package',
        'Import-PackageProvider'
        'Find-PackageProvider'
        'Install-PackageProvider'
        'Register-PackageSource',
        'Set-PackageSource',
        'Unregister-PackageSource',
        'Uninstall-Package'
        'Save-Package'
	)

	FormatsToProcess  = @('PackageManagement.format.ps1xml')

	PrivateData = @{
        PSData = @{
            Tags = @('PackageManagement')
            ProjectUri = 'https://oneget.org'
        }
    }
}


text:
package org.apache.camel.component.azure.blob;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import com.microsoft.azure.storage.AccessCondition;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.BlobListingDetails;
import com.microsoft.azure.storage.blob.BlockEntry;
import com.microsoft.azure.storage.blob.BlockListingFilter;
import com.microsoft.azure.storage.blob.CloudAppendBlob;
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.microsoft.azure.storage.blob.CloudPageBlob;
import com.microsoft.azure.storage.blob.ListBlobItem;
import com.microsoft.azure.storage.blob.PageRange;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.component.azure.common.ExchangeUtil;
import org.apache.camel.impl.DefaultProducer;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Producer which sends messages to the Azure Storage Blob Service
 */
public class BlobServiceProducer extends DefaultProducer {

    private static final Logger LOG = LoggerFactory.getLogger(BlobServiceProducer.class);

    public BlobServiceProducer(final Endpoint endpoint) {
        super(endpoint);
    }

    @Override
    public void process(final Exchange exchange) throws Exception {
        BlobServiceOperations operation = determineOperation(exchange);
        if (ObjectHelper.isEmpty(operation)) {
            operation = BlobServiceOperations.listBlobs;
        } else {
            switch (operation) {
            case getBlob:
                getBlob(exchange);
                break;
            case deleteBlob:
                deleteBlob(exchange);
                break;
            case listBlobs:
                listBlobs(exchange);
                break;
            case updateBlockBlob:
                updateBlockBlob(exchange);
                break;
            case uploadBlobBlocks:
                uploadBlobBlocks(exchange);
                break;
            case commitBlobBlockList:
                commitBlobBlockList(exchange);
                break;
            case getBlobBlockList:
                getBlobBlockList(exchange);
                break;
            case createAppendBlob:
                createAppendBlob(exchange);
                break;
            case updateAppendBlob:
                updateAppendBlob(exchange);
                break;
            case createPageBlob:
                createPageBlob(exchange);
                break;
            case updatePageBlob:
                uploadPageBlob(exchange);
                break;
            case resizePageBlob:
                resizePageBlob(exchange);
                break;
            case clearPageBlob:
                clearPageBlob(exchange);
                break;
            case getPageBlobRanges:
                getPageBlobRanges(exchange);
                break;
            default:
                throw new IllegalArgumentException("Unsupported operation");
            }
        }
    }

    private void listBlobs(Exchange exchange) throws Exception {
        CloudBlobContainer client = BlobServiceUtil.createBlobContainerClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        LOG.trace("Getting the blob list from the container [{}] from exchange [{}]...",
                  getConfiguration().getContainerName(), exchange);
        BlobServiceConfiguration cfg = getConfiguration();
        @SuppressWarnings("unchecked")
        EnumSet<BlobListingDetails> details =
            (EnumSet<BlobListingDetails>)exchange.getIn().getHeader(BlobServiceConstants.BLOB_LISTING_DETAILS);
        Iterable<ListBlobItem> items =
            client.listBlobs(cfg.getBlobPrefix(), cfg.isUseFlatListing(),
                             details, opts.getRequestOpts(), opts.getOpContext());
        ExchangeUtil.getMessageForResponse(exchange).setBody(items);
    }

    private void updateBlockBlob(Exchange exchange) throws Exception {
        CloudBlockBlob client = BlobServiceUtil.createBlockBlobClient(getConfiguration());
        configureCloudBlobForWrite(client);
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);

        InputStream inputStream = getInputStreamFromExchange(exchange);

        LOG.trace("Putting a block blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        try {
            client.upload(inputStream, -1,
                          opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        } finally {
            closeInputStreamIfNeeded(inputStream);
        }
    }

    private void uploadBlobBlocks(Exchange exchange) throws Exception {
        Object object = exchange.getIn().getMandatoryBody();

        List<BlobBlock> blobBlocks = null;
        if (object instanceof List) {
            blobBlocks = (List<BlobBlock>)blobBlocks;
        } else if (object instanceof BlobBlock) {
            blobBlocks = Collections.singletonList((BlobBlock)object);
        }
        if (blobBlocks == null || blobBlocks.isEmpty()) {
            throw new IllegalArgumentException("Illegal storageBlocks payload");
        }

        CloudBlockBlob client = BlobServiceUtil.createBlockBlobClient(getConfiguration());
        configureCloudBlobForWrite(client);
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);

        LOG.trace("Putting a blob [{}] from blocks from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        List<BlockEntry> blockEntries = new LinkedList<BlockEntry>();
        for (BlobBlock blobBlock : blobBlocks) {
            blockEntries.add(blobBlock.getBlockEntry());
            client.uploadBlock(blobBlock.getBlockEntry().getId(), blobBlock.getBlockStream(), -1,
                               opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        }
        Boolean commitBlockListLater = exchange.getIn().getHeader(BlobServiceConstants.COMMIT_BLOCK_LIST_LATER,
                                                                  Boolean.class);
        if (Boolean.TRUE != commitBlockListLater) {
            client.commitBlockList(blockEntries,
                                   opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        }
    }

    private void commitBlobBlockList(Exchange exchange) throws Exception {
        Object object = exchange.getIn().getMandatoryBody();

        List<BlockEntry> blockEntries = null;
        if (object instanceof List) {
            blockEntries = (List<BlockEntry>)blockEntries;
        } else if (object instanceof BlockEntry) {
            blockEntries = Collections.singletonList((BlockEntry)object);
        }
        if (blockEntries == null || blockEntries.isEmpty()) {
            throw new IllegalArgumentException("Illegal commit block list payload");
        }

        CloudBlockBlob client = BlobServiceUtil.createBlockBlobClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);

        LOG.trace("Putting a blob [{}] block list from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        client.commitBlockList(blockEntries,
                               opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
    }

    private void getBlob(Exchange exchange) throws Exception {
        BlobServiceUtil.getBlob(exchange, getConfiguration());
    }

    private void deleteBlob(Exchange exchange) throws Exception {
        switch (getConfiguration().getBlobType()) {
        case blockblob:
            deleteBlockBlob(exchange);
            break;
        case appendblob:
            deleteAppendBlob(exchange);
            break;
        case pageblob:
            deletePageBlob(exchange);
            break;
        default:
            throw new IllegalArgumentException("Unsupported blob type");
        }
    }

    private void getBlobBlockList(Exchange exchange) throws Exception {
        CloudBlockBlob client = BlobServiceUtil.createBlockBlobClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        LOG.trace("Getting the blob block list [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        BlockListingFilter filter = exchange.getIn().getBody(BlockListingFilter.class);
        if (filter == null) {
            filter = BlockListingFilter.COMMITTED;
        }
        List<BlockEntry> blockEntries =
            client.downloadBlockList(filter, opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        ExchangeUtil.getMessageForResponse(exchange).setBody(blockEntries);
    }

    private void deleteBlockBlob(Exchange exchange) throws Exception {
        CloudBlockBlob client = BlobServiceUtil.createBlockBlobClient(getConfiguration());
        doDeleteBlock(client, exchange);
    }

    private void createAppendBlob(Exchange exchange) throws Exception {
        CloudAppendBlob client = BlobServiceUtil.createAppendBlobClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        if (opts.getAccessCond() == null) {
            // Default: do not reset the blob content if the blob already exists
            opts.setAccessCond(AccessCondition.generateIfNotExistsCondition());
        }
        doCreateAppendBlob(client, opts, exchange);
    }

    private void doCreateAppendBlob(CloudAppendBlob client, BlobServiceRequestOptions opts, Exchange exchange)
        throws Exception {
        LOG.trace("Creating an append blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        try {
            client.createOrReplace(opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        } catch (StorageException ex) {
            if (ex.getHttpStatusCode() != 409) {
                throw ex;
            }
        }
        ExchangeUtil.getMessageForResponse(exchange)
            .setHeader(BlobServiceConstants.APPEND_BLOCK_CREATED, Boolean.TRUE);
    }

    private void updateAppendBlob(Exchange exchange) throws Exception {
        CloudAppendBlob client = BlobServiceUtil.createAppendBlobClient(getConfiguration());
        configureCloudBlobForWrite(client);
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        if (opts.getAccessCond() == null) {
            // Default: do not reset the blob content if the blob already exists
            opts.setAccessCond(AccessCondition.generateIfNotExistsCondition());
        }

        Boolean appendBlobCreated = exchange.getIn().getHeader(BlobServiceConstants.APPEND_BLOCK_CREATED,
                                                                  Boolean.class);
        if (Boolean.TRUE != appendBlobCreated) {
            doCreateAppendBlob(client, opts, exchange);
        }

        InputStream inputStream = getInputStreamFromExchange(exchange);
        try {
            client.appendBlock(inputStream, -1,
                               opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        } finally {
            closeInputStreamIfNeeded(inputStream);
        }
    }

    private void deleteAppendBlob(Exchange exchange) throws Exception {
        CloudAppendBlob client = BlobServiceUtil.createAppendBlobClient(getConfiguration());
        doDeleteBlock(client, exchange);
    }

    private void createPageBlob(Exchange exchange) throws Exception {
        CloudPageBlob client = BlobServiceUtil.createPageBlobClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        if (opts.getAccessCond() == null) {
            // Default: do not reset the blob content if the blob already exists
            opts.setAccessCond(AccessCondition.generateIfNotExistsCondition());
        }
        doCreatePageBlob(client, opts, exchange);
    }

    private void doCreatePageBlob(CloudPageBlob client, BlobServiceRequestOptions opts, Exchange exchange)
        throws Exception {
        LOG.trace("Creating a page blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        Long pageSize = getPageBlobSize(exchange);
        try {
            client.create(pageSize,
                          opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        } catch (StorageException ex) {
            if (ex.getHttpStatusCode() != 409) {
                throw ex;
            }
        }
        ExchangeUtil.getMessageForResponse(exchange)
            .setHeader(BlobServiceConstants.PAGE_BLOCK_CREATED, Boolean.TRUE);

    }

    private void uploadPageBlob(Exchange exchange) throws Exception {
        LOG.trace("Updating a page blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);

        CloudPageBlob client = BlobServiceUtil.createPageBlobClient(getConfiguration());
        configureCloudBlobForWrite(client);
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        if (opts.getAccessCond() == null) {
            // Default: do not reset the blob content if the blob already exists
            opts.setAccessCond(AccessCondition.generateIfNotExistsCondition());
        }

        Boolean pageBlobCreated = exchange.getIn().getHeader(BlobServiceConstants.PAGE_BLOCK_CREATED,
                                                                  Boolean.class);
        if (Boolean.TRUE != pageBlobCreated) {
            doCreatePageBlob(client, opts, exchange);
        }
        InputStream inputStream = getInputStreamFromExchange(exchange);
        doUpdatePageBlob(client, inputStream, opts, exchange);

    }

    private void resizePageBlob(Exchange exchange) throws Exception {
        LOG.trace("Resizing a page blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);

        CloudPageBlob client = BlobServiceUtil.createPageBlobClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        Long pageSize = getPageBlobSize(exchange);
        client.resize(pageSize, opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
    }

    private void clearPageBlob(Exchange exchange) throws Exception {
        LOG.trace("Clearing a page blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);

        CloudPageBlob client = BlobServiceUtil.createPageBlobClient(getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);

        Long blobOffset = getConfiguration().getBlobOffset();
        Long blobDataLength = getConfiguration().getDataLength();
        PageRange range = exchange.getIn().getHeader(BlobServiceConstants.PAGE_BLOB_RANGE, PageRange.class);
        if (range != null) {
            blobOffset = range.getStartOffset();
            blobDataLength = range.getEndOffset() - range.getStartOffset();
        }
        if (blobDataLength == null) {
            blobDataLength = blobOffset == 0 ? getPageBlobSize(exchange) : 512L;
        }
        client.clearPages(blobOffset, blobDataLength,
                          opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
    }

    private void doUpdatePageBlob(CloudPageBlob client, InputStream is, BlobServiceRequestOptions opts, Exchange exchange)
        throws Exception {

        Long blobOffset = getConfiguration().getBlobOffset();
        Long blobDataLength = getConfiguration().getDataLength();
        PageRange range = exchange.getIn().getHeader(BlobServiceConstants.PAGE_BLOB_RANGE, PageRange.class);
        if (range != null) {
            blobOffset = range.getStartOffset();
            blobDataLength = range.getEndOffset() - range.getStartOffset();
        }
        if (blobDataLength == null) {
            blobDataLength = (long)is.available();
        }
        try {
            client.uploadPages(is, blobOffset, blobDataLength,
                           opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        } finally {
            closeInputStreamIfNeeded(is);
        }

    }

    private void getPageBlobRanges(Exchange exchange) throws Exception {
        CloudPageBlob client = BlobServiceUtil.createPageBlobClient(getConfiguration());
        BlobServiceUtil.configureCloudBlobForRead(client, getConfiguration());
        BlobServiceRequestOptions opts = BlobServiceUtil.getRequestOptions(exchange);
        LOG.trace("Getting the page blob ranges [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        List<PageRange> ranges =
            client.downloadPageRanges(opts.getAccessCond(), opts.getRequestOpts(), opts.getOpContext());
        ExchangeUtil.getMessageForResponse(exchange).setBody(ranges);
    }

    private void deletePageBlob(Exchange exchange) throws Exception {
        CloudPageBlob client = BlobServiceUtil.createPageBlobClient(getConfiguration());
        doDeleteBlock(client, exchange);
    }

    private Long getPageBlobSize(Exchange exchange) {
        Long pageSize = exchange.getIn().getHeader(BlobServiceConstants.PAGE_BLOB_SIZE, Long.class);
        if (pageSize == null) {
            pageSize = 512L;
        }
        return pageSize;
    }

    private void doDeleteBlock(CloudBlob client, Exchange exchange) throws Exception {
        LOG.trace("Deleting a blob [{}] from exchange [{}]...", getConfiguration().getBlobName(), exchange);
        client.delete();
    }

    private String getCharsetName(Exchange exchange) {
        String charset = exchange.getIn().getHeader(Exchange.CHARSET_NAME, String.class);
        return charset == null ? "UTF-8" : charset;
    }

    private void configureCloudBlobForWrite(CloudBlob client) {
        if (getConfiguration().getStreamWriteSize() > 0) {
            client.setStreamWriteSizeInBytes(getConfiguration().getStreamWriteSize());
        }
        if (getConfiguration().getBlobMetadata() != null) {
            client.setMetadata(new HashMap<String, String>(getConfiguration().getBlobMetadata()));
        }
    }

    private BlobServiceOperations determineOperation(Exchange exchange) {
        BlobServiceOperations operation = exchange.getIn().getHeader(BlobServiceConstants.OPERATION, BlobServiceOperations.class);
        if (operation == null) {
            operation = getConfiguration().getOperation();
        }
        return operation;
    }

    protected BlobServiceConfiguration getConfiguration() {
        return getEndpoint().getConfiguration();
    }

    @Override
    public String toString() {
        return "StorageBlobProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]";
    }

    @Override
    public BlobServiceEndpoint getEndpoint() {
        return (BlobServiceEndpoint) super.getEndpoint();
    }

    private InputStream getInputStreamFromExchange(Exchange exchange) throws Exception {
        Object blobObject = exchange.getIn().getMandatoryBody();
        InputStream inputStream = null;
        if (blobObject instanceof String) {
            String charset = getCharsetName(exchange);
            inputStream = new ByteArrayInputStream(((String)blobObject).getBytes(charset));
        } else if (blobObject instanceof InputStream) {
            inputStream = (InputStream)blobObject;
        } else if (blobObject instanceof File) {
            inputStream = new FileInputStream((File)blobObject);
        } else {
            throw new IllegalArgumentException("Unsupported blob type:" + blobObject.getClass().getName());
        }
        return inputStream;
    }

    private void closeInputStreamIfNeeded(InputStream inputStream) throws IOException {
        if (getConfiguration().isCloseStreamAfterWrite()) {
            inputStream.close();
        }
    }

}