text:
require 'rallyeif-wrk'
require './lib/testrail-api-master/ruby/testrail.rb'

RecoverableException   = RallyEIF::WRK::RecoverableException if not defined?(RecoverableException)
UnrecoverableException = RallyEIF::WRK::UnrecoverableException
RallyLogger            = RallyEIF::WRK::RallyLogger
XMLUtils               = RallyEIF::WRK::XMLUtils

module RallyEIF
  module WRK

    VALID_TESTRAIL_ARTIFACTS = ['testcase']

    class TestRailConnection < Connection

      attr_reader   :testrail,  :tr_project
      attr_reader   :all_suites,  :all_sections
      attr_reader   :rally_story_field_for_plan_id
      attr_accessor :project,  :section_id

      #
      # Global info that will be obtained from the TestRail system.
      #
      @testrail           = '' # The connecton packet used to make request.
      @tr_project         = {} # Information about project in config file.
      @all_suites         = {} # All suites in the project.
      @all_sections       = {} # All sections in the project
      @tr_cust_fields_tc  = {} # Hash of custom fields on test case.
      @tr_cust_fields_tcr = {} # Hash of custom fields on test case result.
      @tr_fields_tc       = {} # Hash of standard fields on test case.
      @tr_fields_tcr      = {} # Hash of standard fields on test case result.
      @tr_user_info       = {} # TestRail information about user in config file.

      def initialize(config=nil)
        super()
        read_config(config) if !config.nil?
      end

      def read_config(config)
        super(config)
        @url       = XMLUtils.get_element_value(config, self.conn_class_name.to_s, "Url")
        @project   = XMLUtils.get_element_value(config, self.conn_class_name.to_s, "Project")
        # yes, it's weird to put a field name from a Rally artifact into the other connection
        # but this keeps us from overriding/monkey-patching the Rally connection class
        @rally_story_field_for_plan_id = XMLUtils.get_element_value(config, self.conn_class_name.to_s, "RallyStoryFieldForPlanID", false)
        @section_id = nil
        @cfg_suite_ids = XMLUtils.get_element_value(config, self.conn_class_name.to_s, "SuiteIDs", false)
      end

      def name()
        return "TestRail"
      end

      def version()
        return RallyEIF::TestRail::Version
      end

      def self.version_message()
        version_info = "#{RallyEIF::TestRail::Version}-#{RallyEIF::TestRail::Version.detail}"
        return "TestRailConnection version #{version_info}"
      end

      def get_backend_version()
        return "%s %s" % [name, version]
      end
#---------------------#
      def connect()
        RallyLogger.debug(self, "********************************************************")
        RallyLogger.debug(self, "Connecting to TestRail:")
        RallyLogger.debug(self, "  Url               : #{@url}")
        RallyLogger.debug(self, "  Username          : #{@user}")
        RallyLogger.debug(self, "  Connector Name    : #{name}")
        RallyLogger.debug(self, "  Connector Version : #{version}")
        RallyLogger.debug(self, "  Artifact Type     : #{artifact_type}")
        RallyLogger.debug(self, "*******************************************************")

        #
        # Set up a connection packet
        #
        @testrail          = ::TestRail::APIClient.new(@url)
        @testrail.user     = @user
        @testrail.password = @password

        #
        # PROJECTS:  Build a hash of TestRail projects
        #            (not necessary to have them all, but we have to find ours anyway)
        #
        uri = 'get_projects'
        all_projects = @testrail.send_get(uri)

        if all_projects.length < 1
          raise UnrecoverableException.new("Could not find any projects in TestRail.", self)
        end

        # We should find one and only project name matching the one we are looking for.
        found_projects = []
        all_projects.each do |proj|
          if proj['name'] == @project
            found_projects.push proj
            cdate = ''
            if proj['is_completed'] == true
              cdate = "(on #{Time.at(proj['completed_on']).to_datetime})" # pretty date
            end
            RallyLogger.info(self,"Found project: P#{proj['id']}")
            RallyLogger.info(self,"         name: #{proj['name']} (id=#{proj['id']})")
            RallyLogger.info(self,"          url: #{proj['url']}")
            RallyLogger.info(self,"   suite_mode: #{proj['suite_mode']} (1: single suite, 2: 1+baselines, 3: multiple suites)")
            RallyLogger.info(self," is_completed: #{proj['is_completed']} #{cdate}")
          end
        end
        if found_projects.length != 1
          raise UnrecoverableException.new("Found '#{found_projects.length}' projects named '#{@project}'; the connector needs one and only one", self)
        end
        @tr_project = found_projects[0].to_hash

        # Build suite info...
        @tr_project_sm = @tr_project['suite_mode']
        @tr_suite_ids = Array.new
        @all_suites = get_all_suites()
        RallyLogger.info(self,"Found '#{@all_suites.length}' suites in above project:")
        @all_suites.each do |next_suite|
          RallyLogger.info(self,"\tSuite S#{next_suite['id']}: name=#{next_suite['name']}")
          @tr_suite_ids.push(next_suite['id'])
        end
        # Handle config file: <SuiteIDs>1,2,3,4</SuiteIDs>
        if !@cfg_suite_ids.nil?
          suite_ids = @cfg_suite_ids.split(',')     # Make array from one string
          suite_ids.map!{ |s| s.gsub(/^[sS]/, '') } # Remove potential leading 'S' (i.e. ["S1", "S2", "S3", ...])
          suite_ids.map!{|s|s.to_i}                 # Convert array of strings to integers
          unknown_ids = suite_ids - @tr_suite_ids   # Did they specify any we did not find?
          if !unknown_ids.empty?
            raise UnrecoverableException.new("Found unknown ID(s) in config file <SuiteIDs> tag: '#{unknown_ids}'", self)
          end

          new_list = Array.new        # Make a new list of suites
          @all_suite_ids = Array.new  # Keep a list of suite IDs
          @all_suites.each do |next_suite|
            if suite_ids.include?(next_suite['id'])
              new_list.push(next_suite)
              @all_suite_ids.push(next_suite['id'])
            end
          end
          @all_suites = new_list
          mesg = 'be limited to suites specified' # For logger msg below
        else
          @all_suite_ids = @tr_suite_ids
          mesg = 'include all suites found'
        end
        RallyLogger.debug(self, "Future searches will #{mesg}: '#{@all_suite_ids}'")

        # Build section info...
        @tr_section_ids = Array.new
        @all_sections = get_all_sections()
        RallyLogger.debug(self, "Found '#{@all_sections.length}' sections")
        @all_sections.each do |next_section|
          RallyLogger.debug(self, "\tid='#{next_section['id']}', suite_id='#{next_section['suite_id']}' name='#{next_section['name']}'")
          @tr_section_ids.push(next_section['id'])
        end

        #
        # CUSTOM FIELDS:  Build a hash of custom fields for the given <Artifactype>.
        # Each entry:  {'system_name' => ['name', 'label', 'type_id', [ProjIDs]}
        #
        type_ids = ['?Unknown?-0',  # 0
                    'String',       # 1
                    'Integer',      # 2
                    'Text',         # 3
                    'URL',          # 4
                    'Checkbox',     # 5
                    'Dropdown',     # 6
                    'User',         # 7
                    'Date',         # 8
                    'Milestone',    # 9
                    'Steps',        # 10
                    '?Unknown?-11', # 11
                    'Multi-select'] # 12
        case @artifact_type.to_s
        when 'testcase'
          begin
            uri = 'get_case_fields'
            cust_fields = @testrail.send_get(uri)
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
            RallyLogger.warning(self, "\t#{ex.message}")
            raise UnrecoverableException.new("\tFailed to retrieve Test Case custom field names", self)
          end

          @tr_cust_fields_tc  = {} # Hash of custom fields on test case.
          cust_fields.each do |item|
            # Ignore the custom field if it is not unassigned to any project...
            next if item['configs'] == []

            # Is this custom field global (for all projects)?
            if item['configs'][0].to_hash['context']['is_global'] == true
              # nil means good for all projects
              pids = nil
            else
              # not global, save the list of project IDs
              pids = item['configs'][0].to_hash['context']['project_ids']
            end
            @tr_cust_fields_tc[item['system_name']] =  [item['name'],  item['label'],  item['type_id'],  pids]
          end

        when 'testrun'
          # No way to get fields.

        when 'testplan'
          #

        when 'testsuite'
          #

        when 'testsection'
          #

        when 'testresult'
          begin
            uri = 'get_result_fields'
            cust_fields = @testrail.send_get(uri)
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
            RallyLogger.warning(self, "\t#{ex.message}")
            raise UnrecoverableException.new("\tFailed to retrieve Test Result custom field names", self)
          end

          @tr_cust_fields_tcr  = {} # Hash of custom fields on test case.
          cust_fields.each do |item|
            # Ignore the custom field if it is not unassigned to any project...
            next if item['configs'] == []

            # Is this custom field global (for all projects)?
            if item['configs'][0].to_hash['context']['is_global'] == true
              # nil means good for all projects
              pids = nil
            else
              # not global, save the list of project IDs
              pids = item['configs'][0].to_hash['context']['project_ids']
            end
            @tr_cust_fields_tcr[item['system_name']] = [item['name'],  item['label'],  item['type_id'], pids]
          end

        else
          RallyLogger.error(self, "Unrecognize value for <ArtifactType> '#{@artifact_type}' (msg1)")
        end

        #
        # STANDARD FIELDS:  Build hash of Test Case standard fields
        #                   (done manually since there is no API method to get them).
        case @artifact_type.to_s

        when 'testcase'    # Field-name          Type (1=String, 2=Integer)
          @tr_fields_tc = { 'created_by'        => 2,
                            'created_on'        => 2,
                            'estimate'          => 1,
                            'estimate_forecast' => 1,
                            'id'                => 2,
                            'milestone_id'      => 2,
                            'priority_id'       => 2,
                            'refs'              => 1,
                            'section_id'        => 2,
                            'suite_id'          => 2,
                            'title'             => 1,
                            'type_id'           => 2,
                            'updated_by'        => 2,
                            'updated_on'        => 2}

        when 'testresult' #  Field-name          Type (1=String, 2=Integer)
          @tr_fields_tcr = {'assignedto_id'     => 2,
                            'comment'           => 1,
                            'created_by'        => 2,
                            'created_on'        => 2,
                            'defects'           => 1,
                            'elapsed'           => 2,
                            'id'                => 2,
                            'status_id'         => 2,
                            'test_id '          => 2,
                            'version'           => 1}

        when 'testplan'#  Field-name          Type (1=String, 2=Integer, 3=array, 4=bool)
          @tr_fields_tp =  {'assignedto_id'         => 2,
                            'blocked_count'         => 2,
                            'completed_on'          => 2,
                            'created_by'            => 2,
                            'created_on'            => 2,
                            'custom_status?_count'  => 2,
                            'description'           => 1,
                            'entries'               => 3,
                            'failed_count'          => 2,
                            'id'                    => 2,
                            'is_completed'          => 4,
                            'milestone_id'          => 2,
                            'name'                  => 1,
                            'passed_count'          => 2,
                            'project_id'            => 2,
                            'retest_count'          => 2,
                            'untested_count'        => 2,
                            'url'                   => 1}
        when 'testrun'
        when 'testsuite'
        when 'testsection'

        else
          RallyLogger.error(self, "Unrecognized value for <ArtifactType> '#{@artifact_type}' (msg2)")
        end

        #
        # USER INFO:  Request info for the user listed in config file
        #
        begin
          uri = "get_user_by_email&email=#{@user}"
          @tr_user_info = @testrail.send_get(uri)
          RallyLogger.debug(self, "User information retrieve successfully for '#{@user}'")
        rescue Exception => ex
          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
          RallyLogger.warning(self, "\t#{ex.message}")
          raise UnrecoverableException.new("\tFailed to retrieve information for <User> '#{@user}'", self)
        end

        return @testrail

      end # 'def connect()'
