repo_name
stringlengths
2
55
dataset
stringclasses
1 value
owner
stringlengths
3
31
lang
stringclasses
10 values
func_name
stringlengths
1
104
code
stringlengths
20
96.7k
docstring
stringlengths
1
4.92k
url
stringlengths
94
241
sha
stringlengths
40
40
kamal
github_2023
basecamp
ruby
Kamal::Git.untracked_files
def untracked_files `git ls-files --others`.lines.map(&:strip) end
# returns an array of relative path names of untracked files, including gitignored files
https://github.com/basecamp/kamal/blob/6f29d4e78bc29c3392f54f93ea0451ad1ff68b13/lib/kamal/git.rb#L34-L36
6f29d4e78bc29c3392f54f93ea0451ad1ff68b13
kamal
github_2023
basecamp
ruby
Kamal::Utils.escape_shell_value
def escape_shell_value(value) value.to_s.scan(/[\x00-\x7F]+|[^\x00-\x7F]+/) \ .map { |part| part.ascii_only? ? escape_ascii_shell_value(part) : part } .join end
# Escape a value to make it safe for shell use.
https://github.com/basecamp/kamal/blob/6f29d4e78bc29c3392f54f93ea0451ad1ff68b13/lib/kamal/utils.rb#L60-L64
6f29d4e78bc29c3392f54f93ea0451ad1ff68b13
kamal
github_2023
basecamp
ruby
Kamal::Commands::Docker.installed?
def installed? docker "-v" end
# Checks the Docker client version. Fails if Docker is not installed.
https://github.com/basecamp/kamal/blob/6f29d4e78bc29c3392f54f93ea0451ad1ff68b13/lib/kamal/commands/docker.rb#L8-L10
6f29d4e78bc29c3392f54f93ea0451ad1ff68b13
rails7-startkit
github_2023
the-teacher
ruby
puma_stop
def puma_stop if inside_rails_conainer? puts 'Stopping PUMA' pids = `pgrep -f puma`.split("\n") pids.delete(Process.pid.to_s) pids.each { |pid| system "kill -9 #{pid}" } else run_rails_command('pkill -f puma') end end
# Do not use: `pkill -f puma` # It matches the running script name and kills it also :)
https://github.com/the-teacher/rails7-startkit/blob/51bb127e2114910bdc759f6974740a5c4703a53d/Rails7StartKit/bin/puma.rb#L20-L29
51bb127e2114910bdc759f6974740a5c4703a53d
rails7-startkit
github_2023
the-teacher
ruby
cache
def cache puts 'Toggle App Cache in development mode' cache_toggle_file = 'tmp/caching-dev.txt' FileUtils.chdir APP_ROOT do if File.exist?(cache_toggle_file) puts "File '#{cache_toggle_file}' exists" remove_file(cache_toggle_file) puts "File '#{cache_toggle_file}' is removed" puts 'Cache is OFF' else puts "File '#{cache_toggle_file}' does not exist" touch_file(cache_toggle_file) puts "File '#{cache_toggle_file}' is created" puts 'Cache is ON' end end # Not sure if for windows it will work. # https://stackoverflow.com/questions/11982057/how-can-i-trigger-a-shell-script-and-run-in-background-async-in-ruby # puts 'Restarting PUMA server' puma_restart end
# def get_secret_key # container_bash_exec('rails', 'rake secret > tail') # container_bash_exec('rails', 'printenv SECRET_KEY_BASE') # end
https://github.com/the-teacher/rails7-startkit/blob/51bb127e2114910bdc759f6974740a5c4703a53d/Rails7StartKit/bin/rails7startkit.rb#L57-L80
51bb127e2114910bdc759f6974740a5c4703a53d
devise-api
github_2023
nejdetkadir
ruby
Devise.Api.Responses.ErrorResponse.error_description
def error_description return [I18n.t("devise.api.error_response.#{error}")] if record.blank? if invalid_authentication_error? && devise_lockable_info.present? && record.access_locked? return [I18n.t('devise.api.error_response.lockable.locked')] end if invalid_authentication_error? && devise_confirmable_info.present? && !record.confirmed? return [I18n.t('devise.api.error_response.confirmable.unconfirmed')] end return [I18n.t('devise.api.error_response.invalid_authentication')] if invalid_authentication_error? record.errors.full_messages end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
https://github.com/nejdetkadir/devise-api/blob/bd49310c4e96ec6e56ec38c2542754718b2f1c57/lib/devise/api/responses/error_response.rb#L59-L70
bd49310c4e96ec6e56ec38c2542754718b2f1c57
revise_auth
github_2023
excid3
ruby
ReviseAuth.Authentication.login
def login(user) user_return_to = session[:user_return_to] reset_session Current.user = user session[:user_id] = user.id session[:user_return_to] = user_return_to end
# Logs in the user # - Reset the session to prevent session fixation # See: https://guides.rubyonrails.org/security.html#session-fixation-countermeasures # - Set Current.user for the current request # - Save a session cookie so the next request is authenticated
https://github.com/excid3/revise_auth/blob/6af392c5138f18c18205acfc404d355bda17d80c/lib/revise_auth/authentication.rb#L60-L66
6af392c5138f18c18205acfc404d355bda17d80c
revise_auth
github_2023
excid3
ruby
ReviseAuth.Authentication.revise_auth_controller?
def revise_auth_controller? is_a?(::ReviseAuthController) end
# Return true if it's a revise_auth_controller. false to all controllers unless # the controllers defined inside revise_auth. Useful if you want to apply a before # filter to all controllers, except the ones in revise_auth: # # before_action :authenticate_user!, unless: :revise_auth_controller?
https://github.com/excid3/revise_auth/blob/6af392c5138f18c18205acfc404d355bda17d80c/lib/revise_auth/authentication.rb#L94-L96
6af392c5138f18c18205acfc404d355bda17d80c
solid_queue
github_2023
rails
ruby
SolidQueue::Processes.Interruptible.interruptible_sleep
def interruptible_sleep(time) # Invoking this from the main thread may result in significant slowdown. # Utilizing asynchronous execution (Futures) addresses this performance issue. Concurrent::Promises.future(time) do |timeout| queue.clear unless queue.pop(timeout:).nil? end.on_rejection! do |e| wrapped_exception = RuntimeError.new("Interruptible#interruptible_sleep - #{e.class}: #{e.message}") wrapped_exception.set_backtrace(e.backtrace) handle_thread_error(wrapped_exception) end.value nil end
# Sleeps for 'time'. Can be interrupted asynchronously and return early via wake_up. # @param time [Numeric, Duration] the time to sleep. 0 returns immediately.
https://github.com/rails/solid_queue/blob/9cd6bc3a16826d04c63ba667c93bd8cbb094db81/lib/solid_queue/processes/interruptible.rb#L19-L31
9cd6bc3a16826d04c63ba667c93bd8cbb094db81
solid_queue
github_2023
rails
ruby
ActiveSupport::TestCase.silence_on_thread_error_for
def silence_on_thread_error_for(expected, &block) current_proc = SolidQueue.on_thread_error SolidQueue.with(on_thread_error: silent_on_thread_error_for(expected, current_proc)) do block.call end end
# Silences specified exceptions during the execution of a block # # @param [Exception, Array<Exception>] expected an Exception or an array of Exceptions to ignore # @yield Executes the provided block with specified exception(s) silenced
https://github.com/rails/solid_queue/blob/9cd6bc3a16826d04c63ba667c93bd8cbb094db81/test/test_helper.rb#L85-L91
9cd6bc3a16826d04c63ba667c93bd8cbb094db81
dockerfile-rails
github_2023
fly-apps
ruby
DockerfileGenerator.api_client_dir
def api_client_dir if api_only? scan = "*/package.json" else scan = "{client,frontend}/package.json" end file = Dir[scan].find do |file| JSON.load_file(file).dig("scripts", "build") end file && File.dirname(file) end
# scan for node clients. Do a wide scan if api_only?, otherwise look # for specific directories.
https://github.com/fly-apps/dockerfile-rails/blob/f48c9f23fc888061dd94f170d37bb6260032dde8/lib/generators/dockerfile_generator.rb#L1250-L1262
f48c9f23fc888061dd94f170d37bb6260032dde8
128iid
github_2023
aleshevdenis
ruby
CheckmarxScaHelper.fetch_all_vulns_of_project
def fetch_all_vulns_of_project(token, scan_id) print_good "\n" print_good "Getting All vulnerabilities of ScanId: #{scan_id} \n" checkmarx_sca_vulnerabilites_api_url = "https://api-sca.checkmarx.net/risk-management/risk-reports/#{scan_id}/vulnerabilities" headers = { "Content-Type" => "application/json", "accept" => "application/json", "Authorization" => "Bearer #{token}" } auth_response = http_get(checkmarx_sca_vulnerabilites_api_url, headers) return nil unless auth_response begin vulns_results = JSON.parse(auth_response.body) print_good "Scan Results: \n" print_good vulns_results.to_s rescue JSON::ParserError print_error "Unable to process scans response!" end vulns_results end
# method to fetch all vuln of foreach project
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/checkmarx_sca/lib/checkmarx_sca_helper.rb#L83-L103
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
ExpanseIssues.ExpanseIssuesMapper.default_issue_field_mapping
def default_issue_field_mapping(issue_type) { "asset" => [ { action: "copy", source: "ip", target: "ip_address" }, { action: "proc", target: "hostname", proc: lambda { |x| temp = x["domain"] temp = x["assets"].first["displayName"] if temp.nil? && x["assets"].first["assetType"].match?(/Domain/im) # temp = temp.gsub("\*", "WILDCARD") unless temp.nil? temp } }, { action: "proc", target: "tags", proc: lambda { |x| temp = ["Expanse"] # always tag as 'Expanse' # Handle new businessUnits (plural) tag if x.key?("businessUnits") x["businessUnits"].foreach do |bu| temp << "businessUnit:#{bu.fetch('name')}" end end # Annotations are like tags, add foreach one # if x.key?("annotations") # x["annotations"]["tags"].foreach do |at| # temp << at.fetch("name") # end # end # flatten since we have an array of arrays temp.flatten } } ], "vuln" => [ { action: "proc", target: "vuln_def_name", proc: ->(_x) { issue_type } }, { action: "proc", target: "scanner_identifier", proc: ->(x) { x["id"] } }, { action: "proc", target: "created_at", proc: ->(x) { x["initialEvidence"]["timestamp"] } }, { action: "proc", target: "last_seen_at", proc: ->(x) { x["latestEvidence"]["timestamp"] } }, { action: "proc", target: "port", proc: ->(x) { (x["portNumber"] || x["initialEvidence"]["portNumber"]).to_i } }, { action: "proc", target: "details", proc: ->(x) { "Headline: #{x['headline']}\nHelpText: #{x['helpText']}\n\nFull Issue:\n #{JSON.pretty_generate(x)}" } }, { action: "proc", target: "scanner_score", proc: ->(x) { map_issue_priority(x["priority"]) } }, { action: "proc", target: "override_score", proc: ->(x) { map_issue_priority(x["priority"]).to_i * 10 } }, { action: "data", target: "scanner_type", data: "Expanse_issues" } ], "vuln_def" => [ { action: "data", target: "scanner_type", data: "Expanse_issues" }, { action: "proc", target: "name", proc: ->(_x) { issue_type } }, { action: "proc", target: "scanner_identifier", proc: ->(_x) { issue_type } }, { action: "proc", target: "description", proc: ->(x) { x["headline"] } }, { action: "data", target: "remediation", data: "Investigate this Issue!" } ] } end
### ### This method provides a field mapping for an exposure, giving the caller ### the ability to process foreach field later with the data it has. ###
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/digital_footprint/expanse_issues/lib/expanse_issues_mapper.rb#L120-L174
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.upload
def upload kdi_upload(@output_dir, "batch-#{millis}.json", @kenna_connector_id, @kenna_api_host, @kenna_api_key, @skip_autoclose, @max_retries, @kdi_version) end
# Uploads whatever's in memory into Kenna and then clears memory # # Note: Uploaded data does not get imported into Kenna automatically. It just sits there # until `kickoff` is called. # This allows for uploading in batches. Once a few batches have been uploaded and # you're happy for whatever is there to get imported into Kenna you can call `kickoff`
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L56-L58
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.add_assets_from_specifiers
def add_assets_from_specifiers(edgescan_location_specifiers, edgescan_vulnerabilities) # Convert location specifiers into kenna assets, remove any lists within lists, or duplicate assets kenna_assets = edgescan_location_specifiers.map(&:to_kenna_asset).flatten.uniq # Add any kenna assets, from vulnerabilities, that are not already present # This will only happen if a vulnerability does not have a corresponding host or location specifier kenna_assets.concat(edgescan_vulnerabilities.map(&:to_kenna_asset).uniq - kenna_assets) kenna_assets.foreach do |asset| add_asset(asset) end end
# Converts Edgescan location specifiers and vulnerabilities into Kenna assets and adds them to memory
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L68-L77
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.add_asset
def add_asset(kenna_asset) return if (@assets || []).map { |asset| asset["external_id"] }.include?(kenna_asset["external_id"]) create_kdi_asset(kenna_asset, false) end
# Adds Kenna asset into memory (if one with the same `external_id` doesn't exist already)
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L88-L92
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.add_finding
def add_finding(external_id, kenna_finding) create_kdi_asset_finding({ "external_id" => external_id }, kenna_finding, "external_id") end
# Adds Kenna finding into memory
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L100-L102
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
NetsparkerTask.map_state_to_triage_state
def map_state_to_triage_state(state_string) case state_string when "Present", /Revived|Scanning/ "new" when /False Positive/ "false_positive" when /Accepted Risk/ "risk_accepted" when /Fixed/ "resolved" when /Ignored/ "not_a_security_issue" end end
# Possible KDI values are: "new", "in_progress", "triaged", "resolved", "false_positive", "risk_accepted", "duplicate", "not_a_security_issue". # Possible Netsparker values are: Present, Accepted Risk, False Positive, Fixed (Unconfirmed), Fixed (Confirmed), Fixed (Can't Retest), Ignored, Revived, Scanning
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/netsparker/netsparker_task.rb#L202-L215
1709c456363b4f9aca306328bbad14555735d88b
searchlink
github_2023
ttscoff
ruby
SL.SearchLink.get_plugin_configs
def get_plugin_configs(default_config) SL::Searches.plugins[:search].each_value do |plugin| next unless plugin.key?(:config) && !plugin[:config].nil? && !plugin[:config].empty? plugin[:config].each do |cfg| new_config = get_plugin_config(cfg) default_config += new_config end end default_config end
# # Get plugin configs # # @param default_config [String] Existing configuration # # @return [String] default_config with plugin configurations added #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/config.rb#L241-L252
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.SearchLink.restore_prev_config
def restore_prev_config @prev_config&.each do |k, v| SL.config[k] = v $stderr.print "\r\033[0KReset config: #{k} = #{SL.config[k]}\n" unless SILENT end @prev_config = {} end
# Reset configuration
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/config.rb#L291-L297
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
footer
def footer @footer ||= [] end
# Stores the footer with reference links and footnotes
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L34-L36
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
originput
def originput @originput ||= "" end
# Stores the original input
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L54-L56
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
add_output
def add_output(str) print str if SL.printout && !SL.clipboard SL.output << str end
# Adds the given string to the output. # # @param str [String] The string to add. # # @return [nil] #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L122-L125
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
add_report
def add_report(str) return unless SL.config["report"] unless SL.line_num.nil? position = "#{SL.line_num}:" position += SL.match_column.nil? ? "0:" : "#{SL.match_column}:" position += SL.match_length.nil? ? "0" : SL.match_length.to_s end SL.report.push("(#{position}): #{str}") warn "(#{position}): #{str}" unless SILENT end
# Adds the given string to the report. # # @param str [String] The string to add. # # @return [nil] #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L174-L184
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
print_report
def print_report return if (SL.config["inline"] && SL.originput.split(/\n/).length == 1) || SL.clipboard return if SL.report.empty? out = "\n<!-- Report:\n#{SL.report.join("\n")}\n-->\n" add_output out end
# Prints the report. # # @return [String] The report. #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L209-L216
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.SemVer.initialize
def initialize(version_string) raise VersionError, "Invalid semantic version number: #{version_string}" unless version_string.valid_version? @maj, @min, @patch = version_string.split(/\./) @pre = nil if @patch =~ /(-?[^0-9]+\d*)$/ @pre = Regexp.last_match(1).sub(/^-/, "") @patch = @patch.sub(/(-?[^0-9]+\d*)$/, "") end @maj = @maj.to_i @min = @min.to_i @patch = @patch.to_i end
## Initialize a Semantic Version object ## ## @param version_string [String] a semantic version number ## ## @return [SemVer] SemVer object ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/semver.rb#L14-L27
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.clean
def clean gsub(/\n+/, " ") .gsub(/"/, "&quot") .gsub(/\|/, "-") .gsub(/([&?]utm_[scm].+=[^&\s!,.)\]]++?)+(&.*)/, '\2') .sub(/\?&/, "").strip end
## ## Remove newlines, escape quotes, and remove Google ## Analytics strings ## ## @return [String] cleaned URL/String ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L142-L148
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.remove_protocol
def remove_protocol sub(%r{^(https?|s?ftp|file)://}, "") end
## ## Remove the protocol from a URL ## ## @return [String] just hostname and path of URL ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L165-L167
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.remove_seo
def remove_seo(url) title = dup url = URI.parse(url) host = url.hostname unless host return self unless SL.config["debug"] SL.add_error("Invalid URL", "Could not remove SEO for #{url}") return self end path = url.path root_page = path =~ %r{^/?$} ? true : false title.gsub!(/\s*(&ndash;|&mdash;)\s*/, " - ") title.gsub!(/&[lr]dquo;/, '"') title.gsub!(/&[lr]dquo;/, "'") title.gsub!(/&#8211;/, " — ") title = CGI.unescapeHTML(title) title.gsub!(/ +/, " ") seo_title_separators = %w[| » « — – - · :] begin re_parts = [] host_parts = host.sub(/(?:www\.)?(.*?)\.[^.]+$/, '\1').split(/\./).delete_if { |p| p.length < 3 } h_re = !host_parts.empty? ? host_parts.map { |seg| seg.downcase.split(//).join(".?") }.join("|") : "" re_parts.push(h_re) unless h_re.empty? # p_re = path.path_elements.map{|seg| seg.downcase.split(//).join('.?') }.join('|') # re_parts.push(p_re) if p_re.length > 0 site_re = "(#{re_parts.join('|')})" dead_switch = 0 while title.downcase.gsub(/[^a-z]/i, "") =~ /#{site_re}/i break if dead_switch > 5 seo_title_separators.each_with_index do |sep, i| parts = title.split(/ *#{Regexp.escape(sep)} +/) next if parts.length == 1 remaining_separators = seo_title_separators[i..].map { |s| Regexp.escape(s) }.join("") seps = Regexp.new("^[^#{remaining_separators}]+$") longest = parts.longest_element.strip unless parts.empty? parts.delete_if do |pt| compressed = pt.strip.downcase.gsub(/[^a-z]/i, "") compressed =~ /#{site_re}/ && pt =~ seps ? !root_page : false end end title = if parts.empty? longest elsif parts.length < 2 parts.join(sep) elsif parts.length > 2 parts.longest_element.strip else parts.join(sep) end end dead_switch += 1 end rescue StandardError => e return self unless SL.config["debug"] SL.add_error("Error SEO processing title for #{url}", e) return self end seps = Regexp.new(" *[#{seo_title_separators.map { |s| Regexp.escape(s) }.join('')}] +") if title =~ seps seo_parts = title.split(seps) title = seo_parts.longest_element.strip if seo_parts.length.positive? end title && title.length > 5 ? title.gsub(/\s+/, " ") : CGI.unescapeHTML(self) end
## ## Remove SEO elements from a title ## ## @param url The url of the page from which the title came ## ## @return [String] cleaned title ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L257-L340
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.truncate!
def truncate!(max) replace truncate(max) end
## ## Truncate in place ## ## @see #truncate ## ## @param max [Number] The maximum length ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L349-L351
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_with_timeout
def search_with_timeout(search, timeout) url = nil title = nil link_text = nil begin Timeout.timeout(timeout) do url, title, link_text = search.call end rescue Timeout::Error SL.add_error("Timeout", "Search timed out") url, title, link_text = false end [url, title, link_text] end
## ## Execute a search with deadman's switch ## ## @param search [Proc] The search command ## @param timeout [Number] The timeout ## ## @return [Array] url, title, link_text ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/util.rb#L58-L73
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
cache_file_for
def cache_file_for(filename) cache_folder = File.expand_path("~/.config/searchlink/cache") FileUtils.mkdir_p(cache_folder) unless File.directory?(cache_folder) File.join(cache_folder, filename.sub(/(\.cache)?$/, ".cache")) end
## ## Get the path for a cache file ## ## @param filename [String] The filename to ## generate the cache for ## ## @return [String] path to new cache file ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/util.rb#L83-L87
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_paths
def search_paths(path = ENV["PATH"]) paths = if path && !path.empty? path.split(::File::PATH_SEPARATOR) else %w[/usr/local/bin /usr/ucb /usr/bin /bin /opt/homebrew/bin] end paths.select(&Dir.method(:exist?)) end
# Find default system paths # # @param [String] path # the path to search through # # @example # search_paths("/usr/local/bin:/bin") # # => ["/bin"] # # @return [Array<String>] # the array of paths to search # # @api private
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/which.rb#L87-L94
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
file_with_path?
def file_with_path?(cmd) ::File.expand_path(cmd) == cmd end
# Check if executable file is part of absolute/relative path # # @param [String] cmd # the executable to check # # @return [Boolean] # # @api private
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/which.rb#L165-L167
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
Curl.Html.extract_tag
def extract_tag(tag, attribute = nil, source: false, content: false) res = extract_tag_contents(tag, source: true) return res if source res.map! do |tag_source| m = tag_source.to_enum(:scan, /(\S+)=(['"])(.*?)\2/).map { Regexp.last_match } attrs = m.each_with_object({}) { |at, a| a[at[1]] = at[3] } tags = tag_source.match(/<.*?>(?<content>.*?)</) contents = tags.nil? ? nil : tags["content"] { tag: tag, source: tag_source, attrs: attrs, content: contents } end return res.map { |r| r[:content] } if content return res if attribute.nil? res.map { |r| r[:attrs][attribute] } end
## ## Extract an array of tags or tag attributes ## ## @param tag [String] The tag ## @param attribute [String] The attribute ## @param source [Boolean] Return full tag source ## (negates attribute if true) ## @param content [Boolean] Return only tag ## contents ## ## @return [Hash, Array] if source, return array of full ## tags, if content, return array of tag contents, ## otherwise, return a hash of tags including ## attributes and content ## ## If attribute is not given, tag contents will be returned ## ## @example page.extract_tag('h1') => [Array of h1 tag ## contents] ## @example page.extract_tag('img', 'src') => [Array of img ## src attributes] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/curl/html.rb#L79-L102
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
Curl.Html.content_tags
def content_tags(content) return nil if content.nil? res = content.to_enum(:scan, %r{(?mix) <(?<tag>(?!</)[a-z0-9]+)(?<attrs>\s[^>]+)? (?:\s*/>|>(?<content>.*?)</\k<tag>>)}).map { Regexp.last_match } res.map do |tag| if tag["attrs"].nil? attrs = nil else attrs = tag["attrs"].strip.to_enum(:scan, /(?ix) (?<key>[@a-z0-9-]+)(?:=(?<quot>["']) (?<value>[^"']+)\k<quot>|[ >])?/i).map { Regexp.last_match } attrs.map! { |a| { key: a["key"], value: a["key"] =~ /^(class|rel)$/ ? a["value"].split(/ /) : a["value"] } } end { tag: tag["tag"], source: tag.to_s, attrs: attrs, content: tag["content"], tags: content_tags(tag["content"]) } end end
## ## Return an array of all tags in the content ## ## @param content [String] The content to parse ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/curl/html.rb#L243-L266
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
applemusic
def applemusic(terms, media = "music", entity = "") url = "https://itunes.apple.com/search?term=#{terms.url_encode}&country=#{SL.config['country_code']}&media=#{media}&entity=#{entity}" page = Curl::Json.new(url, compressed: true, symbolize_names: true) json = page.json return false unless json[:resultCount]&.positive? output = process_result(json[:results][0]) return false if output.empty? output end
# Search apple music # terms => search terms (unescaped) # media => music, podcast # entity => optional: artist, song, album, podcast # returns {:type=>,:id=>,:url=>,:title}
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/applemusic.rb#L76-L87
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_hook
def search_hook(search) types = %w[name path address] query = search.strip.split(" ").map { |s| types.map { |t| %(#{t} contains "#{s}") }.join(" or ") } query = query.map { |q| "(#{q})" }.join(" and ") path_matches = run_query(query) top_match = path_matches.uniq.first return false unless top_match [top_match[:url], top_match[:name]] end
# Search bookmark paths and addresses. Return array of bookmark hashes.
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/hook.rb#L64-L74
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search
def search(search_type, search_terms, link_text) # You can branch to multiple searches by testing the search_type case search_type when /e$/ url, title = SL.ddg("site:genius.com #{search_terms}", link_text) if url title = get_lyrics(url) # To return an embed, set url (first parameter in the return # array) to 'embed', and put the embed contents in the second # parameter. title ? ["embed", title, link_text] : false else # Use `SL#add_error(title, text)` to add errors to the HTML # report. The report will only be shown if errors have been added. SL.add_error("No lyrics found", "Song lyrics for #{search_terms} not found") false end when /js$/ url, title = SL.ddg("site:genius.com #{search_terms}", link_text) if url title = js_embed(url) title ? ["embed", title, link_text] : false else SL.add_error("No lyrics found", "Song lyrics for #{search_terms} not found") false end else # You can perform a DuckDuckGo search using SL#ddg, passing the # search terms and link_text. It will return url, title, and # link_text. SL#ddg will add its own errors, and if it returns false # that will automatically be tested for, no additional error # handling is required. url, title, link_text = SL.ddg("site:genius.com #{search_terms}", link_text) # Always return an array containing the resulting URL, the title, # and the link_text variable that was passed in, even if it's # unmodified. [url, title, link_text] end end
# Every plugin must contain a #search method that takes 3 arguments: # # - `search_type` will contain the !search trigger that was used (minus the !) # - `search_terms` will include everything that came after the !search # - `link_text` will contain the text that will be used for the linked # text portion of the link. This can usually remain untouched but must # be passed back at the end of the function.
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/lyrics.rb#L53-L91
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search
def search(_, search_terms, link_text) unless SL.config["pinboard_api_key"] SL.add_error("Missing Pinboard API token", "Find your api key at https://pinboard.in/settings/password and add it to your configuration (pinboard_api_key: YOURKEY)") return false end exact_match = false match_phrases = [] # If search terms start with ''term, only search for exact string matches case search_terms when /^ *'/ exact_match = true search_terms.gsub!(/(^ *'+|'+ *$)/, "") when /%22(.*?)%22/ match_phrases = search_terms.scan(/%22(\S.*?\S)%22/) search_terms.gsub!(/%22(\S.*?\S)%22/, "") end cache = load_pinboard_cache # cache = pinboard_bookmarks bookmarks = cache["bookmarks"] if exact_match bookmarks.each do |bm| text = [bm["description"], bm["extended"], bm["tags"]].join(" ") return [bm["href"], bm["description"], link_text] if text.matches_exact(search_terms) end return false end unless match_phrases.empty? bookmarks.delete_if do |bm| matched = tru full_text = [bm["description"], bm["extended"], bm["tags"]].join(" ") match_phrases.each do |phrase| matched = false unless full_text.matches_exact(phrase) end !matched end end matches = [] bookmarks.each do |bm| title_tags = [bm["description"], bm["tags"]].join(" ") full_text = [bm["description"], bm["extended"], bm["tags"]].join(" ") score = if title_tags.matches_exact(search_terms) 14.0 elsif full_text.matches_exact(search_terms) 13.0 elsif full_text.matches_any(search_terms) full_text.matches_score(search_terms) else 0 end return [bm["href"], bm["description"], link_text] if score == 14 next unless score.positive? matches.push({ score: score, href: bm["href"], title: bm["description"], date: bm["time"] }) end return false if matches.empty? top = matches.max_by { |bm| [bm[:score], bm[:date]] } return false unless top [top[:href], top[:title], link_text] end
# Search pinboard bookmarks # Begin query with '' to force exact matching (including description text) # Regular matching searches for each word of query and scores the bookmarks # exact matches in title get highest score # exact matches in description get second highest score # other bookmarks are scored based on the number of words that match # # After sorting by score, bookmarks will be sorted by date and the most recent # will be returned # # Exact matching is case and punctuation insensitive
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/pinboard.rb#L107-L187
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_edge_history
def search_edge_history(term) base = File.expand_path("~/Library/Application Support/Microsoft Edge/") profiles = Dir.glob("**/History", base: base) profiles.delete_if { |p| p =~ /^Snapshots/ } profiles.map! { |f| File.join(base, f) } res = false profiles.each do |bookmarks| next unless File.exist?(bookmarks) profile = bookmarks.match(%r{Edge/([^/]+)/})[1] SL.notify("Searching Chrome History for profile #{profile}", term) res = search_chromium_history(bookmarks, term) break if res end res end
## Search Edge history ## ## @param term The search term ## ## @return [Array] Single bookmark, [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L61-L81
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_edge_bookmarks
def search_edge_bookmarks(term) base = File.expand_path("~/Library/Application Support/Microsoft Edge") profiles = Dir.glob("**/Bookmarks", base: base) profiles.delete_if { |p| p =~ /^Snapshots/ } profiles.map! { |f| File.join(base, f) } res = false profiles.each do |bookmarks| next unless File.exist?(bookmarks) profile = bookmarks.match(%r{Edge/([^/]+)/})[1] SL.notify("Searching Edge Bookmarks for profile #{profile}", term) res = search_chromium_bookmarks(bookmarks, term) break if res end res end
## ## Search Ege bookmarks ## ## @param term [String] The search term ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L224-L243
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_chrome_bookmarks
def search_chrome_bookmarks(term) base = File.expand_path("~/Library/Application Support/Google/Chrome/") profiles = Dir.glob("**/Bookmarks", base: base) profiles.delete_if { |p| p =~ /^Snapshots/ } profiles.map! { |f| File.join(base, f) } res = false profiles.each do |bookmarks| next unless File.exist?(bookmarks) profile = bookmarks.match(%r{Chrome/([^/]+)/})[1] SL.notify("Searching Chrome Bookmarks for profile #{profile}", term) res = search_chromium_bookmarks(bookmarks, term) break if res end res end
## ## Search Chrome bookmarks ## ## @param term [String] The search term ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L252-L271
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_arc_json
def search_arc_json(bookmarks_file, term) arc_bookmarks = JSON.parse(IO.read(bookmarks_file)) exact_match = false match_phrases = [] # If search terms start with ''term, only search for exact string matches if term =~ /^ *'/ exact_match = true term.gsub!(/(^ *'+|'+ *$)/, "") elsif term =~ /%22(.*?)%22/ match_phrases = term.scan(/%22(\S.*?\S)%22/) term.gsub!(/%22(\S.*?\S)%22/, "") end if arc_bookmarks bookmarks = [] arc_bookmarks["sidebarSyncState"]["items"].each do |mark| next if mark.is_a?(String) next unless mark["value"]["childrenIds"].empty? next unless mark["value"]["data"]["tab"] url = { url: mark["value"]["data"]["tab"]["savedURL"], saved_title: mark["value"]["data"]["tab"]["savedTitle"], title: mark["value"]["title"], created: mark["value"]["createdAt"].to_datetime, active: mark["value"]["data"]["tab"]["timeLastActiveAt"]&.to_datetime } score = score_mark(url, term) if score > 7 url[:score] = score bookmarks << url end end unless bookmarks.empty? if exact_match bookmarks.delete_if do |bm| !(bm[:url].matches_exact(term) || bm[:title].matches_exact(term) || bm[:saved_title].matches_exact(term)) end end if match_phrases match_phrases.map! { |phrase| phrase[0] } bookmarks.delete_if do |bm| matched = true match_phrases.each do |phrase| matched = false unless bm[:url].matches_exact(phrase) || bm[:title].matches_exact(phrase) || bm[:saved_title].matches_exact(phrase) end !matched end end return false if bookmarks.empty? lastest_bookmark = bookmarks.min_by { |u| u[:created] } return [lastest_bookmark[:url], lastest_bookmark[:title], lastest_bookmark[:date]] end end false end
## ## Search Arc/JSON bookmarks ## ## @param bookmarks_file [String] path to bookmarks file ## @param term [String] the string to search for ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L281-L352
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_chromium_bookmarks
def search_chromium_bookmarks(bookmarks_file, term) chrome_bookmarks = JSON.parse(IO.read(bookmarks_file)) exact_match = false match_phrases = [] # If search terms start with ''term, only search for exact string matches if term =~ /^ *'/ exact_match = true term.gsub!(/(^ *'+|'+ *$)/, "") elsif term =~ /%22(.*?)%22/ match_phrases = term.scan(/%22(\S.*?\S)%22/) term.gsub!(/%22(\S.*?\S)%22/, "") end if chrome_bookmarks roots = chrome_bookmarks["roots"] urls = extract_chrome_bookmarks(roots, [], term) unless urls.empty? urls.delete_if { |bm| !(bm[:url].matches_exact(term) || bm[:title].matches_exact(term)) } if exact_match if match_phrases match_phrases.map! { |phrase| phrase[0] } urls.delete_if do |bm| matched = true match_phrases.each do |phrase| matched = false unless bm[:url].matches_exact(phrase) || bm[:title].matches_exact(phrase) end !matched end end return false if urls.empty? lastest_bookmark = urls.max_by { |u| u[:score] } return [lastest_bookmark[:url], lastest_bookmark[:title], lastest_bookmark[:date]] end end false end
## ## Generic chromium bookmark search ## ## @param bookmarks_file [String] The path to ## bookmarks file for ## selected browser ## @param term [String] The term ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L364-L407
70a0d794424e2312833310fdf8aeb78d18d13183
ubicloud
github_2023
ubicloud
ruby
Hosting::HetznerApis.reset
def reset(server_id, dist: "Ubuntu 22.04.2 LTS base") create_connection.post(path: "/reset/#{server_id}", body: "type=hw", expects: 200) nil end
# Cuts power to a Server and starts it again. This forcefully stops it # without giving the Server operating system time to gracefully stop. This # may lead to data loss, it’s equivalent to pulling the power cord and # plugging it in again. Reset should only be used when reboot does not work.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/lib/hosting/hetzner_apis.rb#L31-L34
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
Strand.load
def load(snap = nil) Object.const_get("::Prog::" + prog).new(self, snap) end
# :nocov:
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/strand.rb#L76-L78
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
VmHost.download_cloud_hypervisor
def download_cloud_hypervisor(version_x64: nil, version_arm64: nil, sha256_ch_bin_x64: nil, sha256_ch_bin_arm64: nil, sha256_ch_remote_x64: nil, sha256_ch_remote_arm64: nil) version, sha256_ch_bin, sha256_ch_remote = if arch == "x64" [version_x64, sha256_ch_bin_x64, sha256_ch_remote_x64] elsif arch == "arm64" [version_arm64, sha256_ch_bin_arm64, sha256_ch_remote_arm64] else fail "BUG: unexpected architecture" end fail ArgumentError, "No version provided" if version.nil? Strand.create_with_id(prog: "DownloadCloudHypervisor", label: "start", stack: [{subject_id: id, version: version, sha256_ch_bin: sha256_ch_bin, sha256_ch_remote: sha256_ch_remote}]) end
# Introduced for downloading cloud hypervisor via REPL.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/vm_host.rb#L235-L245
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
VmHost.hardware_reset
def hardware_reset Hosting::Apis.hardware_reset_server(self) end
# Cuts power to a Server and starts it again. This forcefully stops it # without giving the Server operating system time to gracefully stop. This # may lead to data loss, it’s equivalent to pulling the power cord and # plugging it in again. Reset should only be used when reboot does not work.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/vm_host.rb#L282-L284
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
VmHostSlice.allowed_cpus_cgroup
def allowed_cpus_cgroup @allowed_cpus_cgroup ||= cpus.map(&:cpu_number).sort.slice_when { |a, b| b != a + 1 }.map do |group| (group.size > 1) ? "#{group.first}-#{group.last}" : group.first.to_s end.join(",") end
# We use cgroup format here, which looks like: # 2-3,6-10 # (comma-separated ranges of cpus)
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/vm_host_slice.rb#L21-L25
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
Prog::Ai::InferenceEndpointReplicaNexus.ping_gateway
def ping_gateway api_key_ds = DB[:api_key] .where(owner_table: "project") .where(used_for: "inference_endpoint") .where(is_valid: true) .where(owner_id: Sequel[:project][:id]) .exists eligible_projects_ds = Project.where(api_key_ds) eligible_projects_ds = eligible_projects_ds.where(id: inference_endpoint.project.id) unless inference_endpoint.is_public eligible_projects = eligible_projects_ds.all .select(&:active?) .map do { ubid: _1.ubid, api_keys: _1.api_keys.select { |k| k.used_for == "inference_endpoint" && k.is_valid }.map { |k| Digest::SHA2.hexdigest(k.key) }, quota_rps: 50.0, quota_tps: 5000.0 } end body = { replica_ubid: inference_endpoint_replica.ubid, public_endpoint: inference_endpoint.is_public, projects: eligible_projects } resp = vm.sshable.cmd("sudo curl -m 5 -s -H \"Content-Type: application/json\" -X POST --data-binary @- --unix-socket /ie/workdir/inference-gateway.clover.sock http://localhost/control", stdin: body.to_json) project_usage = JSON.parse(resp)["projects"] Clog.emit("Successfully pinged inference gateway.") { {inference_endpoint: inference_endpoint.ubid, replica: inference_endpoint_replica.ubid, project_usage: project_usage} } update_billing_records(project_usage) end
# pushes latest config to inference gateway and collects billing information
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/prog/ai/inference_endpoint_replica_nexus.rb#L164-L196
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
Prog::Vnet::UpdateFirewallRules.consolidate_rules
def consolidate_rules(rules) port_segments = create_port_segments(rules) consolidated_rules = [] port_segments.each do |segment| # Find rules that overlap with the current segment overlapping_rules = rules.select do |r| r.port_range.begin <= segment[:end] && r.port_range.end - 1 >= segment[:begin] end # Merge cidrs for overlapping rules merged_cidrs = if rules.first.cidr.version == 4 NetAddr.summ_IPv4Net(overlapping_rules.map(&:cidr)) else NetAddr.summ_IPv6Net(overlapping_rules.map(&:cidr)) end merged_cidrs.each do |cidr| consolidated_rules << FirewallRuleObj.new(cidr, {begin: segment[:begin], end: segment[:end] + 1}) end end combined_rules = combine_continuous_ranges_for_same_subnet(consolidated_rules) combined_rules_self = combined_rules.map do |r| if r.port_range[:begin] != r.port_range[:end] - 1 "#{r.cidr} . #{r.port_range[:begin]}-#{r.port_range[:end] - 1}" else "#{r.cidr} . #{r.port_range[:begin]}" end end.join(",") combined_rules_lb_dest = vm.load_balancer ? combined_rules.filter_map do |r| if r.port_range[:begin] <= vm.load_balancer.src_port && vm.load_balancer.src_port <= r.port_range[:end] - 1 "#{r.cidr} . #{vm.load_balancer.dst_port}" end end.join(",") : [] [combined_rules_self, combined_rules_lb_dest] end
# This method is needed to properly consolidate port_ranges + cidrs. # For example, if we have the following rules: # 1. 10.10.10.8/29 . 80-8080 # 2. 10.10.10.0/27 . 5432-10000 # # We can't just merge the cidrs because the port ranges overlap. We need to # first identify where the overlap is in the port ranges and then merge the # cidrs for the overlapping port ranges. The result should be: # 1. 10.10.10.8/29 . 80-5431 # 2. 10.10.10.0/27 . 5432-10000 # # In the processing of these 2 rules, we first identify the port segments as; # 1. 80-5431 # 2. 5432-8080 # 3. 8081-10000 # # Then we identify the cidrs for each segment: # 1. 10.10.10.8/29 (This is simply used from the first rule because the first # rule is the only rule that has a cidr that overlaps with this segment) # 2. 10.10.10.8/29 + 10.10.10.0/27: The combination of these will result in # 10.10.10.0/27 # 3. 10.10.10.0/27 (This is simply used from the second rule because the # second rule is the only rule that has a cidr that overlaps with this # segment) # # For the combination of the cidrs, we use the summ_IPv4/6Net method from the # netaddr gem. This method will combine the cidrs and remove any duplicates. # If we don't perform this combination, we will end up with an error from # nftables saying file exists. # # Additionally, the customers may have thousands of rules and possibly, they # overlap. We want to minimize the number of rules that we create on the # nftables side to avoid performance issues.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/prog/vnet/update_firewall_rules.rb#L220-L256
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
r
def r(commandline, stdin: "", expect: [0]) stdout, stderr, status = Open3.capture3(commandline, stdin_data: stdin) fail CommandFail.new("command failed: " + commandline, stdout, stderr) unless expect.include?(status.exitstatus) stdout end
# rubocop:enable Lint/InheritException
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/rhizome/common/lib/util.rb#L27-L31
05593ec0c7f3cbae7ef9214933d69a50bd29e947
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Configuration.serpapi_api_key
def serpapi_api_key(**kwargs) key_lookup(:serpapi_api_key, kwargs) end
# @return [String] The SerpAPI API key either from arg or env.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars.rb#L46-L48
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Boxcar.validate_inputs
def validate_inputs(inputs:) missing_keys = input_keys - inputs.keys raise "Missing some input keys: #{missing_keys}" if missing_keys.any? inputs end
# Check that all inputs are present. # @param inputs [Hash] The inputs. # @raise [RuntimeError] If the inputs are not the same.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar.rb#L33-L38
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Boxcar.apply
def apply(input_list:) raise NotImplementedError end
# Apply the boxcar to a list of inputs. # @param input_list [Array<Hash>] The list of inputs. # @return [Array<Boxcars::Boxcar>] The list of outputs.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar.rb#L57-L59
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Boxcar.save
def save(path:) File.write(path, YAML.dump(self)) end
# save this boxcar to a file
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar.rb#L110-L112
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Conversation.check_lines
def check_lines(lines) raise ArgumentError, "Lines must be an array" unless lines.is_a?(Array) lines.each do |ln| raise ArgumentError, "Conversation item must be a array" unless ln.is_a?(Array) raise ArgumentError, "Conversation item must have 2 items, role and text" unless ln.size == 2 raise ArgumentError, "Conversation item must have a role #{ln} in (#{PEOPLE})" unless PEOPLE.include? ln[0] end end
# check the lines
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation.rb#L16-L24
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Conversation.to_a
def to_a lines end
# @return [Array] The result as a convesation array
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation.rb#L27-L29
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Conversation.as_messages
def as_messages(inputs = nil) { messages: no_history.map { |ln| { role: ln.first, content: cformat(ln.last, inputs) } } } rescue ::KeyError => e first_line = e.message.to_s.split("\n").first Boxcars.error "Missing prompt input key: #{first_line}" raise KeyError, "Prompt format error: #{first_line}" end
# compute the prompt parameters with input substitutions (used for chatGPT) # @param inputs [Hash] The inputs to use for the prompt. # @return [Hash] The formatted prompt { messages: ...}
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation.rb#L90-L96
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.ConversationPrompt.as_messages
def as_messages(inputs) conversation.as_messages(inputs) end
# prompt for chatGPT params # @param inputs [Hash] The inputs to use for the prompt. # @return [Hash] The formatted prompt.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation_prompt.rb#L20-L22
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.ConversationPrompt.with_conversation
def with_conversation(conversation) return self unless conversation new_prompt = dup new_prompt.conversation.add_conversation(conversation) new_prompt end
# tack on the ongoing conversation if present to the prompt
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation_prompt.rb#L32-L38
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Engine.initialize
def initialize(description: 'Engine', name: nil, prompts: [], batch_size: 20) @name = name || self.class.name @description = description @prompts = prompts @batch_size = batch_size end
# An Engine is used by Boxcars to generate output from prompts # @param name [String] The name of the Engine. Defaults to classname. # @param description [String] A description of the Engine. # @param prompts [Array<Prompt>] The prompts to use for the Engine. # @param batch_size [Integer] The number of prompts to send to the Engine at a time.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine.rb#L13-L18
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Train.return_stopped_response
def return_stopped_response(early_stopping_method, intermediate_steps, **kwargs) case early_stopping_method when "force" TrainFinish.new({ output: "Agent stopped due to max iterations." }, "") when "generate" thoughts = "" intermediate_steps.each do |action, observation| thoughts += action.log thoughts += "\n#{observation_text(observation)}\n#{engine_prefix}" end thoughts += "\n\nI now need to return a final answer based on the previous steps:" new_inputs = { agent_scratchpad: thoughts, stop: _stop } full_inputs = kwargs.merge(new_inputs) full_output = predict(**full_inputs) parsed_output = extract_boxcar_and_input(full_output) if parsed_output.nil? TrainFinish.new({ output: full_output }, full_output) else boxcar, boxcar_input = parsed_output Boxcars.debug "Got boxcar #{boxcar} and input #{boxcar_input}" if boxcar == finish_boxcar_name TrainFinish.new({ output: boxcar_input }, full_output) else TrainFinish.new({ output: full_output }, full_output) end end else raise "early_stopping_method should be one of `force` or `generate`, got #{early_stopping_method}" end end
# get the stopped response # @param early_stopping_method [String] The early stopping method. # @param intermediate_steps [Array] The intermediate steps. # @param kwargs [Hash] extra keword arguments. # @return [Boxcars::Action] The action to take.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train.rb#L156-L185
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Train.call
def call(inputs:) prepare_for_new_call intermediate_steps = [] iterations = 0 while should_continue?(iterations) output = plan(intermediate_steps, **inputs) return pre_return(output, intermediate_steps) if output.is_a?(TrainFinish) if (boxcar = name_to_boxcar_map[output.boxcar]) begin observation = Observation.ok(get_boxcar_result(boxcar, output.boxcar_input)) return_direct = boxcar.return_direct rescue Boxcars::ConfigurationError, Boxcars::SecurityError => e raise e rescue StandardError => e Boxcars.error "Error in #{boxcar.name} train#call: #{e}\nbt:#{caller[0..5].join("\n ")}", :red observation = Observation.err("Error - #{e}, correct and try again.") end elsif output.boxcar == :error observation = output.log return_direct = false else observation = Observation.err("Error - #{output.boxcar} is not a valid action, try again.") return_direct = false end Boxcars.debug "Observation: #{observation}", :green intermediate_steps.append([output, observation]) if return_direct output = TrainFinish.new({ return_values[0] => observation }, "") return pre_return(output, intermediate_steps) end iterations += 1 end output = return_stopped_response(early_stopping_method, intermediate_steps, **inputs) pre_return(output, intermediate_steps) end
# execute the train train # @param inputs [Hash] The inputs. # @return [Hash] The output.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train.rb#L202-L237
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.VectorSearch.call
def call(query:, count: 1) validate_query(query) query_vector = convert_query_to_vector(query) @vector_search_instance.call(query_vector: query_vector, count: count) end
# @param query [String] The query to search for. # @param count [Integer] The number of results to return. # @return [Array] array of hashes with :document and :distance keys # @example # [ # { # document: Boxcars::VectorStore::Document.new( # content: "hello", # embedding: [0.1, 0.2, 0.3], # metadata: { a: 1 } # ), # distance: 0.1 # } # ]
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/vector_search.rb#L42-L46
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.EngineBoxcar.initialize
def initialize(prompt:, engine: nil, **kwargs) @prompt = prompt @engine = engine || Boxcars.engine.new @top_k = kwargs.delete(:top_k) || 5 @stop = kwargs.delete(:stop) || ["Answer:"] super(**kwargs) end
# A Boxcar is a container for a single tool to run. # @param prompt [Boxcars::Prompt] The prompt to use for this boxcar with sane defaults. # @param engine [Boxcars::Engine] The engine to user for this boxcar. Can be inherited from a train if nil. # @param kwargs [Hash] Additional arguments including: name, description, top_k, return_direct, and stop
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar/engine_boxcar.rb#L13-L19
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.EngineBoxcar.input_key
def input_key input_keys.first end
# the first input key for the prompt
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar/engine_boxcar.rb#L27-L29
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.JSONEngineBoxcar.extract_answer
def extract_answer(data) reply = data Result.new(status: :ok, answer: reply, explanation: reply) end
# get answer from parsed JSON # @param data [Hash] The data to extract from. # @return [Result] The result.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar/json_engine_boxcar.rb#L66-L69
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Anthropic.get_num_tokens
def get_num_tokens(text:) text.split.length # TODO: hook up to token counting gem end
# calculate the number of tokens used
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/anthropic.rb#L159-L161
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Anthropic.max_tokens_for_prompt
def max_tokens_for_prompt(prompt_text) num_tokens = get_num_tokens(prompt_text) # get max context size for model by name max_size = modelname_to_contextsize(model_name) max_size - num_tokens end
# Calculate the maximum number of tokens possible to generate for a prompt. # @param prompt_text [String] The prompt text to use. # @return [Integer] the number of tokens possible to generate.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/anthropic.rb#L172-L178
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Cohere.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], **kwargs) @llm_params = DEFAULT_PARAMS.merge(kwargs) @prompts = prompts @batch_size = 20 super(description: description, name: name) end
# A engine is the driver for a single tool to run. # @param name [String] The name of the engine. Defaults to "OpenAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [Array<String>] The prompts to use when asking the engine. Defaults to [].
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/cohere.rb#L28-L33
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.GeminiAi.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], batch_size: 20, **kwargs) @llm_parmas = DEFAULT_PARAMS.merge(kwargs) @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "GeminiAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [Array<String>] The prompts to use when asking the engine. Defaults to []. # @param batch_size [Integer] The number of prompts to send to the engine at once. Defaults to 20.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gemini_ai.rb#L27-L32
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.GeminiAi.run
def run(question, **kwargs) prompt = Prompt.new(template: question) response = client(prompt: prompt, **kwargs) raise Error, "GeminiAI: No response from API" unless response check_response(response) response["choices"].map { |c| c.dig("message", "content") || c["text"] }.join("\n").strip end
# get an answer from the engine for a question. # @param question [String] The question to ask the engine. # @param kwargs [Hash] Additional parameters to pass to the engine if wanted.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gemini_ai.rb#L69-L76
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.GeminiAi.default_params
def default_params llm_params end
# Get the default parameters for the engine.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gemini_ai.rb#L79-L81
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Gpt4allEng.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], batch_size: 2, **_kwargs) @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "OpenAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [Array<String>] The prompts to use when asking the engine. Defaults to []. # @param batch_size [Integer] The number of prompts to send to the engine at once. Defaults to 2.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gpt4all_eng.rb#L22-L26
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Gpt4allEng.client
def client(prompt:, inputs: {}, **_kwargs) gpt4all = Gpt4all::ConversationalAI.new gpt4all.prepare_resources(force_download: false) gpt4all.start_bot input_text = prompt.as_prompt(inputs: inputs)[:prompt] Boxcars.debug("Prompt after formatting:\n#{input_text}", :cyan) if Boxcars.configuration.log_prompts gpt4all.prompt(input_text) rescue StandardError => e Boxcars.error(["Error from gpt4all engine: #{e}", e.backtrace[-5..-1]].flatten.join("\n ")) ensure gpt4all.stop_bot end
# Get an answer from the engine. # @param prompt [String] The prompt to use when asking the engine. # @param openai_access_token [String] The access token to use when asking the engine. # Defaults to Boxcars.configuration.openai_access_token. # @param kwargs [Hash] Additional parameters to pass to the engine if wanted.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gpt4all_eng.rb#L33-L44
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Gpt4allEng.run
def run(question, **kwargs) prompt = Prompt.new(template: question) answer = client(prompt: prompt, **kwargs) Boxcars.debug("Answer: #{answer}", :cyan) answer end
# get an answer from the engine for a question. # @param question [String] The question to ask the engine. # @param kwargs [Hash] Additional parameters to pass to the engine if wanted.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gpt4all_eng.rb#L49-L54
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.IntelligenceBase.default_model_params
def default_model_params {} end
# can be overridden by provider subclass
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/intelligence_base.rb#L24-L26
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.IntelligenceBase.validate_content
def validate_content(content) raise ArgumentError, "Content must have type and text fields" unless content[:type] && content[:text] content end
# Validate content structure
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/intelligence_base.rb#L53-L57
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Openai.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], batch_size: 20, **kwargs) @open_ai_params = DEFAULT_PARAMS.merge(kwargs) if @open_ai_params[:model] =~ /^o/ && @open_ai_params[:max_tokens].present? @open_ai_params[:max_completion_tokens] = @open_ai_params.delete(:max_tokens) @open_ai_params.delete(:temperature) end @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "OpenAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [Array<String>] The prompts to use when asking the engine. Defaults to []. # @param batch_size [Integer] The number of prompts to send to the engine at once. Defaults to 20.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/openai.rb#L29-L39
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Openai.check_response
def check_response(response, must_haves: %w[choices]) if response['error'] code = response.dig('error', 'code') msg = response.dig('error', 'message') || 'unknown error' raise KeyError, "OPENAI_ACCESS_TOKEN not valid" if code == 'invalid_api_key' raise ValueError, "OpenAI error: #{msg}" end must_haves.each do |key| raise ValueError, "Expecting key #{key} in response" unless response.key?(key) end end
# make sure we got a valid response # @param response [Hash] The response to check. # @param must_haves [Array<String>] The keys that must be in the response. Defaults to %w[choices]. # @raise [KeyError] if there is an issue with the access token. # @raise [ValueError] if the response is not valid.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/openai.rb#L109-L121
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Perplexityai.initialize
def initialize(name: DEFAULT_PER_NAME, description: DEFAULT_PER_DESCRIPTION, prompts: [], batch_size: 20, **kwargs) @perplexity_params = DEFAULT_PER_PARAMS.merge(kwargs) @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "PerplexityAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [Array<String>] The prompts to use when asking the engine. Defaults to []. # @param batch_size [Integer] The number of prompts to send to the engine at once. Defaults to 20.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/perplexityai.rb#L27-L32
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.TrainAction.initialize
def initialize(boxcar:, log:, boxcar_input: nil) @boxcar_input = boxcar_input @boxcar = boxcar @log = log end
# record for a train action # @param boxcar [String] The boxcar to run. # @param log [String] The log of the action. # @param boxcar_input [String] The input to the boxcar. # @return [Boxcars::TrainAction] The train action.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train/train_action.rb#L13-L17
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.ZeroShot.extract_boxcar_and_input
def extract_boxcar_and_input(text) get_action_and_input(engine_output: text) rescue StandardError => e [:error, e.message] end
# Extract the boxcar and input from the engine output. # @param text [String] The output from the engine. # @return [Array<Boxcars::Boxcar, String>] The boxcar and input.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train/zero_shot.rb#L30-L34
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.VectorStore.InMemory.BuildFromFiles.initialize
def initialize(params) @split_chunk_size = params[:split_chunk_size] || 2000 @training_data_path = File.absolute_path(params[:training_data_path]) @embedding_tool = params[:embedding_tool] || :openai validate_params(embedding_tool, training_data_path) @memory_vectors = [] end
# initialize the vector store with the following parameters: # @param params [Hash] A Hash containing the initial configuration. # @option params [Symbol] :embedding_tool The embedding tool to use. # @option params [String] :training_data_path The path to the training data files. # @option params [Integer] :split_chunk_size The number of characters to split the text into. # @return [Hash] vector_store: array of hashes with :content, :metadata, and :embedding keys
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/vector_store/in_memory/build_from_files.rb#L15-L22
9a294a13e96cbb628adb542807464e81a94d6535
GlobalSfMpy
github_2023
zhangganlin
ruby
set_distance_type!
def set_distance_type! distance_function Flann.send(:flann_set_distance_type, distance_function, get_distance_order) self end
# Set the distance function to use when computing distances between data points.
https://github.com/zhangganlin/GlobalSfMpy/blob/ac6a0564d84e1d6e9a4077195e384d379aa20492/thirdparty/TheiaSfM/libraries/flann/src/ruby/lib/flann.rb#L199-L202
ac6a0564d84e1d6e9a4077195e384d379aa20492
GlobalSfMpy
github_2023
zhangganlin
ruby
read_dataset
def read_dataset filename Dir.chdir("spec") do f = File.new(filename, 'r') n = NMatrix.new([65536, 3], dtype: :float32) i = 0 while line = f.gets line.chomp! fields = line.split n[i,:*] = fields.map { |field| field.to_f } i += 1 end n end end
# Helper function for reading a test dataset so we can test nearest neighbors # and radius search and such.
https://github.com/zhangganlin/GlobalSfMpy/blob/ac6a0564d84e1d6e9a4077195e384d379aa20492/thirdparty/TheiaSfM/libraries/flann/src/ruby/spec/spec_helper.rb#L35-L50
ac6a0564d84e1d6e9a4077195e384d379aa20492
by
github_2023
jeremyevans
ruby
By.Server.initialize
def initialize(socket_path: default_socket_path, argv: default_argv, debug: default_debug, daemonize: default_daemonize, daemon_args: default_daemon_args, worker_class: default_worker_class) @socket_path = socket_path @argv = argv @debug = debug if @daemonize = !!daemonize @daemon_args = Array(daemon_args) end @worker_class = worker_class end
# Creates a new server. Arguments: # socket_path: The path to the UNIX socket to create and listen on. # argv: The arguments to the server, which are libraries to be required by default. # debug: If set, operations on an existing server socket will be logged. # If the value is <tt>'log'</tt>, <tt>$LOADED_FEATURES</tt> will also be logged to the stdout # after libraries have been required. # daemonize: Whether to daemonize, +true+ by default. # daemon_args: Arguments to use when daemonizing, <tt>[false, false]</tt> by default. # worker_class: The class to use for worker process handling, Worker by default.
https://github.com/jeremyevans/by/blob/20a61981f559498b6a47ecfdb8e694880d42c9ec/lib/by/server.rb#L30-L40
20a61981f559498b6a47ecfdb8e694880d42c9ec
by
github_2023
jeremyevans
ruby
By.Server.print_loaded_features
def print_loaded_features puts $LOADED_FEATURES end
# Print <tt>$LOADED_FEATURES</tt> to stdout.
https://github.com/jeremyevans/by/blob/20a61981f559498b6a47ecfdb8e694880d42c9ec/lib/by/server.rb#L207-L209
20a61981f559498b6a47ecfdb8e694880d42c9ec
by
github_2023
jeremyevans
ruby
By.Worker.reopen_stdio
def reopen_stdio $stdin.reopen(@socket.recv_io(IO)) $stdout.reopen(@socket.recv_io(IO)) $stderr.reopen(@socket.recv_io(IO)) end
# Replace stdin, stdout, stderr with the IO values provided by the client.
https://github.com/jeremyevans/by/blob/20a61981f559498b6a47ecfdb8e694880d42c9ec/lib/by/worker.rb#L36-L40
20a61981f559498b6a47ecfdb8e694880d42c9ec
beyla
github_2023
grafana
ruby
UsersController.show
def show render json: @user end
# GET /users/1
https://github.com/grafana/beyla/blob/2f2517bd9e5824bcd315292e62102f361a216434/test/integration/components/rubytestserver/testapi/app/controllers/users_controller.rb#L12-L14
2f2517bd9e5824bcd315292e62102f361a216434
beyla
github_2023
grafana
ruby
UsersController.update
def update if @user.update(user_params) render json: @user else render json: @user.errors, status: :unprocessable_entity end end
# PATCH/PUT /users/1
https://github.com/grafana/beyla/blob/2f2517bd9e5824bcd315292e62102f361a216434/test/integration/components/rubytestserver/testapi/app/controllers/users_controller.rb#L28-L34
2f2517bd9e5824bcd315292e62102f361a216434
litestack
github_2023
oldmoe
ruby
random_str
def random_str(size) @db.get_first_value("select hex(randomblob(?))", size) end
# sqlite database for fast random string generation
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/bench/bench.rb#L28-L30
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
ActiveSupport.Cache.Litecache.read_entry
def read_entry(key, **options) deserialize_entry(@cache.get(key)) end
# Read an entry from the cache.
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/active_support/cache/litecache.rb#L80-L82
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
ActiveSupport.Cache.Litecache.delete_entry
def delete_entry(key, **options) @cache.delete(key) end
# Delete an entry from the cache.
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/active_support/cache/litecache.rb#L120-L122
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litecable.subscribe
def subscribe(channel, subscriber, success_callback = nil) @subscribers.acquire do |subs| subs[channel] = {} unless subs[channel] subs[channel][subscriber] = true end success_callback&.call capture(:subscribe, channel) end
# subscribe to a channel, optionally providing a success callback proc
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/litecable.rb#L40-L47
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litecache.increment
def increment(key, amount = 1, expires_in = nil) expires_in ||= @expires_in @conn.acquire { |cache| cache.stmts[:incrementer].execute!(key.to_s, amount, expires_in)[0][0] } end
# increment an integer value by amount, optionally add an expiry value (in seconds)
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/litecache.rb#L165-L168
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litesupport.Liteconnection.with_connection
def with_connection @conn.acquire do |conn| @checked_out_conn = conn yield conn ensure @checked_out_conn = nil end end
# this will force the other run_* methods to use the # checked out connection if one exists
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/liteconnection.rb#L132-L139
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litedb.transaction
def transaction(mode = :immediate) super(mode) end
# enforce immediate mode to avoid deadlocks for a small performance penalty
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/litedb.rb#L43-L45
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf