text:
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
require 'active_support'

class Facebooker::SessionTest < Test::Unit::TestCase

  def setup
    ENV['FACEBOOK_API_KEY'] = '1234567'
    ENV['FACEBOOK_SECRET_KEY'] = '7654321'
    Facebooker.current_adapter = nil
    @session = Facebooker::Session.create('whatever', 'doesnotmatterintest')
    Facebooker.use_curl=false
  end

  def teardown
    Facebooker::Session.configuration_file_path = nil
    super
  end

  def test_install_url_escapes_optional_next_parameter
    session = Facebooker::CanvasSession.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    assert_equal("http://www.facebook.com/install.php?api_key=1234567&v=1.0&next=next_url%3Fa%3D1%26b%3D2", session.install_url(:next => "next_url?a=1&b=2"))
  end

  def test_can_get_api_and_secret_key_from_environment
    assert_equal('1234567', Facebooker::Session.api_key)
    assert_equal('7654321', Facebooker::Session.secret_key)
  end

  def test_if_keys_are_not_available_via_environment_then_they_are_gotten_from_a_file
    ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'] = nil
    Facebooker.instance_variable_set('@facebooker_configuration', nil)
    flexmock(File).should_receive(:read).with(File.expand_path("~/.facebookerrc")).once.and_return('{:api => "foo"}')
    assert_equal('foo', Facebooker::Session.api_key)
  end

  def test_if_environment_and_file_fail_to_match_then_an_exception_is_raised
    ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'] = nil
    Facebooker.instance_variable_set('@facebooker_configuration', nil)
    flexmock(File).should_receive(:read).with(File.expand_path("~/.facebookerrc")).once.and_return {raise Errno::ENOENT, "No such file"}
    assert_raises(Facebooker::Session::ConfigurationMissing) {
      Facebooker::Session.api_key
    }
  end

  def test_marshal_stores_api_key
    data = Marshal.dump(@session)
    loaded_session = Marshal.load(data)
    assert_equal 'whatever', loaded_session.instance_variable_get("@api_key")
  end

  def test_marshal_stores_secret_key
    data = Marshal.dump(@session)
    loaded_session = Marshal.load(data)
    assert_equal 'doesnotmatterintest', loaded_session.instance_variable_get("@secret_key")
  end

  def test_configuration_file_path_can_be_set_explicitly
    Facebooker::Session.configuration_file_path = '/tmp/foo'
    assert_equal('/tmp/foo', Facebooker::Session.configuration_file_path)
  end

  def test_session_can_be_secured_with_existing_values
    session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    session.secure_with!("a session key", "123456", Time.now.to_i + 60)
    assert(session.secured?)
    assert_equal 'a session key', session.session_key
    assert_equal 123456, session.user.to_i
  end

  def test_session_can_be_secured_with_existing_values_and_a_nil_uid
    flexmock(session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY']))
    session.should_receive(:post).with('facebook.users.getLoggedInUser', :session_key => 'a session key').returns(321)
    session.secure_with!("a session key", nil, Time.now.to_i + 60)
    assert(session.secured?)
    assert_equal 'a session key', session.session_key
    assert_equal 321, session.user.to_i
  end

  # The Facebook API for this is hideous.  Oh well.
  def test_can_ask_session_to_check_friendship_between_pairs_of_users
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    mock_http = establish_session
    mock_http.should_receive(:post_form).and_return(example_check_friendship_xml).once.ordered(:posts)
    assert_equal({[222332, 222333] => true, [1240077, 1240079] => false}, @session.check_friendship([[222332, 222333], [1240077, 1240079]]))
  end

  def test_facebook_can_claim_ignorance_as_to_friend_relationships
    mock_http = establish_session
    mock_http.should_receive(:post_form).and_return(example_check_friendship_with_unknown_result).once.ordered(:posts)
    assert_equal({[1240077, 1240079] => nil}, @session.check_friendship([[1240077, 1240079]]))
  end

  def test_can_query_with_fql
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    expect_http_posts_with_responses(example_fql_for_multiple_photos_xml)
    response = @session.fql_query('Lets be frank. We are not testing the query here')
    assert_kind_of(Facebooker::Photo, response.first)
  end

  def test_anonymous_fql_results_get_put_in_a_positioned_array_on_the_model
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    expect_http_posts_with_responses(example_fql_for_multiple_photos_with_anon_xml)
    response = @session.fql_query('Lets be frank. We are not testing the query here')
    assert_kind_of(Facebooker::Photo, response.first)
    response.each do |photo|
      assert_equal(['first', 'second'], photo.anonymous_fields)
    end
  end
  def test_no_results_returns_empty_array
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    expect_http_posts_with_responses(no_results_fql)
    response = @session.fql_query('Lets be frank. We are not testing the query here')
    assert_equal [],response
  end

  def test_can_fql_query_for_event_members
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    expect_http_posts_with_responses(example_fql_query_event_members_xml)
    response = @session.fql_query("DOES NOT REALLY MATTER FOR TEST")
    assert_kind_of(Facebooker::Event::Attendance, response.first)
    assert_equal('attending', response.first.rsvp_status)
  end

  def test_can_query_for_event_members
    expect_http_posts_with_responses(example_event_members_xml)
    event_attendances = @session.event_members(69)
    assert_equal Facebooker::Event::Attendance, event_attendances.first.class
    assert_equal 'attending', event_attendances.first.rsvp_status
    assert_equal(["1240077", "222332", "222333", "222335", "222336"], event_attendances.map{|ea| ea.uid}.sort)
    assert_equal 5, event_attendances.size
  end

  def test_can_query_for_events
    expect_http_posts_with_responses(example_events_get_xml)
    events = @session.events
    assert_equal 'Technology Tasting', events.first.name
  end

  def test_can_query_for_groups
    expect_http_posts_with_responses(example_groups_get_xml)
    groups = @session.user.groups
    assert_equal 'Donald Knuth Is My Homeboy', groups.first.name
  end

  def test_can_query_for_group_memberships
    expect_http_posts_with_responses(example_group_members_xml)
    example_group = Facebooker::Group.new({:gid => 123, :session => @session})
    group_memberships = example_group.memberships
    assert_equal('officers', group_memberships.last.position)
    assert_equal(123, group_memberships.last.gid)
    assert_equal(1240078, example_group.members.last.id)
  end

  def test_can_fql_query_for_users_and_pictures
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    mock_http = establish_session
    mock_http.should_receive(:post_form).and_return(example_fql_for_multiple_users_and_pics).once.ordered(:posts)
    response = @session.fql_query('SELECT name, pic FROM user WHERE uid=211031 OR uid=4801660')
    assert_kind_of Array, response
    assert_kind_of Facebooker::User, response.first
    assert_equal "Ari Steinberg", response.first.name
  end

  def test_can_fql_multiquery_for_users_and_pictures
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    mock_http = establish_session
    mock_http.should_receive(:post_form).and_return(example_fql_multiquery_xml).once.ordered(:posts)
    response = @session.fql_multiquery({:query => 'SELECT name, pic FROM user WHERE uid=211031 OR uid=4801660'})
    assert_kind_of Array, response["query1"]
    assert_kind_of Facebooker::User, response["query1"].first
    assert_equal "Ari Steinberg", response["query1"].first.name
  end

  def test_can_send_notification_with_object
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.expects(:post).with('facebook.notifications.send',{:to_ids=>"1",:notification=>"a",:type=>"user_to_user"},true)
    @session.send(:instance_variable_set,"@uid",3)
    user=flexmock("user")
    user.should_receive(:facebook_id).and_return("1").once
    @session.send_notification([user],"a")
  end
  def test_can_send_notification_with_string
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.send(:instance_variable_set,"@uid",3)
    @session.expects(:post).with('facebook.notifications.send',{:to_ids=>"1",:notification=>"a", :type=>"user_to_user"},true)
    @session.send_notification(["1"],"a")
  end

  def test_can_send_announcement_notification
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.expects(:post).with('facebook.notifications.send',{:to_ids=>"1",:notification=>"a", :type=>"app_to_user"},false)
    @session.send_notification(["1"],"a")
  end

  def test_can_register_template_bundle
    expect_http_posts_with_responses(example_register_template_bundle_return_xml)
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    assert_equal 17876842716, @session.register_template_bundle("{*actor*} did something")
  end

  def test_can_register_template_bundle_with_action_links
    expect_http_posts_with_responses(example_register_template_bundle_return_xml)
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    assert_equal 17876842716, @session.register_template_bundle("{*actor*} did something",nil,nil,[{:text=>"text",:href=>"href"}])
  end

  def test_can_register_template_bundle_with_short_story
    one_line = "{*actor*} did something"
    short_story = { :title => 'title', :body => 'body' }

    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.expects(:post).with(
      'facebook.feed.registerTemplateBundle',
      {:one_line_story_templates => [one_line].to_json, :short_story_templates => [short_story].to_json},
      false
    )
    @session.register_template_bundle(one_line, short_story)
  end

  def test_can_register_template_bundle_with_short_story_for_several_templates
    one_line = ["{*actor*} did something", "{*actor*} did something again"]
    short_story = [{ :title => 'title', :body => 'body' }, { :title => 'title2', :body => 'body2' }]

    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.expects(:post).with(
      'facebook.feed.registerTemplateBundle',
      {:one_line_story_templates => one_line.to_json, :short_story_templates => short_story.to_json},
      false
    )
    @session.register_template_bundle(one_line, short_story)
  end

  def test_can_register_template_bundle_with_full_story_for_several_templates
    one_line = ["{*actor*} did something", "{*actor*} did something again"]
    short_story = [{ :title => 'title', :body => 'body' }, { :title => 'title2', :body => 'body2' }]
    full_story = { :title => 'title', :body => 'body' }

    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.expects(:post).with(
      'facebook.feed.registerTemplateBundle',
      {:one_line_story_templates => one_line.to_json, :short_story_templates => short_story.to_json, :full_story_template => full_story.to_json},
      false
    )
    @session.register_template_bundle(one_line, short_story, full_story)
  end

  def test_can_publish_user_action
    expect_http_posts_with_responses(publish_user_action_return_xml)
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    assert @session.publish_user_action(17876842716,{})
  end

  def test_logs_api_calls
    call_name = 'sample.api.call'
    params = { :param1 => true, :param2 => 'value' }
    flexmock(Facebooker::Logging, :Logging).should_receive(:log_fb_api).once.with(
       call_name, params, Proc)
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.post(call_name, params)
  end

  def test_requests_inside_batch_are_added_to_batch
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    @session.send(:service).expects(:post).once
    @session.batch do
      @session.send_notification(["1"],"a")
      @session.send_notification(["1"],"a")
    end

  end

  def test_parses_batch_response
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    expect_http_posts_with_responses(example_batch_run_xml)
    @session.batch do
      @fql_response = @session.fql_query('SELECT name, pic FROM user WHERE uid=211031 OR uid=4801660')
    end
    assert_kind_of(Facebooker::Event::Attendance, @fql_response.first)
    assert_equal('attending', @fql_response.first.rsvp_status)
  end
  def test_parses_batch_response_sets_exception
    @session = Facebooker::Session.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    expect_http_posts_with_responses(example_batch_run_xml)
    Facebooker::FqlQuery.expects(:process).raises(NoMethodError.new)

    @session.batch do
      @fql_response = @session.fql_query('SELECT name, pic FROM user WHERE uid=211031 OR uid=4801660')
    end
    assert_raises(NoMethodError) {
      @fql_response.first
    }
  end

  def test_can_set_and_get_current_batch
    Facebooker::BatchRun.current_batch=4
    assert_equal 4,Facebooker::BatchRun.current_batch
  end

  def test_can_get_stanard_info
    expect_http_posts_with_responses(standard_info_xml)
    result = @session.users_standard([4])
    assert_equal "Mike Mangino",result.first.name
  end

  def test_can_query_for_pages
    expect_http_posts_with_responses(example_pages_xml)
    example_page = Facebooker::Page.new(
      :page_id => 4846711747,
      :name => "Kronos Quartet",
      :website => "http://www.kronosquartet.org",
      :company_overview => "",
      :session => @session)
    pages = @session.pages(:fields => %w[ page_id name website company_overview ])

    assert_equal 1, pages.size

    page = pages.first
    assert_equal "4846711747", page.page_id
    assert_equal "Kronos Quartet", page.name
    assert_equal "http://www.kronosquartet.org", page.website

    # TODO we really need a way to differentiate between hash/list and text attributes
    # assert_equal({}, page.company_overview)

    # sakkaoui : as a fix to the parser, I replace empty text node by "" instead of {}
    # we have child.attributes['list'] == 'true' that let us know that we have a hash/list.
    assert_equal("", page.company_overview)

    genre = page.genre
    assert_equal false, genre.dance
    assert_equal true, genre.party
  end

  private

  def example_fql_multiquery_xml
    <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<fql_multiquery_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
  <fql_result>
    <name>query1</name>
    <results list="true">
      <user>
        <name>Ari Steinberg</name>
        <uid>46903192</uid>
        <rsvp_status xsi:nil="true"/>
      </user>
    </results>
  </fql_result>
  <fql_result>
    <name>query2</name>
    <results list="true">
      <user>
        <name>Lisa Petrovskaia</name>
        <pic xsi:nil="true"/>
      </user>
    </results>
  </fql_result>
</fql_multiquery_response>
XML
  end

  def example_groups_get_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <groups_get_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <group>
        <gid>2206609142</gid>
        <name>Donald Knuth Is My Homeboy</name>
        <nid>0</nid>
        <description>Donald Ervin Knuth (born January 10, 1938) is a renowned computer scientist and professor emeritus at Stanford University.

    Knuth is best known as the author of the multi-volume The Art of Computer Programming, one of the most highly respected references in the computer science field. He practically created the field of rigorous analysis of algorithms, and made many seminal contributions to several branches of theoretical computer science. He is also the creator of the TeX typesetting system and of the METAFONT font design system, and pioneered the concept of literate programming.

    That's how he ROLLS, y0.</description>
        <group_type>Just for Fun</group_type>
        <group_subtype>Fan Clubs</group_subtype>
        <recent_news/>
        <pic>http://photos-142.facebook.com/ip006/object/543/95/s2206609142_32530.jpg</pic>
        <pic_big>http://photos-142.facebook.com/ip006/object/543/95/n2206609142_32530.jpg</pic_big>
        <pic_small>http://photos-142.facebook.com/ip006/object/543/95/t2206609142_32530.jpg</pic_small>
        <creator>1240077</creator>
        <update_time>1156543965</update_time>
        <office/>
        <website/>
        <venue>
          <street/>
          <city/>
          <state>CA</state>
          <country>United States</country>
        </venue>
      </group>
    </groups_get_response>
    XML
  end

  def example_events_get_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <events_get_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <event>
        <eid>1037629024</eid>
        <name>Technology Tasting</name>
        <tagline>Who said Engineering can't be delicious?</tagline>
        <nid>12409987</nid>
        <pic>http://photos-628.facebook.com/ip006/object/1345/48/s1037629024_30775.jpg</pic>
        <pic_big>http://photos-628.facebook.com/ip006/object/1345/48/n1037629024_30775.jpg</pic_big>
        <pic_small>http://photos-628.facebook.com/ip006/object/1345/48/t1037629024_30775.jpg</pic_small>
        <host>Facebook</host>
        <description>Facebook will be hosting technology thought leaders and avid software engineers for a social evening of technology tasting. We invite you to connect with some of our newest technologies and innovative people over hors d'oeuvres and wine. Come share ideas, ask questions, and challenge existing technology paradigms in the spirit of the open source community.</description>
        <event_type>Party</event_type>
        <event_subtype>Cocktail Party</event_subtype>
        <start_time>1172107800</start_time>
        <end_time>1172115000</end_time>
        <creator>1078</creator>
        <update_time>1170096157</update_time>
        <location>Facebook's New Office</location>
        <venue>
          <city>Palo Alto</city>
          <state>CA</state>
          <country>United States</country>
        </venue>
      </event>
    </events_get_response>
    XML
  end

  def example_fql_query_event_members_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
      <event_member>
        <uid>517961878</uid>
        <eid>2454827764</eid>
        <rsvp_status>attending</rsvp_status>
      </event_member>
      <event_member>
        <uid>744961110</uid>
        <eid>2454827764</eid>
        <rsvp_status>declined</rsvp_status>
      </event_member>
    </fql_query_response>
    XML
  end
  def example_check_friendship_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <friends_areFriends_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <friend_info>
        <uid1>222332</uid1>
        <uid2>222333</uid2>
        <are_friends>1</are_friends>
      </friend_info>
      <friend_info>
        <uid1>1240077</uid1>
        <uid2>1240079</uid2>
        <are_friends>0</are_friends>
      </friend_info>
    </friends_areFriends_response>
    XML
  end

  def example_check_friendship_with_unknown_result
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <friends_areFriends_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <friend_info>
        <uid1>1240077</uid1>
        <uid2>1240079</uid2>
        <are_friends xsi:nil="true"/>
      </friend_info>
    </friends_areFriends_response>
    XML
  end

  def example_fql_for_multiple_users_and_pics
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
      <user>
        <name>Ari Steinberg</name>
        <pic>http://profile.ak.facebook.com/profile2/1805/47/s211031_26434.jpg</pic>
      </user>
      <user>
        <name>Ruchi Sanghvi</name>
        <pic>http://profile.ak.facebook.com/v52/870/125/s4801660_2498.jpg</pic>
      </user>
    </fql_query_response>
    XML
  end

  def example_fql_for_multiple_photos_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
      <photo>
        <src>http://photos-c.ak.facebook.com/photos-ak-sf2p/v108/212/118/22700225/s22700225_30345986_2713.jpg</src>
        <caption>Nottttt. get ready for some museumz</caption>
        <caption>Nottttt. get ready for some museumz</caption>
      </photo>
      <photo>
        <src>http://photos-c.ak.facebook.com/photos-ak-sf2p/v77/74/112/22701786/s22701786_30324934_7816.jpg</src>
        <caption>Rooftop barbecues make me act funny</caption>
        <caption>Rooftop barbecues make me act funny</caption>
      </photo>
      <photo>
        <src>http://photos-c.ak.facebook.com/photos-ak-sctm/v96/154/56/22700188/s22700188_30321538_17.jpg</src>
        <caption>An epic shot of Patrick getting ready for a run to second.</caption>
        <caption>An epic shot of Patrick getting ready for a run to second.</caption>
      </photo>
    </fql_query_response>
    XML
  end

  def example_fql_for_multiple_photos_with_anon_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
      <photo>
        <src>http://photos-c.ak.facebook.com/photos-ak-sf2p/v108/212/118/22700225/s22700225_30345986_2713.jpg</src>
        <caption>Nottttt. get ready for some museumz</caption>
        <caption>Nottttt. get ready for some museumz</caption>
        <anon>first</anon>
        <anon>second</anon>
      </photo>
      <photo>
        <src>http://photos-c.ak.facebook.com/photos-ak-sf2p/v77/74/112/22701786/s22701786_30324934_7816.jpg</src>
        <caption>Rooftop barbecues make me act funny</caption>
        <caption>Rooftop barbecues make me act funny</caption>
        <anon>first</anon>
        <anon>second</anon>
      </photo>
      <photo>
        <src>http://photos-c.ak.facebook.com/photos-ak-sctm/v96/154/56/22700188/s22700188_30321538_17.jpg</src>
        <caption>An epic shot of Patrick getting ready for a run to second.</caption>
        <caption>An epic shot of Patrick getting ready for a run to second.</caption>
        <anon>first</anon>
        <anon>second</anon>
      </photo>
    </fql_query_response>
    XML
  end

  def no_results_fql
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
    </fql_query_response>
    XML

  end

  def example_group_members_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <groups_getMembers_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <members list="true">
        <uid>1240077</uid>
        <uid>1240078</uid>
        <uid>222332</uid>
        <uid>222333</uid>
      </members>
      <admins list="true">
        <uid>1240077</uid>
        <uid>222333</uid>
      </admins>
      <officers list="true">
        <uid>1240078</uid>
      </officers>
      <not_replied list="true"/>
    </groups_getMembers_response>
    XML
  end

  def example_batch_run_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <batch_run_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <batch_run_response_elt>
      #{CGI.escapeHTML(example_fql_query_event_members_xml)}
      </batch_run_response_elt>
    </batch_run_response>
    XML
  end

  def example_event_members_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <events_getMembers_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <attending list="true">
        <uid>222332</uid>
        <uid>222333</uid>
      </attending>
      <unsure list="true">
        <uid>1240077</uid>
      </unsure>
      <declined list="true"/>
      <not_replied list="true">
        <uid>222335</uid>
        <uid>222336</uid>
      </not_replied>
    </events_getMembers_response>
    XML
  end

  def example_register_template_bundle_return_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <feed_registerTemplateBundle_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/">
         17876842716
    </feed_registerTemplateBundle_response>
    XML
  end

  def example_pages_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <pages_getInfo_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <page>
        <page_id>4846711747</page_id>
        <name>Kronos Quartet</name>
        <website>http://www.kronosquartet.org</website>
        <company_overview/>
        <genre>
          <dance>0</dance>
          <party>1</party>
        </genre>
      </page>
    </pages_getInfo_response>
    XML
  end

  def publish_user_action_return_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <feed_publishUserAction_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <feed_publishUserAction_response_elt>1</feed_publishUserAction_response_elt>
    </feed_publishUserAction_response>
    XML
  end

  def standard_info_xml
    <<-XML
    <?xml version="1.0" encoding="UTF-8"?>
    <?xml version="1.0" encoding="UTF-8"?>

    <users_getStandardInfo_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
      <standard_user_info>
        <uid>12451752</uid>
        <name>Mike Mangino</name>
      </standard_user_info>
    </users_getStandardInfo_response>
    XML
  end
end

class CanvasSessionTest < Test::Unit::TestCase
  def setup
    ENV['FACEBOOK_API_KEY'] = '1234567'
    ENV['FACEBOOK_SECRET_KEY'] = '7654321'
  end

  def test_login_url_will_display_callback_url_in_canvas
    session = Facebooker::CanvasSession.create(ENV['FACEBOOK_API_KEY'], ENV['FACEBOOK_SECRET_KEY'])
    assert_equal("http://www.facebook.com/login.php?api_key=1234567&v=1.0&canvas=true", session.login_url)
  end
end


text:
class Statistic::Banners < Statistic::Base
  def orders_count
    Order::Base.where(:banner_id.in => @user.banner_ids).count
  end

  def orders_count_percent
    clicked = clicked_count.to_f
    return 0 if clicked == 0
    (orders_count.to_f / clicked.to_f * 100).to_i
  end

  def clicked_count
    @user.banners.inject(0) {|sum, b| sum + b.visits.count}
  end

  def pass_registration_count
    User.where(:agent_banner_id.in => @user.banners.distinct(:id)).count
  end

  def pass_registration_percent
    return 0 if clicked_count == 0
    pass_registration_count * 100  / clicked_count
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.rogach.scallop.tokenize

import java.lang.Character
import java.lang.StringBuilder

/** This class is responsible for correctly loading argument lists from stdin or files.
  * It handles splitting the input into individual arg tokens, accounting for quotes
  * and whitespace escaping.
  *
  * Tokenisation mechanism should be as similar to shell as possible - content in single quotes
  * is passed through as-is, content in double quotes allows escaping of `"` and `\` characters
  * via `\` character, and `\` outside quotes can be used to escape any character whatsoever.
  */
object ArgumentTokenizer {

  def tokenize(input: String): TokenizationResult = {
    argumentsParser(new StringView(input, 0))
  }

  private type Parser = StringView => TokenizationResult

  /// PARSER COMBINATORS

  /** Matches end of input. */
  private val inputEnd: Parser = (input: StringView) => {
    if (input.length == 0) Matched(Nil, input)
    else Failed
  }

  /** Converts Failed result from a parser into Matched(Nil),
    * Matched or EOF results are passed through unchanged.
    */
  private def optional(parser: Parser): Parser = (input: StringView) => {
    parser(input) match {
      case Failed => Matched(Nil, input)
      case other => other
    }
  }

  /** Creates a parser that applies parser1 and then parser2. */
  private def seq(parser1: Parser, parser2: Parser): Parser = (input: StringView) => {
    parser1(input) match {
      case eof: EOF => eof
      case Failed => Failed
      case Matched(tokens1, rest1) =>
        parser2(rest1) match {
          case Matched(tokens2, rest2) => Matched(tokens1 ++ tokens2, rest2)
          case other => other
        }
    }
  }

  /** Repeats the parser until getting Failed, concatenates all Matched results. */
  private def repeat(parser: Parser): Parser = (input: StringView) => {
    repeatImpl(parser, input, Nil)
  }
  @annotation.tailrec
  private def repeatImpl(parser: Parser, input: StringView, acc: List[Seq[String]]): TokenizationResult = {
    parser(input) match {
      case eof: EOF => eof
      case Failed =>
        if (acc.isEmpty) {
          Failed
        } else {
          Matched(acc.reverse.flatten, input)
        }
      case Matched(tokens, remainingInput) =>
        repeatImpl(parser, remainingInput, tokens :: acc)
    }
  }

  /** Iterates through provided parsers and returns the first Matched result. */
  private def alternatives(parsers: List[Parser]): Parser = (input: StringView) => {
    alternativesImpl(parsers, input)
  }
  @annotation.tailrec
  private def alternativesImpl(parsers: List[Parser], input: StringView): TokenizationResult = {
    parsers match {
      case Nil =>
        Failed
      case parser :: remainingParsers =>
        parser(input) match {
          case eof: EOF => eof
          case Failed =>
            alternativesImpl(remainingParsers, input)
          case matched: Matched =>
            matched
        }
    }
  }

  /** Transforms Matched result of a parser. */
  private def mapResult(parser: Parser, fn: Seq[String] => Seq[String]): Parser = (input: StringView) => {
    parser(input) match {
      case Matched(tokens, rest) => Matched(fn(tokens), rest)
      case other => other
    }
  }

  /// LOW-LEVEL PARSERS

  private val whitespace: Parser = (input: StringView) => {
    var i = 0
    val l = input.length
    while (i < l && Character.isWhitespace(input.charAt(i))) {
      i += 1
    }
    if (i == 0) {
      Failed
    } else {
      Matched(Nil, input.substring(i))
    }
  }

  private val singleQuotedString: Parser = (input: StringView) => {
    if (input.length == 0 || input.charAt(0) != '\'') {
      Failed
    } else {
      val stringEnd = input.indexOf('\'', 1)
      if (stringEnd == -1) {
        EOF("\'")
      } else {
        Matched(Seq(input.extract(1, stringEnd)), input.substring(stringEnd+1))
      }
    }
  }

  private val doubleQuotedString: Parser = (input: StringView) => {
    if (input.length == 0 || input.charAt(0) != '"') {
      Failed
    } else {
      var i = 1
      var s = 1
      val l = input.length
      val b = new StringBuilder()
      var break = false
      var eofEscaped = false
      var stringClosed = false
      while (!break && i < l) {
        while (i < l && input.charAt(i) != '\\' && input.charAt(i) != '"') {
          i += 1
        }
        b.append(input.extract(s, i))
        s = i
        if (i < l) {
          if (input.charAt(i) == '\\') {
            if (i + 1 < l) {
              if (input.charAt(i+1) == '\\' || input.charAt(i+1) == '"') {
                b.append(input.charAt(i+1))
              } else {
                b.append(input.extract(i, i+2))
              }
              i = i + 2
              s = i
            } else {
              eofEscaped = true
              break = true
            }
          } else if (input.charAt(i) == '"') {
            stringClosed = true
            break = true
          } else {
            b.append(input.charAt(i))
            i += 1
            s = i
          }
        }
      }
      if (eofEscaped) {
        EOF("escaped char")
      } else if (!stringClosed) {
        EOF("\"")
      } else {
        Matched(Seq(b.toString), input.substring(i+1))
      }
    }
  }

  private val plainArgument: Parser = (input: StringView) => {
    var i = 0
    var s = 0
    val l = input.length
    val b = new StringBuilder()
    var break = false
    var eofEscaped = false
    while (!break && i < l) {
      while (i < l && !Character.isWhitespace(input.charAt(i)) && input.charAt(i) != '\\' && input.charAt(i) != '"' && input.charAt(i) != '\'') {
        i += 1
      }
      b.append(input.extract(s, i))
      s = i
      if (i < l) {
        if (Character.isWhitespace(input.charAt(i))) {
          break = true
        } else if (input.charAt(i) == '\\') {
          if (i + 1 < l) {
            b.append(input.charAt(i+1))
            i = i + 2
            s = i
          } else {
            eofEscaped = true
            break = true
          }
        } else {
          break = true
        }
      }
    }
    if (eofEscaped) {
      EOF("escaped char")
    } else if (b.length() == 0) {
      Failed
    } else {
      Matched(Seq(b.toString), input.substring(i))
    }
  }

  private val token: Parser =
    mapResult(
      repeat(
        alternatives(List(
          singleQuotedString,
          doubleQuotedString,
          plainArgument
        ))
      ),
      tokens => Seq(tokens.mkString(""))
    )

  private val argumentsParser: Parser =
    alternatives(List(
      seq(
        seq(
          repeat(seq(optional(whitespace), token)),
          optional(whitespace)
        ),
        inputEnd
      ),
      seq(optional(whitespace), inputEnd)
    ))

}


text:
package ch.codebulb.jpaqueries.service;

import ch.codebulb.jpaqueries.model.Customer;
import ch.codebulb.jpaqueries.model.Product;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductServiceWithNamedNativeQueries extends ProductService {
    CustomerService customerService;

    public List<Product> findForPurchaseCustomerPremium() {
        return em.createNamedQuery(Product.SQL_FIND_FOR_PURCHASE_CUSTOMER_PREMIUM, Product.class)
                .getResultList();
    }

    public Map<Customer, Double> sumPriceByPurchaseCustomer() {
        List results = em.createNamedQuery(Product.SQL_SUM_PRICE_BY_PURCHASE_CUSTOMER)
                .getResultList();
        Map<Customer, Double> ret = new HashMap<>();
        for (Object result : results) {
            Object[] arr = (Object[]) result;
            ret.put(customerService.findById((Long)arr[0]), ((Double)arr[1]));
        }
        return ret;
    }
}


text:
<?php

namespace Charcoal\Support\Cms;

// From PSR-7
use Psr\Http\Message\UriInterface;

// From 'charcoal-core'
use Charcoal\Model\ModelInterface;

/**
 * Defines a template intrinsically related to routing.
 */
interface ContextualTemplateInterface
{
    /**
     * Set the current renderable object relative to the context.
     *
     * @param  ModelInterface $context The context / view to render the template with.
     * @return self
     */
    public function setContextObject(ModelInterface $context);

    /**
     * Retrieve the current object relative to the context.
     *
     * This method is meant to be reimplemented in a child template controller
     * to return the resolved object that the module considers "the context".
     *
     * @return ModelInterface|null
     */
    public function contextObject();

    /**
     * Retrieve the current URI of the context.
     *
     * @return string|UriInterface
     */
    public function currentUrl();
}


text:
/*
 * 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.
 */
package com.facebook.presto.plugin.bigquery;

import com.facebook.presto.common.ErrorCode;
import com.facebook.presto.common.ErrorType;
import com.facebook.presto.spi.ErrorCodeSupplier;

import static com.facebook.presto.common.ErrorType.EXTERNAL;

public enum BigQueryErrorCode
        implements ErrorCodeSupplier
{
    BIGQUERY_VIEW_DESTINATION_TABLE_CREATION_FAILED(0, EXTERNAL),
    BIGQUERY_FAILED_TO_EXECUTE_QUERY(1, EXTERNAL),
    BIGQUERY_QUERY_FAILED_UNKNOWN(2, EXTERNAL),
    BIGQUERY_UNSUPPORTED_TYPE_FOR_SLICE(3, EXTERNAL),
    BIGQUERY_UNSUPPORTED_COLUMN_TYPE(4, EXTERNAL),
    BIGQUERY_UNSUPPORTED_TYPE_FOR_BLOCK(5, EXTERNAL),
    BIGQUERY_UNSUPPORTED_TYPE_FOR_LONG(6, EXTERNAL),
    BIGQUERY_UNSUPPORTED_TYPE_FOR_VARBINARY(7, EXTERNAL),
    BIGQUERY_TABLE_DISAPPEAR_DURING_LIST(8, EXTERNAL),
    BIGQUERY_ERROR_END_OF_AVRO_BUFFER(9, EXTERNAL),
    BIGQUERY_ERROR_READING_NEXT_AVRO_RECORD(10, EXTERNAL);

    private final ErrorCode errorCode;

    BigQueryErrorCode(int code, ErrorType type)
    {
        errorCode = new ErrorCode(code + 0x0509_0000, name(), type);
    }

    @Override
    public ErrorCode toErrorCode()
    {
        return errorCode;
    }
}


text:
package org.springframework.web.context;

import org.springframework.context.ApplicationContext;

public interface WebApplicationContext extends ApplicationContext {}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.EnableNullable
{
    [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.EnableNullable)]
    [Shared]
    internal class EnableNullableCodeRefactoringProvider : CodeRefactoringProvider
    {
        private static readonly Func<DirectiveTriviaSyntax, bool> s_isNullableDirectiveTriviaPredicate =
            directive => directive.IsKind(SyntaxKind.NullableDirectiveTrivia);

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public EnableNullableCodeRefactoringProvider()
        {
        }

        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var (document, textSpan, cancellationToken) = context;
            if (!textSpan.IsEmpty)
                return;

            if (document.Project is not
                {
                    ParseOptions: CSharpParseOptions { LanguageVersion: >= LanguageVersion.CSharp8 },
                    CompilationOptions.NullableContextOptions: NullableContextOptions.Disable,
                })
            {
                return;
            }

            var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var token = root.FindToken(textSpan.Start, findInsideTrivia: true);
            if (token.IsKind(SyntaxKind.EndOfDirectiveToken))
                token = root.FindToken(textSpan.Start - 1, findInsideTrivia: true);

            if (!token.IsKind(SyntaxKind.EnableKeyword, SyntaxKind.RestoreKeyword, SyntaxKind.DisableKeyword, SyntaxKind.NullableKeyword, SyntaxKind.HashToken)
                || !token.Parent.IsKind(SyntaxKind.NullableDirectiveTrivia, out NullableDirectiveTriviaSyntax? nullableDirectiveTrivia))
            {
                return;
            }

            context.RegisterRefactoring(
                new MyCodeAction((purpose, cancellationToken) => EnableNullableReferenceTypesAsync(document.Project, purpose, cancellationToken)));
        }

        private static async Task<Solution> EnableNullableReferenceTypesAsync(Project project, CodeActionPurpose purpose, CancellationToken cancellationToken)
        {
            var solution = project.Solution;
            foreach (var document in project.Documents)
            {
                if (await document.IsGeneratedCodeAsync(cancellationToken).ConfigureAwait(false))
                    continue;

                var updatedDocumentRoot = await EnableNullableReferenceTypesAsync(document, cancellationToken).ConfigureAwait(false);
                solution = solution.WithDocumentSyntaxRoot(document.Id, updatedDocumentRoot);
            }

            if (purpose is CodeActionPurpose.Apply)
            {
                var compilationOptions = (CSharpCompilationOptions)project.CompilationOptions!;
                solution = solution.WithProjectCompilationOptions(project.Id, compilationOptions.WithNullableContextOptions(NullableContextOptions.Enable));
            }

            return solution;
        }

        private static async Task<SyntaxNode> EnableNullableReferenceTypesAsync(Document document, CancellationToken cancellationToken)
        {
            var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var firstToken = GetFirstTokenOfInterest(root);
            if (firstToken.IsKind(SyntaxKind.None))
            {
                // The document has no content, so it's fine to change the nullable context
                return root;
            }

            // Update #nullable directives that already exist in the document
            (root, firstToken) = RewriteExistingDirectives(root, firstToken);

            // Update existing documents to retain their original semantics
            //
            // * Add '#nullable disable' if the document didn't specify other semantics
            // * Remove leading '#nullable restore' (was '#nullable enable' prior to rewrite in the previous step)
            // * Otherwise, leave existing '#nullable' directive since it will control the initial semantics for the document
            return await DisableNullableReferenceTypesInExistingDocumentIfNecessaryAsync(document, root, firstToken, cancellationToken).ConfigureAwait(false);
        }

        private static (SyntaxNode root, SyntaxToken firstToken) RewriteExistingDirectives(SyntaxNode root, SyntaxToken firstToken)
        {
            var firstNonDirectiveToken = root.GetFirstToken();
            var firstDirective = root.GetFirstDirective(s_isNullableDirectiveTriviaPredicate);
            if (firstNonDirectiveToken.IsKind(SyntaxKind.None) && firstDirective is null)
            {
                // The document has no semantic content, and also has no nullable directives to update
                return (root, firstToken);
            }

            // Update all prior nullable directives
            var directives = new List<NullableDirectiveTriviaSyntax>();
            for (var directive = firstDirective; directive is not null; directive = directive.GetNextDirective(s_isNullableDirectiveTriviaPredicate))
            {
                directives.Add((NullableDirectiveTriviaSyntax)directive);
            }

            var updatedRoot = root.ReplaceNodes(
                directives,
                (originalNode, rewrittenNode) =>
                {
                    if (originalNode.SettingToken.IsKind(SyntaxKind.DisableKeyword))
                    {
                        // 'disable' keeps its meaning
                        return rewrittenNode;
                    }

                    if (originalNode.SettingToken.IsKind(SyntaxKind.RestoreKeyword))
                    {
                        return rewrittenNode.WithSettingToken(SyntaxFactory.Token(SyntaxKind.DisableKeyword).WithTriviaFrom(rewrittenNode.SettingToken));
                    }

                    if (originalNode.SettingToken.IsKind(SyntaxKind.EnableKeyword))
                    {
                        return rewrittenNode.WithSettingToken(SyntaxFactory.Token(SyntaxKind.RestoreKeyword).WithTriviaFrom(rewrittenNode.SettingToken));
                    }

                    Debug.Fail("Unexpected state?");
                    return rewrittenNode;
                });

            return (updatedRoot, GetFirstTokenOfInterest(updatedRoot));
        }

        private static async Task<SyntaxNode> DisableNullableReferenceTypesInExistingDocumentIfNecessaryAsync(Document document, SyntaxNode root, SyntaxToken firstToken, CancellationToken cancellationToken)
        {
            var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
            var newLine = SyntaxFactory.EndOfLine(options.GetOption(FormattingOptions2.NewLine));

            // Add a new '#nullable disable' to the top of each file
            if (!HasLeadingNullableDirective(root, out var leadingDirective))
            {
                var nullableDisableTrivia = SyntaxFactory.Trivia(SyntaxFactory.NullableDirectiveTrivia(SyntaxFactory.Token(SyntaxKind.DisableKeyword).WithPrependedLeadingTrivia(SyntaxFactory.ElasticSpace), isActive: true));

                var existingTriviaList = firstToken.LeadingTrivia;
                var insertionIndex = GetInsertionPoint(existingTriviaList);

                return root.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(existingTriviaList.InsertRange(insertionIndex, new[] { nullableDisableTrivia, newLine, newLine })));
            }
            else if (leadingDirective.SettingToken.IsKind(SyntaxKind.RestoreKeyword) && leadingDirective.TargetToken.IsKind(SyntaxKind.None))
            {
                // Remove the leading `#nullable restore` directive because it's redundant. Since there is no
                // RemoveTrivia call, we replace the trivia with an empty marker.
                return root.ReplaceTrivia(leadingDirective.ParentTrivia, SyntaxFactory.ElasticMarker);
            }
            else
            {
                // No need to add a '#nullable disable' directive because the file already starts with an unconditional
                // '#nullable' directive that will override it.
                return root;
            }
        }

        private static int GetInsertionPoint(SyntaxTriviaList list)
        {
            var insertionPoint = list.Count;
            for (var i = list.Count - 1; i >= 0; i--)
            {
                switch (list[i].Kind())
                {
                    case SyntaxKind.WhitespaceTrivia:
                    case SyntaxKind.EndOfLineTrivia:
                    case SyntaxKind.SingleLineCommentTrivia:
                    case SyntaxKind.MultiLineCommentTrivia:
                        continue;

                    case SyntaxKind.SingleLineDocumentationCommentTrivia:
                    case SyntaxKind.MultiLineDocumentationCommentTrivia:
                        // Insert before the documentation comment
                        insertionPoint = i;
                        continue;

                    default:
                        return insertionPoint;
                }
            }

            return insertionPoint;
        }

        private static SyntaxToken GetFirstTokenOfInterest(SyntaxNode root)
        {
            var firstToken = root.GetFirstToken(includeDirectives: true);
            if (firstToken.IsKind(SyntaxKind.None))
            {
                return firstToken;
            }

            if (firstToken.IsKind(SyntaxKind.HashToken) && firstToken.Parent.IsKind(SyntaxKind.RegionDirectiveTrivia))
            {
                // If the file starts with a #region/#endregion that contains no semantic content (e.g. just a file
                // header), skip it.
                var nextToken = firstToken.Parent.GetLastToken(includeDirectives: true).GetNextToken(includeDirectives: true);
                if (nextToken.IsKind(SyntaxKind.HashToken) && nextToken.Parent.IsKind(SyntaxKind.EndRegionDirectiveTrivia))
                {
                    firstToken = nextToken.Parent.GetLastToken(includeDirectives: true).GetNextToken(includeDirectives: true);
                }
            }

            return firstToken;
        }

        private static bool HasLeadingNullableDirective(SyntaxNode root, [NotNullWhen(true)] out NullableDirectiveTriviaSyntax? leadingNullableDirective)
        {
            // A leading nullable directive is a '#nullable' directive which precedes any conditional directives ('#if')
            // or code (non-trivia).
            var firstRelevantDirective = root.GetFirstDirective(static directive => directive.IsKind(SyntaxKind.NullableDirectiveTrivia, SyntaxKind.IfDirectiveTrivia));
            if (firstRelevantDirective.IsKind(SyntaxKind.NullableDirectiveTrivia, out NullableDirectiveTriviaSyntax? nullableDirective)
                && nullableDirective.TargetToken.IsKind(SyntaxKind.None))
            {
                var firstSemanticToken = root.GetFirstToken();
                if (firstSemanticToken.IsKind(SyntaxKind.None) || firstSemanticToken.SpanStart > nullableDirective.Span.End)
                {
                    leadingNullableDirective = nullableDirective;
                    return true;
                }
            }

            leadingNullableDirective = null;
            return false;
        }

        private enum CodeActionPurpose
        {
            Preview,
            Apply,
        }

        private sealed class MyCodeAction : CodeAction.SolutionChangeAction
        {
            private readonly Func<CodeActionPurpose, CancellationToken, Task<Solution>> _createChangedSolution;

            public MyCodeAction(Func<CodeActionPurpose, CancellationToken, Task<Solution>> createChangedSolution)
                : base(
                    CSharpFeaturesResources.Enable_nullable_reference_types_in_project,
                    cancellationToken => createChangedSolution(CodeActionPurpose.Apply, cancellationToken),
                    nameof(CSharpFeaturesResources.Enable_nullable_reference_types_in_project))
            {
                _createChangedSolution = createChangedSolution;
            }

            protected override async Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken)
            {
                var changedSolution = await _createChangedSolution(CodeActionPurpose.Preview, cancellationToken).ConfigureAwait(false);
                if (changedSolution is null)
                    return Array.Empty<CodeActionOperation>();

                return new CodeActionOperation[] { new ApplyChangesOperation(changedSolution) };
            }
        }
    }
}


text:
<form role="search" method="get" class="woocommerce-product-search" action="<?php echo esc_url( home_url( '/'  ) ); ?>">
	<?php _e( 'Search for:', 'woocommerce' ); ?>

	<input type="search" class="search-field form-control" placeholder="<?php echo esc_attr_x( 'Search Products…', 'placeholder', 'woocommerce' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label', 'woocommerce' ); ?>" />

		<input type="submit" class="btn btn-default" value="<?php echo esc_attr_x( 'Search', 'submit button', 'woocommerce' ); ?>" />

	<input type="hidden" name="post_type" value="product" />
</form>


text:
<?php
namespace Application\Model;
use Application\View\Helper\Util;

class Vitima {

    private $id_vitima;
    private $nome;
    private $telefone;
    private $data_nasc;
    private $sexo;
    private $id_end;

    public function exchangeArray($data) {
        //objeto Graduacao
        //$grad = new Graduacao($data['id_grad'], $data['graduacao']);

        $this->id_vitima = (!empty($data['id_vitima'])) ? $data['id_vitima'] : null;
        $this->nome = (!empty($data['nome'])) ? $data['nome'] : null;
        $this->telefone = (!empty($data['telefone'])) ? $data['telefone'] : null;
        $this->data_nasc = (!empty($data['data_nasc'])) ? $data['data_nasc'] : null;
        $this->sexo = (!empty($data['sexo'])) ? $data['sexo'] : null;
        $this->id_end = (!empty($data['id_end'])) ? $data['id_end'] : null;

    }