#---------------------#
      def add_run_to_plan(testrun,testplan)
        RallyLogger.debug(self, "Preparing to add testrun: '#{testrun}'")
        RallyLogger.debug(self, "             to testplan: '#{testplan}'")
        begin
          uri = "add_plan_entry/#{testplan['id']}"
          extra_fields = { 'suite_id' => testrun['suite_id'], 'runs' => [testrun] }
          new_plan_entry = @testrail.send_post(uri, extra_fields)
          RallyLogger.debug(self, "New plan entry: '#{new_plan_entry}'")
        rescue Exception => ex
          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_post(#{uri}, #{extra_fields})':")
          RallyLogger.warning(self, "\t#{ex.message}")
          raise UnrecoverableException.new("\tFailed to add TestRun '#{testrun['id']}' to TestPlan '#{testplan['id']}'", self)
        end
        return new_plan_entry
      end
#---------------------#
      def create_internal(int_work_item)
#        if @all_sections.empty?
#          section_id = 1
#        else
#          section_id = @all_sections[0]['id'] # put in first section
#        end
#        if @all_suites.empty?
#          suite_id = 0
#        else
#          suite_id = @all_suites[0]['id'] # put in first suite
#        end

        begin
          case @artifact_type.to_s.downcase
          when 'testcase'
            section_id = int_work_item['section_id']
            RallyLogger.debug(self,"Preparing to create a TestRail '#{@artifact_type}' in Section '#{section_id}'")
            uri = "add_case/#{section_id}"
            new_item = @testrail.send_post(uri, int_work_item)
            gui_id = 'C' + new_item['id'].to_s # How it appears in the GUI
            extra_info = ''
            #RallyLogger.debug(self,"We just created TestRail '#{@artifact_type}' object #{gui_id}")

          when 'testrun'
            suite_id = int_work_item['suite_id']
            RallyLogger.debug(self,"Preparing to create a TestRail '#{@artifact_type}' in Suite 'S#{suite_id}'")
            uri = "add_run/#{@tr_project['id']}&suite_id=#{suite_id}"
            new_item = @testrail.send_post(uri, int_work_item)
            gui_id = 'R' + new_item['id'].to_s # How it appears in the GUI
            extra_info = ''

          when 'testplan'
            RallyLogger.debug(self,"Preparing to create a TestRail '#{@artifact_type}'")
            uri = "add_plan/#{@tr_project['id']}"
            new_item = @testrail.send_post(uri, int_work_item)
            gui_id = 'R' + new_item['id'].to_s # How it appears in the GUI

            # Build a string of info about entries created (for log file)
            str1 = ''
            new_item['entries'].each_with_index do |e,ndx|
              if ndx == 0
                str1 = new_item['entries'].length.to_s + ' entries:('
              else
                str1 = str1 + ','
              end
              str1 = str1 + e['id'].to_s
              str1 = str1 + ')' if ndx == new_item['entries'].length-1
            end

            # Build a string info about runs created (for log file)
            str2 = ''
            new_item['entries'].each_with_index do |e,ndx|
              e['runs'].each_with_index do |r,ndx|
                if ndx == 0
                  str2 = str2 + ' runs:('
                else
                  str2 = str2 + ','
                end
                str2 = str2 + r['id'].to_s
                str2 = str2 + ')' if ndx == e['runs'].length-1
              end
            end
            extra_info = "; #{str1}; #{str2}"

          when 'testsuite'
            RallyLogger.debug(self,"Preparing to create a TestRail 'testsuite'")
            uri = "add_suite/#{@tr_project['id']}"
            new_item = @testrail.send_post(uri, int_work_item)
                  # Returns:
                  #       {"id"=>97,
                  #        "name"=>"Suite '1' of '5'",
                  #        "description"=>"One of JPKole's test suites.",
                  #        "project_id"=>55,
                  #        "is_master"=>false,
                  #        "is_baseline"=>false,
                  #        "is_completed"=>false,
                  #        "completed_on"=>nil,
                  #        "url"=>"https://tsrally.testrail.com/index.php?/suites/view/97"}
            gui_id = 'S' + new_item['id'].to_s # How it appears in the GUI
            extra_info = ''

          when 'testsection'
            RallyLogger.debug(self,"Preparing to create a TestRail 'testsection'")
            uri = "add_section/#{@tr_project['id']}"
            new_item = @testrail.send_post(uri, int_work_item)
                  # Returns:
            gui_id = new_item['id'].to_s # How it appears in the GUI
            extra_info = ''

          when 'testresult'
            # Hardcode these until we understand more...
            run_id  = 1
            case_id = 2

            run_id = int_work_item['run_id'] || run_id
            case_id = int_work_item['case_id'] || case_id
            RallyLogger.debug(self,"Preparing to create a TestRail '#{@artifact_type}' for run_id='R#{run_id}', case_id='T#{case_id}'")
            uri = "add_result_for_case/#{run_id}/#{case_id}"
            new_item = @testrail.send_post(uri, int_work_item)
            gui_id = "(id='#{new_item['id']}' test_id='#{new_item['test_id']}')"
            extra_info = ''

          else
            raise UnrecoverableException.new("Unrecognized value for <ArtifactType> '#{@artifact_type}' (msg2)", self)
          end
        rescue RuntimeError => ex1
          RallyLogger.debug(self,"Runtime error has occurred")
          raise RecoverableException.copy(ex1, self)
        rescue Exception => ex2
          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API during 'send_post'")
          RallyLogger.warning(self, "\targ1: '#{uri}'")
          RallyLogger.warning(self, "\targ2: '#{int_work_item})'")
          RallyLogger.warning(self, "\tmsg : '#{ex2.message}'")
          raise RecoverableException.copy(ex2, self)
        end
        RallyLogger.debug(self,"Created TestRail '#{@artifact_type}' number '#{gui_id}'#{extra_info}")
        return new_item
      end
#---------------------#
      def delete(item)
        begin
          case @artifact_type.to_s.downcase
          when 'testcase'
            uri = "delete_case/#{item['id']}"
            retval = @testrail.send_post(uri,nil)
          when 'testrun'
            uri = "delete_run/#{item['id']}"
            retval = @testrail.send_post(uri,nil)
          when 'testplan'
            uri = "delete_plan/#{item['id']}"
            retval = @testrail.send_post(uri,nil)
          when 'testsuite'
            uri = "delete_suite/#{item['id']}"
            retval = @testrail.send_post(uri,nil)
          when 'testsection'
            # Don't try to delete it unless it exist.
            get_all_sections().each do |next_section|
              uri = nil
              if next_section['id'] == item['id']
                uri = "delete_section/#{item['id']}"
                retval = @testrail.send_post(uri,nil)
                break
              end
            end
            if uri.nil?
              RallyLogger.debug(self,"NOTE: TestRail section '#{item['id']}' appears to be already deleted; ignored")
            end
          when 'testresult'
            # ToDo: How to delete a Result?  Not in documentation?
            uri = 'n/a'
            RallyLogger.debug(self,"NOTE: TestRail has no API for deleting a 'testresult'; ignored")
          else
            raise UnrecoverableException.new("Unrecognize value for <ArtifactType> '#{@artifact_type}' (msg2)", self)
          end
        rescue Exception => ex
          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_post(#{uri}, nil)':\n")
          RallyLogger.warning(self, "\t#{ex.message}")
          raise RecoverableException.new("\tFailed to delete '#{@artifact_type}'; id='#{item['id']}'", self)
        end
        return nil
      end
#---------------------#
      def disconnect()
        RallyLogger.info(self,"Would disconnect at this point if we needed to")
      end
#---------------------#
      def field_exists? (field_name)

        case @artifact_type.to_s
        when 'testcase'
          if (!@tr_cust_fields_tc.member? field_name.to_s.downcase) && (!@tr_fields_tc.member? field_name.to_s.downcase)
            if (!@tr_cust_fields_tc.member? 'custom_' + field_name.to_s.downcase)
              RallyLogger.error(self, "TestRail field '#{field_name.to_s}' not a valid field name for Test Cases in project '#{@project}'")
              RallyLogger.debug(self, "  available fields (standard): #{@tr_fields_tc}")
              RallyLogger.debug(self, "  available fields (custom): #{@tr_cust_fields_tc}")
              return false
            end
          end

        when 'testrun'
          raise UnrecoverableException.new('Unrecognize logic: field_exists? on "testrun"?', self)

        when 'testresult'

          special_fields = ['_testcase','_test']
          if (!@tr_cust_fields_tcr.member? field_name.to_s.downcase) && (!@tr_fields_tcr.member? field_name.to_s.downcase)
            if (!@tr_cust_fields_tcr.member? 'custom_' + field_name.to_s.downcase )  && ( !special_fields.member? field_name.to_s.downcase )
              RallyLogger.error(self, "TestRail field '#{field_name.to_s}' not a valid field name for Test Results in project '#{@project}'")
              RallyLogger.debug(self, "  available fields (standard): #{@tr_fields_tcr}")
              RallyLogger.debug(self, "  available fields (custom): #{@tr_cust_fields_tcr}")
              return false
            end
          end

        else
          raise UnrecoverableException.new("Unrecognize value for <ArtifactType> '#{@artifact_type}' (msg3)", self)
        end

        return true
      end
#---------------------#
      def filter_out_already_connected(artifacts)
        #
        # Find only the new artifacts (i.e. reject those with a populated external_id field)
        #
        matching_artifacts = []
        rejected_artifacts = []
        artifacts.each do |artifact|
          if artifact["custom_#{@external_id_field.downcase}"].nil?
            matching_artifacts.push(artifact)
          else
            rejected_artifacts.push(artifact)
          end
        end
        return matching_artifacts,rejected_artifacts
      end
#---------------------#
      def find(item, type=@artifact_type)
        begin
          case type.to_s.downcase
          when 'testcase'
            uri = "get_case/#{item['id']}"
            found_item = @testrail.send_get(uri)

          when 'test'
            uri = "get_test/#{item['id']}"
            found_item = @testrail.send_get(uri)

          when 'testrun'
            raise UnrecoverableException.new('Unimplemented logic: find on "testrun"...', self)

          when 'testresult'
            raise UnrecoverableException.new('Unimplemented logic: find on "testresult"...', self)

          else
            raise UnrecoverableException.new("Unrecognize value for <ArtifactType> '#{type}' (msg4)", self)
          end
        rescue Exception => ex
          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':\n")
          RallyLogger.warning(self, "\t#{ex.message}")
          raise RecoverableException.copy("\tFailed to find the '#{type}' artifact", self)
        end

        return found_item
      end
#---------------------#
      # find_by_external_id is forced from inheritance
      def find_by_external_id(external_id)
        case @artifact_type.to_s
        when 'testcase'
          begin
            uri = "get_cases/#{@tr_project['id']}"
            artifact_array = @testrail.send_get(uri)
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':\n")
            RallyLogger.warning(self, "\t#{ex.message}")
            raise RecoverableException.new("\tFailed to find testcases with populated <ExternalID> field", self)
          end

        when 'testrun'
          raise UnrecoverableException.new('Unimplemented logic: find_by_external_id on "testrun"', self)

        when 'testresult'
          raise UnrecoverableException.new('Unimplemented logic: find_by_external_id on "testresult"', self)

        else
          raise UnrecoverableException.new("Unrecognize value for <ArtifactType> '#{@artifact_type}' (msg5)", self)
        end

        matching_artifacts = []
        ids = []
        artifact_array.each do |artifact|
          if artifact["custom_#{@external_id_field.downcase}"] == external_id
            matching_artifacts.push(artifact)
            ids.push get_id_value(artifact)
          end
        end

        if matching_artifacts.length < 1
          raise RecoverableException.new("No artifacts found with <ExternalID> = '#{external_id}'", self)
          return nil
        end

        if matching_artifacts.length > 1
          RallyLogger.warning(self, "More than one artifact found with <ExternalID> = '#{external_id}' (IDs=#{ids})")
          raise RecoverableException.new("More than one artifact found with <ExternalID> = '#{external_id}' (IDs=#{ids})", self)
          return nil
        end

        return matching_artifacts.first
      end
#---------------------#
      def find_new()
        RallyLogger.info(self, "Find new TestRail '#{@artifact_type}' objects")

        case @artifact_type.to_s.downcase
        when 'testcase'
          matching_artifacts = find_new_testcases()
        when 'testrun'
          raise UnrecoverableException.new('Unimplemented logic: find_new on "testrun"...', self)

        when 'testresult'
          matching_artifacts = find_test_results()

        else
          raise UnrecoverableException.new("Unrecognized value for <ArtifactType> '#{@artifact_type}' (msg3)", self)
        end

        RallyLogger.info(self, "Found '#{matching_artifacts.length}' new TestRail '#{@artifact_type}' objects")

        return matching_artifacts
      end
#---------------------#
      def find_new_testcases()
        matching_artifacts = []
        case @tr_project_sm
        when 1 # single suite
          # fall thru

        when 2 # 1+baselines
          # fall thru

        when 3 # 3: multiple suites
          if @all_suites.nil?
            raise UnrecoverableException.new("No suites found? (can't continue)", self)
          end
          # fall thru

        else
          raise UnrecoverableException.new("Invalid value for suite_mode (#{@tr_project_sm})", self)
        end

        RallyLogger.info(self, "Find new TestRail '#{@artifact_type}' objects in suite(s) '#{@all_suite_ids}'")
        @all_suites.each do |next_suite|
          begin
            uri = "get_cases/#{@tr_project['id']}&suite_id=#{next_suite['id']}"
            returned_artifacts = @testrail.send_get(uri)
            RallyLogger.debug(self, "Found '#{returned_artifacts.length}' testcases in suite id '#{next_suite['id']}'")
            kept,rejected = filter_out_already_connected(returned_artifacts)
            RallyLogger.debug(self, "Filtered out '#{rejected.length}' of those because they are 'already connected'")
            matching_artifacts = matching_artifacts + kept
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
            RallyLogger.warning(self, "\t#{ex.message}")
            raise UnrecoverableException.new("\tFailed to find new TestRail testcases", self)
          end
        end
        return matching_artifacts
      end
#---------------------#
      def find_test_for_run(run_id)
        tests = []
        uri = "get_tests/#{run_id}"
        RallyLogger.info(self, "Doing send_get '#{uri}'")
        begin
          tests = @testrail.send_get(uri)
        rescue Exception => ex
          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
          RallyLogger.warning(self, "\t#{ex.message}")
          raise UnrecoverableException.new("\tFailed to find any Tests", self)
        end
        return tests
      end
#---------------------#
      # find and populated related data for plans
      def find_test_plans()
        begin
          uri1 = "get_plans/#{@tr_project['id']}"
          plan_shells = @testrail.send_get(uri1)
          plans = []
          plan_shells.each do |plan_shell|
            uri2 = "get_plan/#{plan_shell['id']}"
            plan = @testrail.send_get(uri2)
            runs = []
            tests = []
            run_ids = []

            entries = plan['entries'] || []
            entries.each do |entry|
              run_shells = entry['runs']
              run_shells.each do |run_shell|
                uri3 = "get_run/#{run_shell['id']}"
                run = @testrail.send_get(uri3)
                runs.push(run)

                uri4 = "get_tests/#{run_shell['id']}"
                test = @testrail.send_get(uri4)
                tests.push(test)

                run_ids.push(run_shell['id'])
              end
            end
            plan['runs'] = runs
            plan['tests'] = tests
            plan['run_ids'] = run_ids
            plans.push(plan)
          end
        rescue Exception => ex
          raise UnrecoverableException.new("Failed to find any Test Plans.\n TestRail api returned:#{ex.message}", self)
        end

        return plans
      end
#---------------------#
      def find_test_results()
        # have to iterate over the runs
        runs, run_ids = find_test_runs()
        RallyLogger.info(self, "Find new TestRail '#{@artifact_type}' objects for run_id(s) '#{run_ids}'")

        test_results = []
        runs.each do |run|
          begin
            run_id = run['id']
            uri = "get_results_for_run/#{run_id}"
            results = @testrail.send_get(uri)
            filtered_results,rejected_results = filter_out_already_connected(results)
            test_results = test_results.concat(filtered_results)
            # matching candidates are filtered below...
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
            RallyLogger.warning(self, "\t#{ex.message}")
            raise UnrecoverableException.new("\tFailed to find new Test Results", self)
          end
        end

        # pack test result with referenced test and test case
        RallyLogger.debug(self,"Unfiltered test case result set count:  #{test_results.length}")
        RallyLogger.debug(self,"Filtering out test case results that have an unconnected test case")

        filtered_test_results = []
        test_results.each do |test_result|
          test = find({ 'id' => test_result['test_id'] }, 'test')
          test_result['_test'] = test
          test_case = find({ 'id' => test['case_id'] }, 'testcase')
          test_result['_testcase'] = test_case
          # we only care about results where the test_case is also connected to Rally
          if !test_case["custom_#{@external_id_field.downcase}"].nil?
            filtered_test_results.push(test_result)
          end
        end

        return filtered_test_results
      end
#---------------------#
      def find_test_runs()
        plans = find_test_plans()
        runs = []
        run_ids = []
        plans.each do |plan|
          runs = runs.concat(plan['runs'])
          run_ids = run_ids.concat(plan['run_ids'])
        end

#        begin
#          uri = "get_runs/#{@tr_project['id']}"
#          orphan_runs = @testrail.send_get(uri)
#          runs = orphan_runs.concat(runs)
#        rescue Exception => ex
#          RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
#          RallyLogger.warning(self, "\t#{ex.message}")
#          raise UnrecoverableException.new("\tFailed to find any Test Runs", self)
#        end

        return runs,run_ids
      end
#---------------------#
      def find_updates(reference_time)
        RallyLogger.info(self, "Find updated TestRail '#{@artifact_type}' objects since '#{reference_time}'")
        unix_time = reference_time.to_i
        artifact_array = []
        case @artifact_type.to_s
        when 'testcase'
          artifact_array = find_updates_testcase(reference_time)
        when 'testrun'
          raise UnrecoverableException.new('Not available for "testrun": find_updates...', self)

        when 'testresult'
          raise UnrecoverableException.new('Not available for "testresult": find_updates...', self)

        else
          raise UnrecoverableException.new("Unrecognize value for <ArtifactType> '#{@artifact_type}' (msg6)", self)
        end
        RallyLogger.info(self, "Found '#{artifact_array.length}' updated '#{@artifact_type}' objects in '#{name()}'")

        return artifact_array
      end
#---------------------#
      def find_updates_testcase(reference_time)
        RallyLogger.info(self, "Find updated TestRail '#{@artifact_type}' objects since '#{reference_time}'")
        unix_time = reference_time.to_i
        matching_artifacts = []

        @all_suites.each do |next_suite|
          begin
            uri = "get_cases/#{@tr_project['id']}&suite_id=#{next_suite['id']}&updated_after=#{unix_time}"
            result_array = @testrail.send_get(uri)
            # throw away those without extid
            result_array.each do |item|
              if item["custom_#{@external_id_field.downcase}"] != nil
                matching_artifacts.push(item)
              end
            end
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
            RallyLogger.warning(self, "\t#{ex.message}")
            raise UnrecoverableException.new("Failed trying to find testcases for update", self)
          end
        end

        return matching_artifacts
      end
#---------------------#
      def get_all_sections()
        case @tr_project_sm
          when 1 # single suite
          when 2 # 1+baselines
            @all_suites = [{'id' => @tr_project['id']}]
          when 3 # 3: multiple suites
            if @all_suites.nil?
              raise UnrecoverableException.new("No suites found? (can't continue)", self)
            end
          else
            raise UnrecoverableException.new("Invalid value for suite_mode (#{@tr_project_sm})", self)
        end
        @all_sections = Array.new
        @all_suites.each do |next_suite|
          uri = "get_sections/#{@tr_project['id']}&suite_id=#{next_suite['id']}"
          begin
            sections = @testrail.send_get(uri)
          rescue Exception => ex
            RallyLogger.warning(self, "EXCEPTION occurred on TestRail API 'send_get(#{uri})':")
            RallyLogger.warning(self, "\t#{ex.message}")
          end
          @all_sections.push(sections)
        end
        return @all_sections.first || {}
      end
#---------------------#
      def get_all_suites()
        uri = "get_suites/#{@tr_project['id']}"
        @all_suites = @testrail.send_get(uri)
        return @all_suites
      end
#---------------------#
#      def get_default_section_id()
#RallyLogger.debug(self,"JPKdebug: #{@tr_project['id']}")
#RallyLogger.debug(self,"JPKdebug: get_sections/#{@tr_project['id']}")
#        begin
#          returned_artifacts = @testrail.send_get("get_sections/#{@tr_project['id']}")
#        rescue Exception => ex
#          RallyLogger.warning(self, "Cannot find sections: #{ex.message}")
#        end
#
#        if returned_artifacts.nil?
#          return {'id' => -1}
#        else
#          RallyLogger.debug(self, "Found '#{returned_artifacts.length}' sections:")
#          returned_artifacts.each do |sec|
#            RallyLogger.debug(self, "\tid=#{sec['id']},  suite_id=#{sec['suite_id']},  name=#{sec['name']}")
#          end
#RallyLogger.debug(self,"JPKdebug: returned_artifacts.class=#{returned_artifacts.class}")
##RallyLogger.debug(self,"JPKdebug: returned_artifacts.length=#{returned_artifacts.length}")
#          return returned_artifacts.first || {'id' => -1}
#        end
#      end
#---------------------#
      # This method will hide the actual call of how to get the id field's value
      def get_id_value(artifact)
        return get_value(artifact,'id')
      end
#---------------------#
      def get_object_link(artifact)
        # We want:  "<a href='https://<TestRail server>/<Artifact ID>'>link</a>"
        linktext = artifact[@id_field] || 'link'
        it = "<a href='https://#{@url}/#{artifact['id']}'>#{linktext}</a>"
        return it
      end
#---------------------#
      def get_value(artifact,field_name)
        return artifact["#{field_name.downcase}"]
      end
#---------------------#
      def pre_create(int_work_item)
        return int_work_item
      end
#---------------------#
      def update_external_id_fields(artifact, external_id, end_user_id, item_link)
        if @artifact_type.to_s.downcase == "testresult"
          return artifact
        end

        new_fields = {}
        if !external_id.nil?
          sys_name = 'custom_' + @external_id_field.to_s.downcase
          new_fields[sys_name] = external_id
          RallyLogger.debug(self, "Updating TestRail item <ExternalIDField>: '#{sys_name}' to '#{external_id}'")
        end

        # Rally gives us a full '<a href=' tag
        if !item_link.nil?
          url_only = item_link.gsub(/.* href=["'](.*?)['"].*$/, '\1')
          if !@external_item_link_field.nil?
            sys_name = 'custom_' + @external_item_link_field.to_s.downcase
            new_fields[sys_name] = url_only
            RallyLogger.debug(self, "Updating TestRail item <CrosslinkUrlField>: '#{sys_name}' to '#{url_only}'")
          end
        end

        if !@external_end_user_id_field.nil?
          sys_name = 'custom_' + @external_end_user_id_field.to_s.downcase
          new_fields[sys_name] = end_user_id
          RallyLogger.debug(self, "Updating TestRail item <ExternalEndUserIDField>: '#{sys_name}' to '#{end_user_id}'")
        end

        updated_item = update_internal(artifact, new_fields)
        return updated_item
      end
#---------------------#
      def update_internal(artifact, new_fields)
        #artifact.update_attributes int_work_item
        case @artifact_type.to_s.downcase
        when 'testcase'
          all_fields = artifact
          all_fields.merge!(new_fields)
          uri = "update_case/#{artifact['id']}"
          updated_item = @testrail.send_post(uri, all_fields)

        when 'testrun'
          all_fields = artifact
          all_fields.merge!(new_fields)
          uri = "update_run/#{artifact['id']}"
          updated_item = @testrail.send_post(uri, all_fields)

        when 'testresult'
          raise UnrecoverableException.new('Unimplemented logic: update_internal on "testresult"...', self)

        else
          raise UnrecoverableException.new("Unrecognize value for <ArtifactType> '#{@artifact_type}' (msg7)", self)
        end
        return updated_item
      end
#---------------------#
      def validate
        status_of_all_fields = true  # Assume all fields passed

        #sys_name = 'custom_' + @external_id_field.to_s.downcase
        if !field_exists?(@external_id_field)
          status_of_all_fields = false
          RallyLogger.error(self, "TestRail <ExternalIDField> '#{@external_id_field}' does not exist")
        end

        if @id_field
          if !field_exists?(@id_field)
            status_of_all_fields = false
            RallyLogger.error(self, "TestRail <IDField> '#{@id_field}' does not exist")
          end
        end

        if @external_end_user_id_field
          if !field_exists?(@external_end_user_id_field)
            status_of_all_fields = false
            RallyLogger.error(self, "TestRail <ExternalEndUserIDField> '#{@external_end_user_id_field}' does not exist")
          end
        end

        return status_of_all_fields
      end
#---------------------#
    end
  end
end


text:
layout: post
title: "cmake parameters"
date:   2016-06-24 00:00 IST
categories: cmake
tags: cmake
comments: true
analytics: true
---

<span/>

## 1. -B
`-B <package directory>`
 override/define CPACK_PACKAGE_DIRECTORY

`# cmake . -B./build-cmake/Debug/obj`

## 2. `cmake --build <dir> [<options>] [-- <build-tool-options>...]`
`cmake --build ./path-to-obj --target target_name -- -j4`

If you use `make`, cmake will send `-j4` to `make`.

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const express = require('express');
const nconf = require('nconf');
const swig = require('swig');
const path = require('path');
const redis = require('redis');
const favicon = require('serve-favicon');

nconf.argv().env().file({
    file: 'secrets.json'
});

// littlebits setup
const api = require('@littlebits/cloud-http')
    .defaults({
        access_token: nconf.get('cloudbit_access_token'),
        device_id: nconf.get('cloudbit_device_id')
    });

// express setup
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(path.join(__dirname, 'public')));

// pubnub setup
const pubnub = require("pubnub")({
    ssl: true,
    publish_key: nconf.get('pubnub_publish_key'),
    subscribe_key: nconf.get('pubnub_subscribe_key')
});

// set up redis
const redisClient = redis.createClient(
    nconf.get('redis_port') || '6379',
    nconf.get('redis_host') || '127.0.0.1',
    {
        'auth_pass': nconf.get('redis_password'),
        'return_buffers': true
    }
).on('error', function(err) {
    console.error('ERR:REDIS: ' + err);
});

// show the index page
app.get('/', function(req, res, next) {
    redisClient.get('clicks', function(err, data) {
        let clicks = data ? data : 0;
        clicks = clicks > 100 ? 100 : clicks;
        if (err) { return next(err); }
        res.render('index', {
            subscribeKey: nconf.get('pubnub_subscribe_key'),
            clicks: clicks + "" // swig type coersion bug
        });
    });
});

// reset the counter in redis to 0 votes
app.get('/reset', function(req, res, next) {
    redisClient.set('clicks', 0, function(err, data) {
        if (err) { return next(err); }
        res.sendStatus(202);
    });
});

// increment the click counter in memcached
app.post('/click', function(req, res, next) {
    redisClient.incr('clicks', function(err, reply) {
        if (err) return next(err);
        // broadcast the new click count to connected clients
        let clicks = (reply > 100) ? 100 : reply;
        api.output();
        pubnub.publish({
            channel: 'click',
            message: clicks,
            callback: function(r) {
                res.sendStatus(202);
            },
            error: function(err) {
                return next(err);
            }
        });
    });
});

// Start the server
const server = app.listen(process.env.PORT || 8080,
    '0.0.0.0', function() {
    console.log('App listening at http://%s:%s',
        server.address().address,
        server.address().port);
    console.log('Press Ctrl+C to quit.');
});


text:
import os
import subprocess

from itertools import chain
from pathlib import Path

import pytest

from netCDF4 import Dataset
from pkg_resources import resource_filename

from compliance_checker.cf import CF1_6Check, CF1_7Check, util
from compliance_checker.suite import CheckSuite

def glob_down(pth, suffix, lvls):
    """globs down up to (lvls: int) levels of subfolders\n
    suffix in the form ".ipynb"\n
    pth: Path"""
    return list(chain(*[pth.glob(f'*{"/*"*lvl}{suffix}') for lvl in range(lvls)]))

def generate_dataset(cdl_path, nc_path):
    subprocess.call(["ncgen", "-o", str(nc_path), str(cdl_path)])

def static_files(cdl_stem):
    """
    Returns the Path to a valid nc dataset\n
    replaces the old STATIC_FILES dict
    """
    datadir = Path(resource_filename("compliance_checker", "tests/data")).resolve()
    assert datadir.exists(), f"{datadir} not found"

    cdl_paths = glob_down(datadir, f"{cdl_stem}.cdl", 3)
    assert (
        len(cdl_paths) > 0
    ), f"No file named {cdl_stem}.cdl found in {datadir} or its subfolders"
    assert (
        len(cdl_paths) == 1
    ), f"Multiple candidates found with the name {cdl_stem}.cdl:\n{cdl_paths}\nPlease reconcile naming conflict"
    cdl_path = cdl_paths[0]  # PurePath object

    nc_path = cdl_path.parent / f"{cdl_path.stem}.nc"
    if not nc_path.exists():
        generate_dataset(cdl_path, nc_path)
        assert (
            nc_path.exists()
        ), f"ncgen CLI utility failed to produce {nc_path} from {cdl_path}"
    return str(nc_path)

# ---------Fixtures-----------

# class scope:

@pytest.fixture
def cs(scope="class"):
    """
    Initialize the dataset
    """
    cs = CheckSuite()
    cs.load_all_available_checkers()
    return cs

@pytest.fixture
def std_names(scope="class"):
    """get current std names table version (it changes)"""
    _std_names = util.StandardNameTable()
    return _std_names

# func scope:

@pytest.fixture
def loaded_dataset(request):
    """
    Return a loaded NC Dataset for the given path\n
    nc_dataset_path parameterized for each test
    """
    nc_dataset_path = static_files(request.param)
    nc = Dataset(nc_dataset_path, "r")
    yield nc
    nc.close()

@pytest.fixture
def new_nc_file(tmpdir):
    """
    Make a new temporary netCDF file for the scope of the test
    """
    nc_file_path = os.path.join(tmpdir, "example.nc")
    if os.path.exists(nc_file_path):
        raise IOError("File Exists: %s" % nc_file_path)
    nc = Dataset(nc_file_path, "w")
    # no need for cleanup, built-in tmpdir fixture will handle it
    return nc

@pytest.fixture
def tmp_txt_file(tmpdir):
    file_path = os.path.join(tmpdir, "output.txt")
    if os.path.exists(file_path):
        raise IOError("File Exists: %s" % file_path)

    return file_path

@pytest.fixture
def checksuite_setup():
    """For test_cli"""
    CheckSuite.checkers.clear()
    CheckSuite.load_all_available_checkers()


text:
package cmd

import (
	"bufio"
	"os"
	"path/filepath"
	"strings"

	"github.com/Masterminds/cookoo"
)

// This file contains commands for working with GPM/GVP.

// HasGPMGodeps indicates whether a Godeps file exists.
func HasGPMGodeps(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	dir := cookoo.GetString("dir", "", p)
	path := filepath.Join(dir, "Godeps")
	_, err := os.Stat(path)
	return err == nil, nil
}

// GPMGodeps parses a GPM-flavored Godeps file.
//
// Params
// 	- dir (string): Directory root.
//
// Returns an []*Dependency
func GPMGodeps(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	dir := cookoo.GetString("dir", "", p)
	path := filepath.Join(dir, "Godeps")
	if _, err := os.Stat(path); err != nil {
		return []*Dependency{}, nil
	}
	Info("Found Godeps file.\n")

	buf := []*Dependency{}

	file, err := os.Open(path)
	if err != nil {
		return buf, err
	}
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		parts, ok := parseGodepsLine(scanner.Text())
		if ok {
			dep := &Dependency{Name: parts[0]}
			if len(parts) > 1 {
				dep.Reference = parts[1]
			}
			buf = append(buf, dep)
		}
	}
	if err := scanner.Err(); err != nil {
		Warn("Scan failed: %s\n", err)
		return buf, err
	}

	return buf, nil
}