    public function getId_vitima() {
        return $this->id_vitima;
    }

    public function getNome() {
        return $this->nome;
    }

    public function getTelefone() {
        return $this->telefone;
    }

    public function getData_nasc() {
        return $this->data_nasc;
    }

    public function getSexo() {
        return $this->sexo;
    }

    public function getId_end() {
        return $this->id_end;
    }

    public function setId_vitima($id_vitima) {
        $this->id_vitima = $id_vitima;
    }

    public function setNome($nome) {
        $this->nome = $nome;
    }

    public function setTelefone($telefone) {
        $this->telefone = $telefone;
    }

    public function setData_nasc($data_nasc) {
        $this->data_nasc = Util::toDateYMD($data_nasc);
    }

    public function setSexo($sexo) {
        $this->sexo = $sexo;
    }

    public function setId_end($id_end) {
        $this->id_end = $id_end;
    }

}


text:
import * as React from 'react';
import { render } from '../../../../../__tests__/utils/test-utils';
import { ModulePersonWebsite } from '../website';

describe('ModulePersonWebsite', function fnDescribe() {
    const props = {
        content: {
            website: 'www.foobar.com'
        }
    };

    it('should render correctly', function fnIt() {
        const { asFragment } = render(<ModulePersonWebsite {...props} />);
        expect(asFragment()).toMatchSnapshot();
    });
    it('should return null if content is empty', function fnIt() {
        const { asFragment } = render(
            <ModulePersonWebsite {...props} content={null} />
        );
        expect(asFragment()).toMatchSnapshot();
    });
});


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Extra: permitirá cargar marcos de aplicación
var partials = require('express-partials');
// Extra: permite usar los métodos PUT y DELETE de HTTP
var methodOverride = require('method-override');
// Extra: control de sesión habitual en node.js
var session = require('express-session');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Hace que se utilice un marco de la aplicación
app.use(partials());

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('quiz-dalonsod'));
app.use(session());
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));

// Helpers dinámicos: ayuda con la sesión
app.use(function(req, res, next) {

    // 1º Guardar el path del que se viene, para poder usarlo tras un
    //    login/logout. Por tanto, es cualquiera menos los dos últimos
    if ( !req.path.match(/\/login|\/logout/) ) {
        // TODO esto no cubre las rutas con parámetros, como la de la
        //      búsqueda de preguntas
        req.session.redir = req.path;
    }

    // 2º Para las vistas, hacemos visible la información de sesión
    res.locals.session = req.session;

    // Si se necesitan más helpers, se pueden añadir aquí o hacer otro MW
    // ...

    // Continuamos con la ejecución de los MWs
    next();

});

// Control de autologout (tiempo máximo de inactividad: 2 minutos)
var inactivityMaxPeriodMillisecs = 2*60*1000;
app.use(function(req, res, next) {

    // Actualización de marcas de tiempo: se usa tiempo absoluto para
    //  convertirlo desde las variables de sesión, que son String
    var currentTimestamp = new Date().getTime();
    var lastTimestamp = (+req.session.timestamp);
    req.session.timestamp = currentTimestamp;

    // Solo si hay sesión se hace la validación
    if ( req.session.user ) {
        var diffMilliseconds = currentTimestamp - lastTimestamp;
        // Tiempo máximo de inactividad: 2 minutos
        if ( diffMilliseconds > inactivityMaxPeriodMillisecs ) {
            // Esto suprimirá la sesión
            delete req.session.user;
            req.session.errors = [
                {'message': 'Tiempo máximo de inactividad superado, autentíquese de nuevo'}
            ];
            res.redirect('/login');
            return;
        }
    }

    // Si todo es correcto, se continúa
    next();

});

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            errors: []
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        errors: []
    });
});