// Reads a Godeps-Git file for gpm-git.
func GPMGodepsGit(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	dir := cookoo.GetString("dir", "", p)
	path := filepath.Join(dir, "Godeps-Git")
	if _, err := os.Stat(path); err != nil {
		return []*Dependency{}, nil
	}
	Info("Found Godeps-Git file.\n")

	buf := []*Dependency{}

	file, err := os.Open(path)
	if err != nil {
		return buf, err
	}
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		parts, ok := parseGodepsLine(scanner.Text())
		if ok {
			dep := &Dependency{Name: parts[1], Repository: parts[0]}
			if len(parts) > 2 {
				dep.Reference = parts[2]
			}
			buf = append(buf, dep)
		}
	}
	if err := scanner.Err(); err != nil {
		Warn("Scan failed: %s\n", err)
		return buf, err
	}

	return buf, nil
}

func parseGodepsLine(line string) ([]string, bool) {
	line = strings.TrimSpace(line)

	if len(line) == 0 || strings.HasPrefix(line, "#") {
		return []string{}, false
	}

	return strings.Fields(line), true
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MiniHttp.Utilities
{
    public static class EnumerableExtensions
    {
        public static void Each<T>(this IEnumerable<T> enumerable, Action<T> action)
        {
            foreach (var item in enumerable)
                action(item);
        }
    }
}


text:
package com.example.jianqiang.testlistview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.example.jianqiang.testlistview.awares.ItemViewAware;
import com.example.jianqiang.testlistview.awares.ListAdapterAware;

public class MyListView extends ListView
{
    private SparseArray<View> mArrayList;

    public MyListView(Context context)
    {
        super(context);

        init();
    }

    public MyListView(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        init();
    }

    public MyListView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);

        init();
    }

    public MyListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);

        init();
    }

    private void init()
    {
        mArrayList = new SparseArray<>();
        this.setOnScrollListener(new OnScrollListener()
        {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState)
            {

                if(!(getAdapter() instanceof ListAdapterAware)) return;

                ((ListAdapterAware) getAdapter()).setScrolling(scrollState != SCROLL_STATE_IDLE);

                if(scrollState == SCROLL_STATE_IDLE)
                {
                    for(int i = 0; i < view.getChildCount(); i++)
                    {

                        View itemView = view.getChildAt(i);

                        if(itemView instanceof ItemViewAware)
                        {
                            boolean loadSuccess= ((ItemViewAware) itemView).triggerNetworkJob((ListAdapterAware) getAdapter(),i);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
            {

            }
        });
    }

    @Override
    protected void onDetachedFromWindow()
    {
        super.onDetachedFromWindow();

        if(getAdapter() instanceof ListAdapterAware)
        {
            ((ListAdapterAware) getAdapter()).destroy();
        }
    }

    //For outside calls
    public void updateItem(int position) {
        if(getAdapter() instanceof ListAdapterAware)
        {
            ((ListAdapterAware) getAdapter()).updateItemView(position);
        }

    }

}


text:
package zipkin2.reporter;

import java.util.List;
import zipkin2.Call;
import zipkin2.CheckResult;
import zipkin2.codec.Encoding;

final class NoopSender extends Sender {

  final Encoding encoding;
  final BytesMessageEncoder messageEncoder;

  /** close is typically called from a different thread */
  volatile boolean closeCalled;

  NoopSender(Encoding encoding) {
    this.encoding = encoding;
    this.messageEncoder = BytesMessageEncoder.forEncoding(encoding);
  }

  @Override public int messageMaxBytes() {
    return Integer.MAX_VALUE;
  }

  @Override public Encoding encoding() {
    return encoding;
  }

  @Override public int messageSizeInBytes(List<byte[]> encodedSpans) {
    return encoding().listSizeInBytes(encodedSpans);
  }

  @Override public int messageSizeInBytes(int encodedSizeInBytes) {
    return encoding().listSizeInBytes(encodedSizeInBytes);
  }

  @Override public Call<Void> sendSpans(List<byte[]> encodedSpans) {
    messageEncoder.encode(encodedSpans);
    return Call.create(null);
  }

  @Override public CheckResult check() {
    return CheckResult.OK;
  }

  @Override public void close() {
    closeCalled = true;
  }

  @Override public String toString() {
    return "NoopSender";
  }
}


text:
namespace Nancy.Diagnostics
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using ModelBinding;
    using Nancy.Bootstrapper;
    using Nancy.TinyIoc;
    using Responses;

    internal class DiagnosticsModuleCatalog : INancyModuleCatalog
    {
        private readonly TinyIoCContainer container;

        public DiagnosticsModuleCatalog(IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, DiagnosticsConfiguration diagnosticsConfiguration)
        {
            this.container = ConfigureContainer(providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);
        }

        /// <summary>
        /// Get all NancyModule implementation instances - should be per-request lifetime
        /// </summary>
        /// <param name="context">The current context</param>
        /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="INancyModule"/> instances.</returns>
        public IEnumerable<INancyModule> GetAllModules(NancyContext context)
        {
            return this.container.ResolveAll<INancyModule>(false);
        }

        /// <summary>
        /// Retrieves a specific <see cref="INancyModule"/> implementation - should be per-request lifetime
        /// </summary>
        /// <param name="moduleType">Module type</param>
        /// <param name="context">The current context</param>
        /// <returns>The <see cref="INancyModule"/> instance</returns>
        public INancyModule GetModule(Type moduleType, NancyContext context)
        {
            return this.container.Resolve<INancyModule>(moduleType.FullName);
        }

        private static TinyIoCContainer ConfigureContainer(IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, DiagnosticsConfiguration diagnosticsConfiguration)
        {
            var diagContainer = new TinyIoCContainer();

            diagContainer.Register<IInteractiveDiagnostics, InteractiveDiagnostics>();
            diagContainer.Register<IRequestTracing>(requestTracing);
            diagContainer.Register<IRootPathProvider>(rootPathProvider);
            diagContainer.Register<NancyInternalConfiguration>(configuration);
            diagContainer.Register<IModelBinderLocator, DefaultModelBinderLocator>();
            diagContainer.Register<IBinder, DefaultBinder>();
            diagContainer.Register<IFieldNameConverter, DefaultFieldNameConverter>();
            diagContainer.Register<BindingDefaults, BindingDefaults>();
            diagContainer.Register<ISerializer>(new DefaultJsonSerializer { RetainCasing = false });
            diagContainer.Register<DiagnosticsConfiguration>(diagnosticsConfiguration);

            foreach (var diagnosticsProvider in providers)
            {
                var key = string.Concat(
                    diagnosticsProvider.GetType().FullName,
                    "_",
                    diagnosticsProvider.DiagnosticObject.GetType().FullName);

                diagContainer.Register<IDiagnosticsProvider>(diagnosticsProvider, key);
            }

            foreach (var moduleType in AppDomainAssemblyTypeScanner.TypesOf<DiagnosticModule>().ToArray())
            {
                diagContainer.Register(typeof(INancyModule), moduleType, moduleType.FullName).AsMultiInstance();
            }

            return diagContainer;
        }
    }
}


text:
package isomorphly;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class MethodCallContextTest extends TestCase {

  public static Test suite()
  {
    return new TestSuite( MethodCallContextTest.class );
  }

  public MethodCallContextTest( String testName )
  {
    super( testName );
  }

  public void testInvalidMethodCallContextAnnotation() {
    IsomorphlyEngine engine;

    String packageNames[] = {"test.isomorphly.dummy.invalid.four.annotations"};

    engine = new IsomorphlyEngine(packageNames);

    try {
      engine.init();
    } catch (IsomorphlyValidationException e) {
      assertFalse("isInitialized should be False", engine.isInitialized());
      return;
    }

    assertTrue("It should raise an IsomorphlyValidationException", false);
  }

  public void testValidMethodCallContextAnnotation() throws IsomorphlyValidationException {
    IsomorphlyEngine engine;

    String packageNames[] = {"test.isomorphly.dummy.annotations"};

    engine = new IsomorphlyEngine(packageNames);

    engine.init();

    assertTrue("it should be true", engine.isInitialized());

  }

}


text:
{% extends "modal_form.html" %}
{% load i18n %}

{% block pre_form_content %}
{% trans "Create serialized items from this stock item." %}
<br>
{% trans "Select quantity to serialize, and unique serial numbers." %}
{% endblock %}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/blocked_content/framebust_block_tab_helper.h"

#include "base/check_op.h"
#include "chrome/browser/content_settings/chrome_content_settings_utils.h"
#include "content/public/browser/navigation_handle.h"

FramebustBlockTabHelper::~FramebustBlockTabHelper() = default;

void FramebustBlockTabHelper::AddBlockedUrl(const GURL& blocked_url,
                                            ClickCallback click_callback) {
  blocked_urls_.push_back(blocked_url);
  callbacks_.push_back(std::move(click_callback));
  DCHECK_EQ(blocked_urls_.size(), callbacks_.size());

  manager_.NotifyObservers(0 /* id */, blocked_url);
  content_settings::UpdateLocationBarUiForWebContents(web_contents());
}

bool FramebustBlockTabHelper::HasBlockedUrls() const {
  return !blocked_urls_.empty();
}

void FramebustBlockTabHelper::OnBlockedUrlClicked(size_t index) {
  size_t total_size = blocked_urls_.size();
  DCHECK_LT(index, total_size);
  const GURL& url = blocked_urls_[index];
  if (!callbacks_[index].is_null())
    std::move(callbacks_[index]).Run(url, index, total_size);
  web_contents()->OpenURL(content::OpenURLParams(
      url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB,
      ui::PAGE_TRANSITION_LINK, false));
}

FramebustBlockTabHelper::FramebustBlockTabHelper(
    content::WebContents* web_contents)
    : content::WebContentsObserver(web_contents) {}

void FramebustBlockTabHelper::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  if (!navigation_handle->IsInMainFrame() ||
      !navigation_handle->HasCommitted() ||
      navigation_handle->IsSameDocument()) {
    return;
  }
  blocked_urls_.clear();
  callbacks_.clear();

  content_settings::UpdateLocationBarUiForWebContents(web_contents());
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(FramebustBlockTabHelper)


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace FileFormats
{
    /// <summary>
    /// A container that can provide ILayout instances for Types.
    /// </summary>
    public class LayoutManager
    {
        private Dictionary<Type, ILayout> _layouts = new Dictionary<Type, ILayout>();
        private List<Func<Type, LayoutManager, ILayout>> _layoutProviders = new List<Func<Type, LayoutManager, ILayout>>();
        private Dictionary<Tuple<Type, uint>, ILayout> _arrayLayouts = new Dictionary<Tuple<Type, uint>, ILayout>();

        public LayoutManager() { }

        public void AddLayout(ILayout layout)
        {
            _layouts.Add(layout.Type, layout);
        }

        public void AddLayoutProvider(Func<Type, LayoutManager, ILayout> layoutProvider)
        {
            _layoutProviders.Add(layoutProvider);
        }

        public ILayout GetArrayLayout(Type arrayType, uint numElements)
        {
            if (!arrayType.IsArray)
            {
                throw new ArgumentException("The type parameter must be an array");
            }
            if (arrayType.GetArrayRank() != 1)
            {
                throw new ArgumentException("Multidemensional arrays are not supported");
            }

            ILayout layout;
            Tuple<Type, uint> key = new Tuple<Type, uint>(arrayType, numElements);
            if (!_arrayLayouts.TryGetValue(key, out layout))
            {
                Type elemType = arrayType.GetElementType();
                layout = new ArrayLayout(arrayType, GetLayout(elemType), numElements);
                _arrayLayouts.Add(key, layout);
            }
            return layout;
        }

        public ILayout GetArrayLayout<T>(uint numElements)
        {
            return GetArrayLayout(typeof(T), numElements);
        }

        public ILayout GetLayout<T>()
        {
            return GetLayout(typeof(T));
        }

        public ILayout GetLayout(Type t)
        {
            ILayout layout;
            if (!_layouts.TryGetValue(t, out layout))
            {
                foreach (Func<Type, LayoutManager, ILayout> provider in _layoutProviders)
                {
                    layout = provider(t, this);
                    if (layout != null)
                    {
                        break;
                    }
                }
                if (layout == null)
                {
                    throw new LayoutException("Unable to create layout for type " + t.FullName);
                }
                _layouts.Add(t, layout);
            }
            return layout;
        }
    }
}


text:
var WPML_core = WPML_core || {};

jQuery(document).ready(function(){

   jQuery("#icl_msync_cancel").click(function(){
       location.href = location.href.replace(/#(.)$/, '');
   });

   jQuery('#icl_msync_confirm thead :checkbox').change(function(){
       var on = jQuery(this).attr('checked');
       if(on){
           jQuery('#icl_msync_confirm :checkbox').attr('checked', 'checked');
           if(jQuery('#icl_msync_confirm tbody .check-column :checkbox').length){
                jQuery('#icl_msync_submit').removeAttr('disabled');
           }
       }else{
           jQuery('#icl_msync_confirm :checkbox').removeAttr('checked');
           if(!jQuery('input[name^="sync"]').length){
                jQuery('#icl_msync_submit').attr('disabled', 'disabled');
           }
       }
   })

   jQuery('#icl_msync_confirm tbody :checkbox').change(function(){

       if(jQuery(this).attr('readonly') == 'readonly'){
           if(jQuery(this).attr('checked')){
               jQuery(this).removeAttr('checked');
           }else{
               jQuery(this).attr('checked', 'checked');
           }
       };

       var checked = jQuery('#icl_msync_confirm tbody :checkbox:checked').length;

       if(checked){
           jQuery('#icl_msync_submit').removeAttr('disabled');
       }else{
           jQuery('#icl_msync_submit').attr('disabled', 'disabled');
       }

       if(checked && jQuery('#icl_msync_confirm tbody :checkbox:checked').length == jQuery('#icl_msync_confirm tbody :checkbox').length){
           jQuery('#icl_msync_confirm thead :checkbox').attr('checked', 'checked');
       }else{
           jQuery('#icl_msync_confirm thead :checkbox').removeAttr('checked');
       }

       WPML_core.icl_msync_validation();

   });

   jQuery('#icl_msync_submit').on( 'click', function() {
	  jQuery(this).attr('disabled', 'disabled');

      var total_menus = jQuery('input[name^=sync]:checked').length;

	  var spinner = jQuery('');
	  jQuery('#icl_msync_message').before(spinner);
	  spinner.css({display: 'inline-block', float: 'none', 'visibility': 'visible'});

	  WPML_core.sync_menus(total_menus);

   });

   var max_vars_warning = jQuery('#icl_msync_max_input_vars');
   if (max_vars_warning.length) {
      var menu_sync_check_box_count = jQuery('input[name^=sync]').length;
	  var max_vars_extra = 10; // Allow for a few other items as well. eg. nonce, etc
      if (menu_sync_check_box_count + max_vars_extra > max_vars_warning.data('max_input_vars')) {
		 var warning_text = max_vars_warning.html();
		 warning_text = warning_text.replace('!NUM!', menu_sync_check_box_count + max_vars_extra);
		 max_vars_warning.html(warning_text);
		 max_vars_warning.show();
	  }
   }
});

WPML_core.icl_msync_validation = function(){

    jQuery('#icl_msync_confirm tbody :checkbox').each(function(){
        var mnthis = jQuery(this);

        mnthis.removeAttr('readonly', 'readonly');

        if(jQuery(this).attr('name')=='menu_translation[]'){
            var spl = jQuery(this).val().split('#');
            var menu_id = spl[0];

            jQuery('#icl_msync_confirm tbody :checkbox').each(function(){

                if(jQuery(this).val().search('newfrom-'+menu_id+'-') == 0 && jQuery(this).attr('checked')){
                    mnthis.attr('checked', 'checked');
                    mnthis.attr('readonly', 'readonly');
                }
            });
        }
    });
}

WPML_core.sync_menus = function (total_menus) {

   var data = 'action=icl_msync_confirm';
   data += '&_icl_nonce_menu_sync=' + jQuery('#_icl_nonce_menu_sync').val();

   var number_to_send = 50;

   var menus = jQuery('input[name^=sync]:checked:not(:disabled)');
   if (menus.length) {

	  for ( var i = 0; i < Math.min( number_to_send, menus.length); i++ ) {

	  	  data += '&' + jQuery(menus[i]).serialize();

		  jQuery(menus[i]).attr('disabled', 'disabled');
	  }

	  var message = jQuery('#icl_msync_submit').data('message');
	  message = message.replace('%1', total_menus - menus.length);
	  message = message.replace('%2', total_menus);

	  jQuery('#icl_msync_message').text(message);

      jQuery.ajax({
		 url: ajaxurl,
		 type: "POST",
		 data: data,
		 success: function (response) {

			if (response == '1') {
			   WPML_core.sync_menus(total_menus);
			}
		 }
      });
   } else {
	  jQuery('#icl_msync_message').hide();
	  var message = jQuery('#icl_msync_submit').data('message-complete');
	  jQuery('#icl_msync_message').text(message);
	  jQuery('.spinner').remove();
	  jQuery('#icl_msync_message').fadeIn('slow');
   }

}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
002
005
006package org.jsimpledb.kv.leveldb;
007
008import org.iq80.leveldb.DB;
009import org.iq80.leveldb.ReadOptions;
010import org.iq80.leveldb.Snapshot;
011import org.jsimpledb.kv.CloseableKVStore;
012import org.slf4j.Logger;
013import org.slf4j.LoggerFactory;
014
015/**
016 * Read-only {@link org.jsimpledb.kv.KVStore} view of a LevelDB {@link Snapshot}.
017 *
018 * <p>
019 * Instances must be {@link #close}'d when no longer needed to avoid leaking resources associated with iterators.
020 * This class ensures that the configured {@link Snapshot} is closed when this instance is closed.
021 *
022 * <p>
023 * All mutation operations throw {@link UnsupportedOperationException}.
024 */
025public class SnapshotLevelDBKVStore extends LevelDBKVStore implements CloseableKVStore {
026
027    private final Logger log = LoggerFactory.getLogger(this.getClass());
028    private final Snapshot snapshot;
029    private boolean closed;
030
031    /**
032     * Constructor.
033     *
034     * @param db LevelDB database to snapshot
035     * @param verifyChecksums whether to verify checksums on reads
036     * @throws NullPointerException if {@code db} is null
037     */
038    public SnapshotLevelDBKVStore(DB db, boolean verifyChecksums) {
039        this(db, db.getSnapshot(), verifyChecksums);
040    }
041
042    private SnapshotLevelDBKVStore(DB db, Snapshot snapshot, boolean verifyChecksums) {
043        super(db, new ReadOptions().snapshot(snapshot).verifyChecksums(verifyChecksums), null);
044        this.snapshot = snapshot;
045    }
046
047    @Override
048    public synchronized void close() {
049        if (this.closed)
050            return;
051        this.closed = true;
052        super.close();
053        try {
054            this.snapshot.close();
055        } catch (Throwable e) {
056            this.log.error("caught exception closing LevelDB snapshot (ignoring)", e);
057        }
058    }
059
060// KVStore
061
062    @Override
063    public void put(byte[] key, byte[] value) {
064        throw new UnsupportedOperationException("KVStore is read-only");
065    }
066
067    @Override
068    public void remove(byte[] key) {
069        throw new UnsupportedOperationException("KVStore is read-only");
070    }
071
072    @Override
073    public void removeRange(byte[] minKey, byte[] maxKey) {
074        throw new UnsupportedOperationException("KVStore is read-only");
075    }
076
077    @Override
078    public void adjustCounter(byte[] key, long amount) {
079        throw new UnsupportedOperationException("KVStore is read-only");
080    }
081}
082


text:
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Navigator navi;

    return a.exec();
}


text:
         Failed to create backup

         The private key for this wallet is encrypted. Exporting a backup will keep the private key encrypted in the backup archive.

      Set up a Password for your backup

        <input type="password" class="form-control"
        placeholder="{{'Your backup password'|translate}}"
        name="password" ng-model="backup.password">

      Repeat password

        <input type="password" class="form-control"
        placeholder="{{'Repeat password'|translate}}"
        name="password" ng-model="backup.repeatpassword">

          Show Advanced options
          Hide Advanced options

            Do not include private key in backup
            <switch id="no-sign" name="noSign" ng-model="noSign" class="green right m5t m10b"></switch>

          A backup without its private key will allow the user to see the wallet balance, transactions, and create spend proposals. However, it will not be able to approve (sign) proposals.

      <button class="black round expand m0" ng-click="backup.downloadWalletBackup()"
        ng-disabled="(!backup.password || backup.password != backup.repeatpassword)"
        ng-style="{'background-color':index.backgroundColor}"
        ng-show="!backup.isSafari && !backup.isCordova">
        Download backup</button>
      <button class="black round expand m0" ng-click="backup.viewWalletBackup()"
        ng-disabled="(!backup.password || backup.password != backup.repeatpassword)"
        ng-style="{'background-color':index.backgroundColor}"
        ng-show="backup.isSafari && !backup.isCordova">
        View backup</button>

Backup options

        <button class="black round expand" ng-disabled="(!backup.password || backup.password != backup.repeatpassword)"
          ng-style="{'background-color':index.backgroundColor}"
          ng-click="backup.copyWalletBackup()">
          Copy to clipboard</button>
        <button class="black round expand m0" ng-disabled="(!backup.password || backup.password != backup.repeatpassword)"
          ng-style="{'background-color':index.backgroundColor}"
          ng-click="backup.sendWalletBackup()">
          Send by email</button>

Copy backup to a safe place

        <textarea rows="12">{{backup.backupWalletPlainText}}</textarea>

        Copy this text as it is to a safe place (notepad or email)

      * You can safely install your backup on another device and use your wallet from multiple devices at the same time.


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleRoselyn1
{
    class InitialParser
    {
        static void Main(string[] args)
        {
            // Fist, we localize and load the file to check out
            string filename = @"C:\Users\Marino\Desktop\ConsoleRoselyn1\ConsoleRoselyn1\Person.cs";
            string content = File.ReadAllText(filename);
            // Now we have to analyze the contents
            // So, we use the same class as before. Notice
            // it returns a SyntaxTree object.
            SyntaxTree tree = CSharpSyntaxTree.ParseText(content);

            SyntaxNode root = tree.GetRoot();
            // Gets the class identifier
            ClassDeclarationSyntax personClass = root.DescendantNodes().
                OfType<ClassDeclarationSyntax>().First();
            Console.WriteLine("Class names");
            Console.WriteLine("-----------");
            Console.WriteLine(personClass.Identifier);
            // Now, the methods
            Console.WriteLine("\nMethod names");
            Console.WriteLine("------------");
            personClass.DescendantNodes().
                OfType<MethodDeclarationSyntax>().ToList().
                ForEach(method => Console.WriteLine(method.Identifier));

            // And the properties
            Console.WriteLine("\nProperties");
            Console.WriteLine("----------");
            personClass.DescendantNodes()
                .OfType<PropertyDeclarationSyntax>().ToList()
                .ForEach(property => Console.WriteLine(property.Identifier));

            Console.Read();
        }
    }
}


text:
class ShaderScene : public cocos2d::Layer
{
	// Camera
	Camera3d* _camera;

	// Light
	Light* _light;

public:
	ShaderScene();
	~ShaderScene();

	// there's no 'id' in cpp, so we recommend returning the class instance pointer
	static cocos2d::Scene* createScene();

	// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
	virtual bool init();

	// a selector callback
	void menuCloseCallback(cocos2d::Ref* pSender);

	// implement the "static create()" method manually
	CREATE_FUNC(ShaderScene);
};

#endif // __SHADER_SCENE_H__


text:
namespace Plethora.Calendar
{
    /// <summary>
    /// The nature of the date rolling which is to be conducted to ensure a date falls on a business day.
    /// </summary>
    public enum DateRollType
    {
        /// <summary>
        /// No rolling occurs, even if it is a non-business day
        /// </summary>
        Actual,

        /// <summary>
        /// If the date is a non-business day, the date is rolled to the next business day.
        /// </summary>
        Following,

        /// <summary>
        /// If the date is a non-business day, the date is rolled to the next business day, unless doing so would cause
        /// the payment to be in the next calendar month, in which case the date is rolled to the previous business day.
        /// </summary>
        ModifiedFollowing,

        /// <summary>
        /// If the date is a non-business day, the date is rolled to the next business day.
        /// </summary>
        Preceding,

        /// <summary>
        /// If the date is a non-business day, the date is rolled to the previous business day, unless doing so would cause
        /// the payment to be in the previous calendar month, in which case the date is rolled to the next business day.
        /// </summary>
        ModifiedPreceding,
    }
}


text:
package tdigestx;

import com.tdunning.math.stats.TDigest;

public class TDigestProxy
{
	public static final int DEFAULT_DIGEST_TYPE = 0;
	public static final int ARRAY_DIGEST_TYPE = 1;
	public static final int AVLTREE_DIGEST_TYPE = 2;
	public static final int TREE_DIGEST_TYPE = 3;

	public static final int DEFAULT_COMPRESSION = 100;

	private TDigest tdigest = null;

	public static int getDefaultDigestType()
	{
		return DEFAULT_DIGEST_TYPE;
	}

	public static int getArrayDigestType()
	{
		return ARRAY_DIGEST_TYPE;
	}

	public static int getAvlTreeDigestType()
	{
		return AVLTREE_DIGEST_TYPE;
	}

	public static int getTreeDigestType()
	{
		return TREE_DIGEST_TYPE;
	}

	public static int getDefaultCompression()
	{
		return DEFAULT_COMPRESSION;
	}

	public void init()
	{
		init(DEFAULT_DIGEST_TYPE, DEFAULT_COMPRESSION);
	}

	public void init(int digestType)
	{
		init(digestType, DEFAULT_COMPRESSION);
	}

	public void init(int digestType, double compression)
	{
		switch (digestType)
		{
			case ARRAY_DIGEST_TYPE:
				tdigest = TDigest.createArrayDigest(compression);
				break;
			case AVLTREE_DIGEST_TYPE:
				tdigest = TDigest.createAvlTreeDigest(compression);
				break;
			case DEFAULT_DIGEST_TYPE:
				tdigest = TDigest.createDigest(compression);
				break;
			case TREE_DIGEST_TYPE:
				tdigest = TDigest.createTreeDigest(compression);
				break;
			default:
				throw new IllegalArgumentException("Unknown digest type");
		}
	}

	public void add(double x)
	{
		tdigest.add(x);
	}

	public void add(double x, int w)
	{
		tdigest.add(x, w);
	}

	public double quantile(double q)
	{
		return tdigest.quantile(q);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<tree>
  <#list nodes as node>
  <#if nodeManager.getNodeCount(node.nodeId,0,0)==0>
  	<tree text="${node.name?replace('&','&')}[${node.nodeId?c}]" action="admin/nodeEdit.jhtml?mode=edit&nodeId=${node.nodeId?c}&extra=system" target="main" cId="${node.nodeId?c}" extra="system"/>
  <#else>
  	<tree text="${node.name?replace('&','&')}[${node.nodeId?c}]" action="admin/nodeEdit.jhtml?mode=edit&nodeId=${node.nodeId?c}" src="admin/node.jhtml?action=SiteSystemXml&nodeId=${node.nodeId?c}&extra=system" target="main" cId="${node.nodeId?c}" extra="system"/>
  </#if>
  </#list>
</tree>


text:
package hr.fer.ztel.thesis.measure

trait ItemPairSimilarityMeasure extends Serializable {

  /*
   *  sim(x, x) = 0.0 default, could be overridden
   */
  val reflexiveEntryMeasure: Double = 0.0

  /**
    *
    * @param a number of customers who bought both items
    * @param b number of customers who bought only first item
    * @param c number of customers who bought only second item
    * @param d number of customers who did not buy any item
    *
    * @return similarity between a pair of items
    */
  def compute(a: Int, b: Int, c: Int, d: Int): Double

}

object ItemPairSimilarityMeasure extends Serializable {

  def parseMeasure(measure: String): Option[ItemPairSimilarityMeasure] = measure match {
    case "cos" => Some(new CosineSimilarityMeasure)
    case "llr" => Some(new LogLikelihoodRatioSimilarityMeasure)
    case "yuleq" => Some(new YuleQSimilarityMeasure)
    case _ =>
      println(s""""Wrong similiarity measure: $measure! Supported measures: "cos", "llr", "yuleq"""")
      System exit 1
      None
  }

}


text:
var A_CODE = 'a'.charCodeAt();

// Construct and display a string of PGML code representing the
// questions entered on a web page.
function generatePGML(button)
{
  // TERMINOLOGY NOTE: A "problem" to WeBWorK is a set of questions.
  // But when I coded this, I thought of each question as a problem.
  // TODO: Should refactor the terminology...

  // Initialize problem references
  var questionDiv = document.getElementById("questionDiv");
  var problems = questionDiv.getElementsByTagName("form");
  var numProblems = problems.length;

  // Add PG preamble to output string.
  var outString = "";
  outString += '############## Generated by GUIWorK ############## \n';
  outString += '#  Note that if any changes are made directly    # \n';
  outString += '#  to the PG code below then the GUIWorK editor  # \n';
  outString += '#  cannot be used to update this problem.        # \n';
  outString += '################################################## \n';
  outString += 'DOCUMENT(); \n';
  outString += 'loadMacros( \n';
  outString += '"PGstandard.pl", \n';
  outString += '"MathObjects.pl", \n';
  outString += '"PGchoicemacros.pl", \n';
  outString += '"parserRadioButtons.pl", \n';
  outString += '"PGML.pl"); \n';
  outString += ' \n';

  // Add each problem's initialization to the output string
  for (nProblem = 1; nProblem <= numProblems; nProblem++) {

    var problem = problems[nProblem-1];
    var radioObject = '$radio' + nProblem;
    outString += '# INITIALIZATION FOR PROBLEM ' + nProblem + '\n';
    outString += radioObject +' = RadioButtons( \n';
    outString += '  [ \n';
    answerBoxes = problem.getElementsByClassName("inBox");
    answerStrings = new Array();
    for (i=0; i<answerBoxes.length; i++) {
      answerStrings[i] =
        encodeQuotes(encodeLaTeXMathModePG(answerBoxes[i].value));
    }
    for (i=0; i<answerBoxes.length; i++) {
      outString += '    "' + answerStrings[i] +'", \n';
    }
    outString += '  ], \n';
    var selectAnswer = problem.getElementsByClassName("selectAnswer")[0];
//    if (correctAnswer.startsWith("Select")) {
    if (selectAnswer.selectedIndex == 0) {
      window.alert("Must select an answer for Question " + nProblem);
      return false;
    }
    var correctAnswer = selectAnswer.value;
    outString +=
      '  "' + answerStrings[correctAnswer.charCodeAt()-A_CODE] + '", \n';
    outString += '  order=>[ \n';
    for (i=0; i<answerBoxes.length; i++) {
      outString += '    "' + answerStrings[i] +'", \n';
    }
    outString += '  ] \n';
    outString += '); \n';
  }

  // Begin the PGML section
  outString += '\n';
  outString += 'TEXT(beginproblem()); \n';
  outString += 'BEGIN_PGML \n';
  outString += '=== \n';

  // Add each problem's PGML code to the output string
  for (nProblem = 1; nProblem <= numProblems; nProblem++) {
    var problem = problems[nProblem-1];
    var question = problem.getElementsByClassName("question")[0];
    var radioObject = '$radio' + nProblem;
    outString += '  \n';
    outString += '*Question ' + nProblem + '*  \n'; // need exactly 2 spaces
    outString += encodeLaTeXMathModePGML(question.value) + '\n  \n';
    outString += '[@ ANS(' + radioObject + '->cmp); '
    	         + radioObject + '->buttons(); @]*\n';
  }
  // Close PGML section
  outString += '\n';
  outString += 'END_PGML \n';

  // Include any solutions
  var someSolution = false;
  for (nProblem = 1; nProblem <= numProblems; nProblem++) {
    var problem = problems[nProblem-1];
    var solution = problem.getElementsByClassName("solution")[0];
    if (solution.value) {
      if (!someSolution) {
        outString += '\n';
        outString += 'BEGIN_PGML_SOLUTION \n';
	someSolution = true;
      }
      outString += '\n';
      outString += '*Question ' + nProblem + '*  \n';
      outString += encodeLaTeXMathModePGML(solution.value) + ' \n';
    }
  }
  if (someSolution) {
    outString += '\n';
    outString += 'END_PGML_SOLUTION \n';
  }

  // Terminate the PG code
  outString += 'ENDDOCUMENT(); \n';

  // Append HTML representing the entire page, including input values
  // (except anything in the outBox textarea)
  // so that the problem can be edited later.
  // This modifies the document to include the input values.
  outString += '<!-- \n';
  outString += '############## Generated by GUIWorK ############## \n';
  outString += '#  The following code is ignored by WeBWorK      # \n';
  outString += '#  and can be deleted if you do not plan to use  # \n';
  outString += '#  the GUIWorK editor to update this problem.    # \n';
  outString += '################################################## \n';
  outString += '--> \n';
  addInputValues(document.documentElement);
  var outBox = document.getElementById("outBox");
  outBox.textContent = "";
  outString += document.documentElement.outerHTML + '\n';

  // Display the PGML+HTML code in the appropriate textarea
  outBox.value = outString;

  return false;
}

// Add an answer box following the current answer box.
function addAnswer(textBox)
{
  // Retrieve pointers to the current answer paragraph,
  // the div containing all answers, and
  // the fieldset of the form containing this problem.
  var paragraph = textBox.parentNode;
  var answerDiv = paragraph.parentNode;
  var fieldset = answerDiv.parentNode;

  // Create the new answer box as a copy of the current one
  // and insert it following the current answer box.
  var newAnswer = document.createElement("p");
  answerDiv.insertBefore(newAnswer, paragraph.nextSibling);
  newAnswer.innerHTML = paragraph.innerHTML;

  // Clear the box (input element might have value attribute set).
  var input = newAnswer.getElementsByClassName("inBox")[0];
  input.value = '';

  // Increment the newly created answer's letter as well as
  // the letters of all subsequent answers.
  var nextNode = newAnswer;
  do {
    if (nextNode.nodeType == Node.ELEMENT_NODE) {
       var letterSpan = nextNode.getElementsByClassName("letter")[0];
       letterSpan.textContent = nextLetter(letterSpan.textContent);
    }
    nextNode = nextNode.nextSibling;
  } while (nextNode);

  // Add an option to the correct-answer select menu
  var selectAnswer = fieldset.getElementsByClassName("selectAnswer")[0];
  var options = selectAnswer.getElementsByTagName("option");
  var nOptions = options.length-1; // first "option" is disabled
  var newOptionText = String.fromCharCode(A_CODE+nOptions) + ".";
  var newOption = document.createElement("option");
  selectAnswer.appendChild(newOption);
  newOption.textContent = newOptionText;
}

// Delete the current answer box.
function delAnswer(textBox)
{
  // Retrieve pointers to the current answer paragraph,
  // the div containing all answers,
  // the fieldset of the form containing this problem,
  // the next sibling following this answer paragraph,
  // the select containing the possible answer letters,
  // and the options within the select.
  var paragraph = textBox.parentNode;
  var answerDiv = paragraph.parentNode;
  var fieldset = answerDiv.parentNode;
  var nextNode = paragraph.nextSibling;
  var selectAnswer = fieldset.getElementsByClassName("selectAnswer")[0];
  var options = selectAnswer.getElementsByTagName("option");

  // Don't delete if there is only one option remaining.
  // (Note that "Select correct answer" is an option.)
  if (options.length <= 2) {
    window.alert("Cannot delete last remaining answer.");
    return;
  }

  // Delete this answer paragraph.
  answerDiv.removeChild(paragraph);

  // Decrement the letters of all subsequent answers.
  while (nextNode) {
    if (nextNode.nodeType == Node.ELEMENT_NODE) {
       var letterSpan = nextNode.getElementsByClassName("letter")[0];
       letterSpan.textContent = prevLetter(letterSpan.textContent);
    }
    nextNode = nextNode.nextSibling;
  }

  // Remove an option from the correct-answer select menu
  selectAnswer.removeChild(options[options.length-1]);
}

function nextLetter(oldLetter) {
  var newLetter = String.fromCharCode(oldLetter.charCodeAt()+1);
  return newLetter;
}

function prevLetter(oldLetter) {
  var newLetter = String.fromCharCode(oldLetter.charCodeAt()-1);
  return newLetter;
}

// Respond to a selction in the action menu
function actionMenu(actionSelect) {

  // Initialize references to useful elements
  var questionForm = actionSelect.parentNode.parentNode;
  var questionDiv = questionForm.parentNode;

  // Process the selected action
  switch (actionSelect.selectedIndex) {

    // Add a blank problem after this one
    case 1:
    break;

    // Add a blank problem before this one
    case 2:
    break;

    // Create a copy of this question
    case 3:

      // Create new question as a copy of the current one, including
      // current input values,
      // and insert it following the current one.
      var newQuestion = document.createElement("form");
      questionDiv.insertBefore(newQuestion, questionForm.nextSibling);
      newQuestion.setAttribute("onsubmit", "return false;");
      newQuestion.addEventListener("submit",
                                  function (event) { event.preventDefault(); },
				  false);
      actionSelect.selectedIndex = 0;
      addInputValues(questionForm);
      newQuestion.innerHTML = questionForm.innerHTML;

      // Increment the newly created problem's number as well as
      // the number of all subsequent problems.
      var nextNode = newQuestion;
      do {
        if (nextNode.nodeType == Node.ELEMENT_NODE) {
	  var questionNumSpan =
	    nextNode.getElementsByClassName("questionNum")[0];
	  questionNumSpan.textContent = Number(questionNumSpan.textContent) + 1;
	}
	nextNode = nextNode.nextSibling;
      } while (nextNode);
    break;

    // Move this question earlier
    case 5:
    break;

    // Move this question later
    case 6:
    break;

    // Delete this question
    case 8:
    break;

    default:
      window.alert("Unrecognized selection " + actionSelect.selectedIndex);
  }
  // Reset the action menu selection
  actionSelect.selectedIndex = 0;
}

// XML encode quotes in a string.
function encodeQuotes(aString) {
  return aString.replace(/\"/g, """); // used \" rather than " for Emacs
}

// Replace unescaped $...$ or $$...$$ (LaTeX inline/display math mode markings)
// with [`...`] or \n>>[``...``]<<\n (PGML math mode markings).
function encodeLaTeXMathModePGML(aString) {
  var regex1 = /(^|[^\\])\$([^]*?)([^\\])\$/g;
  var regex2 = /(^|[^\\])\$\$([^]*?)([^\\])\$\$/g;
  return aString.replace(regex2, '$1\n>>[``$2$3``]<<\n').replace(regex1, '$1[`$2$3`]');
}

// Replace unescaped $...$ with \(...\) (PG math mode markings).
// This is used in, e.g., radio button answers.
function encodeLaTeXMathModePG(aString) {
  var regex = /(^|[^\\])\$([^]*?)([^\\])\$/g;
  return aString.replace(regex, '$1\\($2$3\\)');
}

// Modifies the specified element by including in the element the
// user's current inputs.  For instance, this adds value attributes to
// input/text elements.
function addInputValues(element) {

  // Set the value attribute of every input/text element to its value.
  var inputs = element.getElementsByTagName("input");
  for (var i=0; i<inputs.length; i++) {
    var input = inputs[i];
    if (input.getAttribute("type") == "text") {
      input.setAttribute("value", input.value);
    }
  }

  // Mark as "selected" the currently selected option in each select control.
  // Note that we must remove any "selected" attribute previously set on
  // a different element.
  var selects = element.getElementsByTagName("select");
  for (var i=0; i<selects.length; i++) {
    var select = selects[i];
    var options = select.options;
    for (var j=0; j<options.length; j++) {
      var option = options[j];
      if (j == select.selectedIndex) {
        option.setAttribute("selected", "selected");
      }
      else if (option.hasAttribute("selected")) {
        option.removeAttribute("selected");
      }
    }
  }

  // Add text within each textarea as a text node of that textarea,
  // skipping the "outBox" textarea if it is present in the list.
  // TODO: Should not be special-casing outBox here.
  textareas = element.getElementsByTagName("textarea");
  for (var i=0; i<textareas.length; i++) {
    var textarea = textareas[i];
    if (textarea.getAttribute("id") != "outBox") {
      textarea.textContent = textarea.value;
    }
  }
}