module.exports = app;


text:
<?php

namespace Acme\DemoBundle;

use Symfony\Component\Security\Core\Util\SecureRandomInterface;

class NoteManager
{
    /** @var array notes */
    protected $data = array();

    /**
     * @var \Symfony\Component\Security\Core\Util\SecureRandomInterface
     */
    protected $randomGenerator;

    /**
     * @var string
     */
    protected $cacheDir;

    public function __construct(SecureRandomInterface $randomGenerator, $cacheDir)
    {
        if (file_exists($cacheDir . '/sf_note_data')) {
            $data = file_get_contents($cacheDir . '/sf_note_data');
            $this->data = unserialize($data);
        }

        $this->randomGenerator = $randomGenerator;
        $this->cacheDir = $cacheDir;
    }

    private function flush()
    {
        file_put_contents($this->cacheDir . '/sf_note_data', serialize($this->data));
    }

    public function fetch($start = 0, $limit = 5)
    {
        return array_slice($this->data, $start, $limit, true);
    }

    public function get($id)
    {
        if (!isset($this->data[$id])) {
            return false;
        }

        return $this->data[$id];
    }

    public function set($note)
    {
        if (null === $note->id) {
            if (empty($this->data)) {
                $note->id = 0;
            } else {
                end($this->data);
                $note->id = key($this->data) + 1;
            }
        }

        if (null === $note->secret) {
            $note->secret = base64_encode($this->randomGenerator->nextBytes(64));
        }

        $this->data[$note->id] = $note;
        $this->flush();
    }

    public function remove($id)
    {
        if (!isset($this->data[$id])) {
            return false;
        }

        unset($this->data[$id]);
        $this->flush();

        return true;
    }
}


text:
<?php

namespace Sylius\Bundle\ResourceBundle\Controller;

use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Bundle\ResourceBundle\Event\ResourceEvent;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Domain manager.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
 */
class DomainManager
{
    private $manager;
    private $eventDispatcher;
    private $flashHelper;
    private $config;

    public function __construct(ObjectManager $manager, EventDispatcherInterface $eventDispatcher, FlashHelper $flashHelper, Configuration $config)
    {
        $this->manager = $manager;
        $this->eventDispatcher = $eventDispatcher;
        $this->flashHelper = $flashHelper;
        $this->config = $config;
    }

    public function create($resource)
    {
        $event = $this->dispatchEvent('pre_create', new ResourceEvent($resource));

        if ($event->isStopped()) {
            $this->flashHelper->setFlash($event->getMessageType(), $event->getMessage(), $event->getMessageParameters());

            return null;
        }

        $this->manager->persist($resource);
        $this->manager->flush();
        $this->flashHelper->setFlash('success', 'create');

        $this->dispatchEvent('post_create', new ResourceEvent($resource));

        return $resource;
    }

    public function update($resource)
    {
        $event = $this->dispatchEvent('pre_update', new ResourceEvent($resource));

        if ($event->isStopped()) {
            $this->flashHelper->setFlash($event->getMessageType(), $event->getMessage(), $event->getMessageParameters());

            return null;
        }

        $this->manager->persist($resource);
        $this->manager->flush();
        $this->flashHelper->setFlash('success', 'update');

        $this->dispatchEvent('post_update', new ResourceEvent($resource));

        return $resource;
    }

    public function delete($resource)
    {
        $event = $this->dispatchEvent('pre_delete', new ResourceEvent($resource));

        if ($event->isStopped()) {
            $this->flashHelper->setFlash($event->getMessageType(), $event->getMessage(), $event->getMessageParameters());

            return null;
        }

        $this->manager->remove($resource);
        $this->manager->flush();
        $this->flashHelper->setFlash('success', 'delete');

        $this->dispatchEvent('post_delete', new ResourceEvent($resource));

        return $resource;
    }

    public function dispatchEvent($name, Event $event)
    {
        $name = $this->config->getEventName($name);

        return $this->eventDispatcher->dispatch($name, $event);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Package net.sf.jsqlparser.parser
</TITLE>

<META NAME="date" CONTENT="2011-02-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
net.sf.jsqlparser.parser

Packages that use net.sf.jsqlparser.parser

net.sf.jsqlparser.parser

Classes in net.sf.jsqlparser.parser used by net.sf.jsqlparser.parser

CCJSqlParser.JJCalls

CCJSqlParser.LookaheadSuccess

CCJSqlParserConstants

          Token literal values and constants.

CCJSqlParserTokenManager

          Token Manager.

JSqlParser

          Every parser must implements this interface

ParseException

          This exception is thrown when parse errors are encountered.

SimpleCharStream

          An implementation of interface CharStream, where the stream is assumed to
 contain only ASCII characters (without unicode processing).

Token

          Describes the input token stream.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
require 'refinery/extension_generation'
require 'rails/generators/migration'

module Refinery
  class FormGenerator < Rails::Generators::NamedBase
    source_root Pathname.new(File.expand_path('../templates', __FILE__))

    include Refinery::ExtensionGeneration

    def description
      "Generates an extension which is set up for frontend form submissions like a contact page."
    end

    def generate
      sanity_check!

      evaluate_templates!

      merge_locales!

      copy_or_merge_seeds!

      append_extension_to_gemfile!

      finalize_extension!
    end

    protected

    def generator_command
      'rails generate refinery:form'
    end

  end
end


text:
use strict;
use warnings;

#############################################################################
#
# Check if all needed modules are available, exit if something is missing.
#############################################################################
#

BEGIN {
  my @req_mods = ('Fcntl', 'File::Basename', 'File::Copy', 'Getopt::Long',
                  'Sys::Hostname', 'Data::Dumper');
  my @missing_mods;
  my $req;
  foreach $req (@req_mods) {
    eval 'require ' . $req;
    if ($@) {
      push(@missing_mods, $req);
    } else {
      $req->import();
    }
  }
  # this avoids the confusing "BEGIN failed--compilation aborted" message
  local $SIG{__DIE__} = sub {warn @_; exit 1};

  if (@missing_mods) {
    my $msg = "FATAL ERROR: please install the following Perl modules " .
              "before executing $0:\n" . join("\n",@missing_mods)."\n";
    die $msg;
  }
}

Getopt::Long::Configure("pass_through");

my @args;                       # Argument list filled in
my $basedir;

##############################################################################
#
#  Usage information
#
##############################################################################

sub usage
{
  print <<EOF1;
Usage: $0 [OPTIONS]
  --basedir=path       The path to the MySQL installation directory.
  --builddir=path      If using --srcdir with out-of-directory builds, you
                       will need to set this to the location of the build
                       directory where built files reside.
  --cross-bootstrap    For internal use.  Used when building the MySQL system
                       tables on a different host than the target.
  --datadir=path       The path to the MySQL data directory.
                       If missing, the directory will be created, but its
                       parent directory must already exist and be writable.
  --defaults-extra-file=name
                       Read this file after the global files are read.
  --defaults-file=name Only read default options from the given file name.
  --force              Causes mysql_install_db to run even if DNS does not
                       work.  In that case, grant table entries that normally
                       use hostnames will use IP addresses.
  --help               Display this help and exit.
  --ldata=path         The path to the MySQL data directory. Same as --datadir.
  --no-defaults        Don't read default options from any option file.
EOF1
  if ( $^O !~ m/^(MSWin32|cygwin)$/ ) {
    print <<EOF2;
  --random-passwords   Create and set a random password for all root accounts
                       and set the "password expired" flag,
                       also remove the anonymous accounts.
EOF2
  }
  print <<EOF3;
  --rpm                For internal use.  This option is used by RPM files
                       during the MySQL installation process.
  --skip-name-resolve  Use IP addresses rather than hostnames when creating
                       grant table entries.  This option can be useful if
                       your DNS does not work.
  --srcdir=path        The path to the MySQL source directory.  This option
                       uses the compiled binaries and support files within the
                       source tree, useful for if you don't want to install
                       MySQL yet and just want to create the system tables.
EOF3
  if ( $^O !~ m/^(MSWin32|cygwin)$/ ) {
    print <<EOF4;
  --user=user_name     The login username to use for running mysqld.  Files
                       and directories created by mysqld will be owned by this
                       user.  You must be root to use this option.  By default
                       mysqld runs using your current login name and files and
                       directories that it creates will be owned by you.
EOF4
  }
  print <<EOF5;
Any other options are passed to the mysqld program.

EOF5
  exit 1;
}

##############################################################################
#
#  Parse an argument list
#
#  We only need to pass arguments through to the server if we don't
#  handle them here.  So, we collect unrecognized options (passed on
#  the command line) into the args variable.
#
##############################################################################

sub parse_arguments
{
  my $opt = shift;

  my @saved_ARGV = @ARGV;
  @ARGV = @_;                           # Set ARGV so GetOptions works

  my $pick_args;
  if (@ARGV and $ARGV[0] eq 'PICK-ARGS-FROM-ARGV')
  {
    $pick_args = 1;
    shift @ARGV;
  }

  GetOptions(
             $opt,
             "force",
             "basedir=s",
             "builddir=s",      # FIXME not documented
             "srcdir=s",
             "ldata|datadir=s",

             # Note that the user will be passed to mysqld so that it runs
             # as 'user' (crucial e.g. if log-bin=/some_other_path/
             # where a chown of datadir won't help)
             "user=s",

             "skip-name-resolve",
             "verbose",
             "rpm",
             "help",
             "random-passwords",

             # These options will also be pased to mysqld.
             "defaults-file=s",
             "defaults-extra-file=s",
             "no-defaults",

             # Used when building the MySQL system tables on a different host than
             # the target. The platform-independent files that are created in
             # --datadir on the host can be copied to the target system.
             #
             # The most common use for this feature is in the Windows installer
             # which will take the files from datadir and include them as part of
             # the install package.  See top-level 'dist-hook' make target.
             #
             # --windows is a deprecated alias
             "cross-bootstrap|windows",
  ) or usage();

  usage() if $opt->{help};

  if ( $opt->{'no-defaults'} && ( $opt->{'defaults-extra-file'} ||
				  $opt->{'defaults-file'} ) )
  {
    error($opt,
	  "Cannot use both --no-defaults and --defaults-[extra-]file");
  }

  @args =  @ARGV if $pick_args;

  @ARGV = @saved_ARGV;                  # Set back ARGV
}

##############################################################################
#
#  Try to find a specific file within --basedir which can either be a binary
#  release or installed source directory and return the path.
#
##############################################################################

sub find_in_basedir
{
  my $opt   = shift;
  my $mode  = shift;            # "dir" or "file"
  my $files = shift;

  foreach my $file ( @{ref($files) ? $files : [$files]} )
  {
    foreach my $dir ( @_ )
    {
      foreach my $part ( "$file","$file.exe","release/$file.exe",
                         "debug/$file.exe","relwithdebinfo/$file.exe" )
      {
        my $path = "$basedir/$dir/$part";
        if ( -f $path )
        {
          return $mode eq "dir" ? dirname($path) : $path;
        }
      }
    }
  }
}

##############################################################################
#
#  Just a function to write out an error report
#
##############################################################################

sub cannot_find_file
{
  my $file = shift;

  print "FATAL ERROR: Could not find $file\n";
  print "\n";
  print "If you compiled from source, you need to run 'make install' to\n";
  print "copy the software into the correct location ready for operation.\n";
  print "\n";
  print "If you are using a binary release, you must either be at the top\n";
  print "level of the extracted archive, or pass the --basedir option\n";
  print "pointing to that location.\n";
  print "\n";

  exit 1;
}

##############################################################################
#
#  Form a command line that can handle spaces in paths and arguments
#
##############################################################################

# FIXME this backslash escaping needed if using '"..."' ?
# This regexp makes sure that any special chars are quoted,
# so the arg gets passed exactly to the server.
# XXX: This is broken; true fix requires using eval and proper
# quoting of every single arg ($opt->{basedir}, $opt->{ldata}, etc.)
#  join(" ", map {s/([^\w\_\.\-])/\\$1/g}

sub quote_options {
  my @cmd;
  foreach my $opt ( @_ )
  {
    next unless $opt;           # If undefined or empty, just skip
    push(@cmd, "\"$opt\"");     # Quote argument
  }
  return join(" ", @cmd);
}

##############################################################################
#
#  Simple escape mechanism (\-escape any ' and \), suitable for two contexts:
#  - single-quoted SQL strings
#  - single-quoted option values on the right hand side of = in my.cnf
#
##############################################################################

# (Function and comment copied from 'mysql_secure_installation')

# These two contexts don't handle escapes identically.  SQL strings allow
# quoting any character (\C => C, for any C), but my.cnf parsing allows
# quoting only \, ' or ".  For example, password='a\b' quotes a 3-character
# string in my.cnf, but a 2-character string in SQL.
#
# This simple escape works correctly in both places.

# FIXME: What about double quote in password? Not handled here - not needed?

sub basic_single_escape {
  my ($str) = @_;
  # Inside a character class, \ is not special; this escapes both \ and '
  $str =~ s/([\'])/\\$1/g;
  return $str;
}

##############################################################################
#
#  Handle the files with confidential contents
#
##############################################################################

my $secret_file;   # full path name of the confidential file
my $escaped_password;      # the password, with special characters escaped

sub ensure_secret_file {
  $secret_file = $ENV{HOME} . "/.mysql_secret";

  # Create safe files to avoid leaking info to other users
  # Loop may be extended if we need more ...
  foreach my $file ( $secret_file ) {
    next if -f $file;                   # Already exists
    local *FILE;
    sysopen(FILE, $file, O_CREAT, 0600)
      or die "ERROR: can't create $file: $!";
    close FILE;
  }
}

##############################################################################
#
#  Append an arbitrary number of lines to an existing file
#
##############################################################################

sub append_file {
  my $file = shift;
  -f $file or die "ERROR: file is missing \"$file\": $!";
  open(FILE, ">>$file") or die "ERROR: can't append to file \"$file\": $!";
  foreach my $line ( @_ ) {
    print FILE $line, "\n";             # Add EOL char
  }
  close FILE;
}

##############################################################################
#
#  Inform the user about the generated random password
#
##############################################################################

sub tell_root_password {
  my $now = localtime(); # scalar context = printable string

  # Now, we need to tell the user the new root password.
  # We use "append_file" to protect the user in case they are doing multiple
  # installations intermixed with backups and restores.
  # While this would be really bad practice, it still might happen.
  # As long as this file is not destroyed, the time stamps may rescue them.
  # Having the comment and the password on the same line makes it easier
  # to automatically extract the password (automated testing!), and the final
  # empty line is for better redability.
  append_file($secret_file,
             "# The random password set for the root user at $now (local time): " .
                 $escaped_password,
             "");
  print "A random root password has been set. You will find it in '$secret_file'.\n";
}

##############################################################################
#
#  Generate a random password
#
##############################################################################

sub generate_random_password {
  # On Linux, Solaris, Max OS X and FreeBSD we have a random device available.
  my $randfile = "/dev/urandom";
  open(FD, $randfile) || return "";
  my $password = "";
  my $pass_len = 16;
  my $c;
  while (length($password) < $pass_len) {
    $c = getc(FD);
    if ($c =~ /\w/) {
      $password .= $c;
    }
  }
  close(FD);
  return $password;
}

##############################################################################
#
#  Ok, let's go.  We first need to parse arguments which are required by
#  my_print_defaults so that we can execute it first, then later re-parse
#  the command line to add any extra bits that we need.
#
##############################################################################

my $opt = {};
parse_arguments($opt, 'PICK-ARGS-FROM-ARGV', @ARGV);

# ----------------------------------------------------------------------
# Actual basedir, not to be confused with --basedir option
# ----------------------------------------------------------------------

if ( $opt->{srcdir} ) {
  $basedir= $opt->{builddir};
} else {
  $basedir= $opt->{basedir};
}
$basedir= "." if ! $basedir;		# Default

# ----------------------------------------------------------------------
# We can now find my_print_defaults.  This script supports:
#
#   --srcdir=path pointing to compiled source tree
#   --basedir=path pointing to installed binary location
#
# or default to compiled-in locations.
# ----------------------------------------------------------------------

my $print_defaults;

if ( $opt->{srcdir} and $opt->{basedir} )
{
  error($opt,"Specify either --basedir or --srcdir, not both");
}
if ( $opt->{srcdir} )
{
  $opt->{builddir} = $opt->{srcdir} unless $opt->{builddir};
  $print_defaults = "$opt->{builddir}/extra/my_print_defaults";
}
else
{
  $print_defaults = find_in_basedir($opt,"file","my_print_defaults","bin","extra");
}
if ( ! $print_defaults )
{
  $print_defaults='./bin/my_print_defaults';
}

-x $print_defaults or -f "$print_defaults.exe"
  or cannot_find_file($print_defaults);

my $config_file;
my $copy_cfg_file;

# ----------------------------------------------------------------------
# This will be the default config file
# ----------------------------------------------------------------------

my $cnfext = ( $^O =~ m/^(MSWin32|cygwin)$/ ) ? "ini" : "cnf";

$config_file= "$basedir/my.$cnfext";

my $cfg_template= find_in_basedir($opt,"file","my-default.$cnfext",
				  ".", "share","share/mysql","support-files");
-e $cfg_template or cannot_find_file("my-default.$cnfext");

$copy_cfg_file= $config_file;
my $failed_write_cfg= 0;
if (-e $copy_cfg_file)
{
  $copy_cfg_file =~ s/my.$cnfext/my-new.$cnfext/;
  # Too early to print warning here, the user may not notice
}
open (TEMPL, $cfg_template) or error($opt, "Could not open config template $cfg_template");
if (open (CFG, "> $copy_cfg_file"))
{
  while (<TEMPL>)
  {
    # Remove lines beginning with # *** which are template comments
    print CFG $_ unless /^# \*\*\*/;
  }
  close CFG;
}
else
{
  warning($opt,"Could not write to config file $copy_cfg_file: $!");
  $failed_write_cfg= 1;
}
close TEMPL;

# ----------------------------------------------------------------------
# Now we can get arguments from the groups [mysqld] and [mysql_install_db]
# in the my.cfg file, then re-run to merge with command line arguments.
# ----------------------------------------------------------------------

my $print_def_file;
if ( $opt->{'defaults-file'} )
{
  $print_def_file= $opt->{'defaults-file'};
}
else
{
  $print_def_file= $config_file;
}

my @default_options;
my $cmd = quote_options($print_defaults,"--defaults-file=$print_def_file",
                        "mysqld","mysql_install_db");
open(PIPE, "$cmd |") or error($opt,"can't run $cmd: $!");
while ( <PIPE> )
{
  chomp;
  next unless /\S/;
  push(@default_options, $_);
}
close PIPE;
$opt = {};                              # Reset the arguments FIXME ?
parse_arguments($opt, @default_options);
parse_arguments($opt, 'PICK-ARGS-FROM-ARGV', @ARGV);

# ----------------------------------------------------------------------
# Create a random password for root, if requested and implemented
# ----------------------------------------------------------------------

if ( $opt->{'random-passwords'} ) {
  # Add other non-working OS like this: $^O =~ m/^(solaris|linux|freebsd|darwin)$/
  # and maintain "usage()".
  # Issue 1: random password creation
  # Issue 2: confidential file
  if ( $^O =~ m/^(MSWin32|cygwin)$/ ) {
    print "Random password not yet implemented for $^O - option will be ignored\n";
    delete $opt->{'random-passwords'};
  } else {
    ensure_secret_file();
    my $password = generate_random_password();
    if ( $password ) {
      # "true" means "string is non-empty"
      $escaped_password = basic_single_escape($password);
    } else {
      # Whatever the reason (missing "/dev/urandom"), an empty password is bad
      print "Could not generate a random password - not setting one\n";
      delete $opt->{'random-passwords'};
    }
  }
}

# ----------------------------------------------------------------------
# Configure paths to support files
# ----------------------------------------------------------------------

# FIXME $extra_bindir is not used
my ($bindir,$extra_bindir,$mysqld,$pkgdatadir,$mysqld_opt,$scriptdir);

if ( $opt->{srcdir} )
{
  $bindir         = "$basedir/client";
  $extra_bindir   = "$basedir/extra";
  $mysqld         = "$basedir/sql/mysqld";
  $mysqld_opt     = "--language=$opt->{srcdir}/sql/share/english";
  $pkgdatadir     = "$opt->{srcdir}/scripts";
  $scriptdir      = "$opt->{srcdir}/scripts";
}
elsif ( $opt->{basedir} )
{
  $bindir         = "$opt->{basedir}/bin";
  $extra_bindir   = $bindir;
  $mysqld         = find_in_basedir($opt,"file",["mysqld-nt","mysqld"],
                                    "libexec","sbin","bin") ||  # ,"sql"
                    find_in_basedir($opt,"file","mysqld-nt",
                                  "bin");  # ,"sql"
  $pkgdatadir     = find_in_basedir($opt,"dir","fill_help_tables.sql",
                                    "share","share/mysql");  # ,"scripts"
  $scriptdir      = "$opt->{basedir}/scripts";
}
else
{
  $bindir         = './bin';
  $extra_bindir   = $bindir;
  $mysqld         = './bin/mysqld';
  $pkgdatadir     = './share';
  $scriptdir      = './bin';
}

unless ( $opt->{ldata} )
{
  $opt->{ldata} = './data';
}

if ( $opt->{srcdir} )
{
  $pkgdatadir = "$opt->{srcdir}/scripts";
}

# ----------------------------------------------------------------------
# Set up paths to SQL scripts required for bootstrap
# ----------------------------------------------------------------------

my $fill_help_tables     = "$pkgdatadir/fill_help_tables.sql";
my $create_system_tables = "$pkgdatadir/mysql_system_tables.sql";
my $fill_system_tables   = "$pkgdatadir/mysql_system_tables_data.sql";
my $security_commands    = "$pkgdatadir/mysql_security_commands.sql";

foreach my $f ( $fill_help_tables, $create_system_tables, $fill_system_tables, $security_commands )
{
  -f $f or cannot_find_file($f);
}

-x $mysqld or -f "$mysqld.exe" or cannot_find_file($mysqld);
# Try to determine the hostname
my $hostname = hostname();

# ----------------------------------------------------------------------
# Check if hostname is valid
# ----------------------------------------------------------------------

my $resolved;
if ( !$opt->{'cross-bootstrap'} and !$opt->{rpm} and !$opt->{force} )
{
  my $resolveip = "$extra_bindir/resolveip";

  $resolved = `$resolveip $hostname 2>&1`;
  if ( $? != 0 )
  {
    $resolved=`$resolveip localhost 2>&1`;
    if ( $? != 0 )
    {
      error($opt,
            "Neither host '$hostname' nor 'localhost' could be looked up with",
            "$resolveip",
            "Please configure the 'hostname' command to return a correct",
            "hostname.",
            "If you want to solve this at a later stage, restart this script",
            "with the --force option");
    }
    warning($opt,
            "The host '$hostname' could not be looked up with $resolveip.",
            "This probably means that your libc libraries are not 100 % compatible",
            "with this binary MySQL version. The MySQL daemon, mysqld, should work",
            "normally with the exception that host name resolving will not work.",
            "This means that you should use IP addresses instead of hostnames",
            "when specifying MySQL privileges !");
  }
}

# FIXME what does this really mean....
if ( $opt->{'skip-name-resolve'} and $resolved and $resolved =~ /\s/ )
{
  $hostname = (split(' ', $resolved))[5];
}

# ----------------------------------------------------------------------
# Create database directories mysql & test
# ----------------------------------------------------------------------

# FIXME The shell variant uses "mkdir -p":
#  - because it is silent if the target exists, or
#  - because it will cerate the path?
# Path creation is demanded by testers in bug# 14731457, but that might be risky
# in case of typos as this is run by root.
# For now, give an error message:
my $parent = dirname ( $opt->{ldata} );
if ( ! -d $parent ) {
  error($opt,
        "The parent directory for the data directory '$opt->{ldata}' does not exist.",
        "If that path was really intended, please create that directory path and then",
        "restart this script.",
        "If some other path was intended, please use the correct path when restarting this script.");
}

my $opt_user= $opt->{user};
my @pwnam;
if ($opt_user)
{
  if ( $^O =~ m/^(MSWin32|cygwin)$/ )
  {
    warning($opt, "The --user option is not supported on Windows, ignoring");
    $opt_user= undef;
  }
  else
  {
    @pwnam= getpwnam($opt_user);
  }
}

foreach my $dir ( $opt->{ldata}, "$opt->{ldata}/mysql", "$opt->{ldata}/test" )
{
  mkdir($dir, 0700) unless -d $dir;
  if ($opt_user and -w "/")
  {
    chown($pwnam[2], $pwnam[3], $dir)
      or error($opt, "Could not chown directory $dir");
  }
}

push(@args, "--user=$opt->{user}") if $opt->{user};

# ----------------------------------------------------------------------
# Configure mysqld command line
# ----------------------------------------------------------------------

# FIXME use --init-file instead of --bootstrap ?!

my $defaults_option = "";
if ( $opt->{'no-defaults'} )
{
  $defaults_option= "--no-defaults";
}
elsif ( $opt->{'defaults-file'} )
{
  $defaults_option= "--defaults-file=$opt->{'defaults-file'}";
}

my $defaults_extra= "--defaults-extra-file=$opt->{'defaults-extra-file'}"
  if $opt->{'defaults-extra-file'};

my $mysqld_bootstrap = $ENV{MYSQLD_BOOTSTRAP} || $mysqld;
my $mysqld_install_cmd_line = quote_options($mysqld_bootstrap,
                                            $defaults_option,
					    $defaults_extra,
                                            $mysqld_opt,
                                            "--bootstrap",
                                            "--basedir=$basedir",
                                            "--datadir=$opt->{ldata}",
                                            "--log-warnings=0",
                                            "--loose-skip-ndbcluster",
                                            "--max_allowed_packet=8M",
                                            "--default-storage-engine=MyISAM",
                                            "--net_buffer_length=16K",
                                            @args,
                                          );

# ----------------------------------------------------------------------
# Create the system and help tables by passing them to "mysqld --bootstrap"
# ----------------------------------------------------------------------

report_verbose_wait($opt,"Installing MySQL system tables...");

open(SQL, $create_system_tables)
  or error($opt,"can't open $create_system_tables for reading: $!");
open(SQL2, $fill_system_tables)
  or error($opt,"can't open $fill_system_tables for reading: $!");
# FIXME  > /dev/null ?
if ( open(PIPE, "| $mysqld_install_cmd_line") )
{
  print PIPE "use mysql;\n";
  while ( <SQL> )
  {
    # When doing a "cross bootstrap" install, no reference to the current
    # host should be added to the system tables.  So we filter out any
    # lines which contain the current host name.
    next if $opt->{'cross-bootstrap'} and /\@current_hostname/;

    print PIPE $_;
  }
  while ( <SQL2> )
  {
    # When doing a "cross bootstrap" install, no reference to the current
    # host should be added to the system tables.  So we filter out any
    # lines which contain the current host name.
    next if $opt->{'cross-bootstrap'} and /\@current_hostname/;

    print PIPE $_;
  }

  if ( $opt->{'random-passwords'} )
  {
    open(SQL3, $security_commands)
      or error($opt,"can't open $security_commands for reading: $!");
    while ( <SQL3> )
    {
      # using the implicit variable $_ !
      s/ABC123xyz/$escaped_password/e ;  # Replace placeholder by random password
    print PIPE $_;
  }
    close SQL3;
    tell_root_password();
  }

  close PIPE;
  close SQL;
  close SQL2;

  report_verbose($opt,"OK");

  # ----------------------------------------------------------------------
  # Pipe fill_help_tables.sql to "mysqld --bootstrap"
  # ----------------------------------------------------------------------

  report_verbose_wait($opt,"Filling help tables...");
  open(SQL, $fill_help_tables)
    or error($opt,"can't open $fill_help_tables for reading: $!");
  # FIXME  > /dev/null ?
  if ( open(PIPE, "| $mysqld_install_cmd_line") )
  {
    print PIPE "use mysql;\n";
    while ( <SQL> )
    {
      print PIPE $_;
    }
    close PIPE;
    close SQL;

    report_verbose($opt,"OK");
  }
  else
  {
    warning($opt,"HELP FILES ARE NOT COMPLETELY INSTALLED!",
                 "The \"HELP\" command might not work properly");
  }

  report_verbose($opt,"To start mysqld at boot time you have to copy",
                      "support-files/mysql.server to the right place " .
                      "for your system");

  if ( !$opt->{'cross-bootstrap'} )
  {
    # This is not a true installation on a running system.  The end user must
    # set a password after installing the data files on the real host system.
    # At this point, there is no end user, so it does not make sense to print
    # this reminder.
    if ( $opt->{'random-passwords'} ) {
      report($opt,
             "A RANDOM PASSWORD HAS BEEN SET FOR THE MySQL root USER !",
             "You will find that password in '$secret_file'.",
             "",
             "You must change that password on your first connect,",
             "no other statement but 'SET PASSWORD' will be accepted.",
             "See the manual for the semantics of the 'password expired' flag.",
             "",
             "Also, the account for the anonymous user has been removed.",
             "",
             "In addition, you can run:",
             "",
             "  $bindir/mysql_secure_installation",
             "",
             "which will also give you the option of removing the test database.",
             "This is strongly recommended for production servers.",
             "",
             "See the manual for more instructions.");
    } else {
    report($opt,
           "PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !",
           "To do so, start the server, then issue the following commands:",
           "",
           "  $bindir/mysqladmin -u root password 'new-password'",
           "  $bindir/mysqladmin -u root -h $hostname password 'new-password'",
           "",
           "Alternatively you can run:",
           "",
           "  $bindir/mysql_secure_installation",
           "",
           "which will also give you the option of removing the test",
           "databases and anonymous user created by default.  This is",
           "strongly recommended for production servers.",
           "",
           "See the manual for more instructions.");
    }

    if ( !$opt->{rpm} )
    {
      report($opt,
             "You can start the MySQL daemon with:",
             "",
             "  cd " . '.' . " ; $bindir/mysqld_safe &",
             "",
             "You can test the MySQL daemon with mysql-test-run.pl",
             "",
             "  cd mysql-test ; perl mysql-test-run.pl");
    }
    report($opt,
           "Please report any problems at http://bugs.mysql.com/",
           "",
           "The latest information about MySQL is available on the web at",
           "",
           "  http://www.mysql.com",
           "",
           "Support MySQL by buying support/licenses at http://shop.mysql.com");

    if ($copy_cfg_file eq $config_file and !$failed_write_cfg)
    {
      report($opt,
	     "New default config file was created as $config_file and",
	     "will be used by default by the server when you start it.",
	     "You may edit this file to change server settings");
    }
    elsif ($failed_write_cfg)
    {
      warning($opt,
	      "Could not copy config file template $cfg_template to",
	      "$copy_cfg_file, may not have access rights to do so.",
	      "You may want to copy the file manually, or create your own,",
              "it will then be used by default by the server when you start it.");
    }
    else
    {
      warning($opt,
	      "Found existing config file $config_file on the system.",
	      "Because this file might be in use, it was not replaced,",
	      "but was used in bootstrap (unless you used --defaults-file)",
	      "and when you later start the server.",
	      "The new default config file was created as $copy_cfg_file,",
	      "please compare it with your file and take the changes you need.");
    }
    foreach my $cfg ( "/etc/my.$cnfext", "/etc/mysql/my.$cnfext" )
    {
      check_sys_cfg_file ($opt, $cfg);
    }
  }
  exit 0
}
else
{
  error($opt,
        "Installation of system tables failed!",
         "",
        "Examine the logs in $opt->{ldata} for more information.",
        "You can try to start the mysqld daemon with:",
        "$mysqld --skip-grant-tables &",
        "and use the command line tool",
        "$bindir/mysql to connect to the mysql",
        "database and look at the grant tables:",
        "",
        "shell> $bindir/mysql -u root mysql",
        "mysql> show tables",
        "",
        "Try 'mysqld --help' if you have problems with paths. Using --log",
        "gives you a log in $opt->{ldata} that may be helpful.",
        "",
        "The latest information about MySQL is available on the web at",
        "http://www.mysql.com",
        "Please consult the MySQL manual section: 'Problems running mysql_install_db',",
        "and the manual section that describes problems on your OS.",
        "Another information source is the MySQL email archive.",
        "",
        "Please check all of the above before submitting a bug report",
        "at http://bugs.mysql.com/")
}

##############################################################################
#
#  Misc
#
##############################################################################

sub check_sys_cfg_file
{
  my $opt= shift;
  my $fname= shift;

  if ( -e $fname )
  {
    warning($opt,
	    "Default config file $fname exists on the system",
	    "This file will be read by default by the MySQL server",
	    "If you do not want to use this, either remove it, or use the",
	    "--defaults-file argument to mysqld_safe when starting the server");
  }
}

sub report_verbose
{
  my $opt  = shift;
  my $text = shift;

  report_verbose_wait($opt, $text, @_);
  print "\n\n";
}

sub report_verbose_wait
{
  my $opt  = shift;
  my $text = shift;

  if ( $opt->{verbose} or (!$opt->{rpm} and !$opt->{'cross-bootstrap'}) )
  {
    print "$text";
    map {print "\n$_"} @_;
  }
}

sub report
{
  my $opt  = shift;
  my $text = shift;

  print "$text\n";
  map {print "$_\n"} @_;
  print "\n";
}

sub error
{
  my $opt  = shift;
  my $text = shift;

  print "FATAL ERROR: $text\n";
  map {print "$_\n"} @_;
  exit 1;
}

sub warning
{
  my $opt  = shift;
  my $text = shift;

  print "WARNING: $text\n";
  map {print "$_\n"} @_;
  print "\n";
}

# Include dummy lines with patterns that generalized pkgadd script expects

my $_pkgadd_fodder= "
basedir=foo
datadir=bar
";


text:
CHAP Links Library
==================

CHAP Links Library is a web based visualization library.
The library is specially designed to be easy to use, to handle large amounts
of data, and to enable manipulation of the data.
The library consists of Graph, Graph3d, Network, Timeline, and Treegrid.

The tools are developed as
[Google Visualization Charts](http://code.google.com/apis/visualization/documentation/gallery.html)
for Javascript and GWT.

Links Library is part of [CHAP](http://chap.almende.com),
the Common Hybrid Agent Platform.