hexsha
stringlengths
40
40
size
int64
2
1.01M
content
stringlengths
2
1.01M
avg_line_length
float64
1.5
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
1
1d6e5ec4faf9048c178e19ba6ab6cb33b824db6a
27,904
require 'log4r' require "vagrant/util/platform" require File.expand_path("../base", __FILE__) module VagrantPlugins module ProviderVirtualBox module Driver # Driver for VirtualBox 5.0.x class Version_5_0 < Base def initialize(uuid) super() @logger = Log4r::Logger.new("vagrant::provider::virtualbox_5_0") @uuid = uuid end def clear_forwarded_ports retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do args = [] read_forwarded_ports(@uuid).each do |nic, name, _, _| args.concat(["--natpf#{nic}", "delete", name]) end execute("modifyvm", @uuid, *args) if !args.empty? end end def clear_shared_folders retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do info = execute("showvminfo", @uuid, "--machinereadable", retryable: true) info.split("\n").each do |line| if line =~ /^SharedFolderNameMachineMapping\d+="(.+?)"$/ execute("sharedfolder", "remove", @uuid, "--name", $1.to_s) end end end end def clonevm(master_id, snapshot_name) machine_name = "temp_clone_#{(Time.now.to_f * 1000.0).to_i}_#{rand(100000)}" args = ["--register", "--name", machine_name] if snapshot_name args += ["--snapshot", snapshot_name, "--options", "link"] end execute("clonevm", master_id, *args, retryable: true) return get_machine_id(machine_name) end def create_dhcp_server(network, options) retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do begin execute("dhcpserver", "add", "--ifname", network, "--ip", options[:dhcp_ip], "--netmask", options[:netmask], "--lowerip", options[:dhcp_lower], "--upperip", options[:dhcp_upper], "--enable") rescue Vagrant::Errors::VBoxManageError => e return if e.extra_data[:stderr] == 'VBoxManage: error: DHCP server already exists' raise end end end def create_host_only_network(options) # Create the interface execute("hostonlyif", "create", retryable: true) =~ /^Interface '(.+?)' was successfully created$/ name = $1.to_s # Get the IP so we can determine v4 vs v6 ip = IPAddr.new(options[:adapter_ip]) # Configure if ip.ipv4? execute("hostonlyif", "ipconfig", name, "--ip", options[:adapter_ip], "--netmask", options[:netmask], retryable: true) elsif ip.ipv6? execute("hostonlyif", "ipconfig", name, "--ipv6", options[:adapter_ip], "--netmasklengthv6", options[:netmask].to_s, retryable: true) else raise "BUG: Unknown IP type: #{ip.inspect}" end # Return the details return { name: name, ip: options[:adapter_ip], netmask: options[:netmask], dhcp: nil } end def create_snapshot(machine_id, snapshot_name) execute("snapshot", machine_id, "take", snapshot_name, retryable: true) end def delete_snapshot(machine_id, snapshot_name) # Start with 0% last = 0 total = "" yield 0 if block_given? # Snapshot and report the % progress execute("snapshot", machine_id, "delete", snapshot_name, retryable: true) do |type, data| if type == :stderr # Append the data so we can see the full view total << data.gsub("\r", "") # Break up the lines. We can't get the progress until we see an "OK" lines = total.split("\n") # The progress of the import will be in the last line. Do a greedy # regular expression to find what we're looking for. match = /.+(\d{2})%/.match(lines.last) if match current = match[1].to_i if current > last last = current yield current if block_given? end end end end end def list_snapshots(machine_id) output = execute( "snapshot", machine_id, "list", "--machinereadable", retryable: true) result = [] output.split("\n").each do |line| if line =~ /^SnapshotName.*?="(.+?)"$/i result << $1.to_s end end result.sort rescue Vagrant::Errors::VBoxManageError => e d = e.extra_data return [] if d[:stderr].include?("does not have") || d[:stdout].include?("does not have") raise end def restore_snapshot(machine_id, snapshot_name) # Start with 0% last = 0 total = "" yield 0 if block_given? execute("snapshot", machine_id, "restore", snapshot_name, retryable: true) do |type, data| if type == :stderr # Append the data so we can see the full view total << data.gsub("\r", "") # Break up the lines. We can't get the progress until we see an "OK" lines = total.split("\n") # The progress of the import will be in the last line. Do a greedy # regular expression to find what we're looking for. match = /.+(\d{2})%/.match(lines.last) if match current = match[1].to_i if current > last last = current yield current if block_given? end end end end end def delete execute("unregistervm", @uuid, "--delete", retryable: true) end def delete_unused_host_only_networks networks = [] execute("list", "hostonlyifs", retryable: true).split("\n").each do |line| networks << $1.to_s if line =~ /^Name:\s+(.+?)$/ end execute("list", "vms", retryable: true).split("\n").each do |line| if line =~ /^".+?"\s+\{(.+?)\}$/ begin info = execute("showvminfo", $1.to_s, "--machinereadable", retryable: true) info.split("\n").each do |inner_line| if inner_line =~ /^hostonlyadapter\d+="(.+?)"$/ networks.delete($1.to_s) end end rescue Vagrant::Errors::VBoxManageError => e raise if !e.extra_data[:stderr].include?("VBOX_E_OBJECT_NOT_FOUND") # VirtualBox could not find the vm. It may have been deleted # by another process after we called 'vboxmanage list vms'? Ignore this error. end end end networks.each do |name| # First try to remove any DHCP servers attached. We use `raw` because # it is okay if this fails. It usually means that a DHCP server was # never attached. raw("dhcpserver", "remove", "--ifname", name) # Delete the actual host only network interface. execute("hostonlyif", "remove", name, retryable: true) end end def discard_saved_state execute("discardstate", @uuid, retryable: true) end def enable_adapters(adapters) args = [] adapters.each do |adapter| args.concat(["--nic#{adapter[:adapter]}", adapter[:type].to_s]) if adapter[:bridge] args.concat(["--bridgeadapter#{adapter[:adapter]}", adapter[:bridge], "--cableconnected#{adapter[:adapter]}", "on"]) end if adapter[:hostonly] args.concat(["--hostonlyadapter#{adapter[:adapter]}", adapter[:hostonly], "--cableconnected#{adapter[:adapter]}", "on"]) end if adapter[:intnet] args.concat(["--intnet#{adapter[:adapter]}", adapter[:intnet], "--cableconnected#{adapter[:adapter]}", "on"]) end if adapter[:mac_address] args.concat(["--macaddress#{adapter[:adapter]}", adapter[:mac_address]]) end if adapter[:nic_type] args.concat(["--nictype#{adapter[:adapter]}", adapter[:nic_type].to_s]) end end execute("modifyvm", @uuid, *args, retryable: true) end def execute_command(command) execute(*command) end def export(path) retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do begin execute("export", @uuid, "--output", path.to_s) rescue Vagrant::Errors::VBoxManageError => e raise if !e.extra_data[:stderr].include?("VERR_E_FILE_ERROR") # If the file already exists we'll throw a custom error raise Vagrant::Errors::VirtualBoxFileExists, stderr: e.extra_data[:stderr] end end end def forward_ports(ports) args = [] ports.each do |options| pf_builder = [options[:name], options[:protocol] || "tcp", options[:hostip] || "", options[:hostport], options[:guestip] || "", options[:guestport]] args.concat(["--natpf#{options[:adapter] || 1}", pf_builder.join(",")]) end execute("modifyvm", @uuid, *args, retryable: true) if !args.empty? end def get_machine_id(machine_name) output = execute("list", "vms", retryable: true) match = /^"#{Regexp.escape(machine_name)}" \{(.+?)\}$/.match(output) return match[1].to_s if match nil end def halt execute("controlvm", @uuid, "poweroff", retryable: true) end def import(ovf) ovf = Vagrant::Util::Platform.windows_path(ovf) output = "" total = "" last = 0 # Dry-run the import to get the suggested name and path @logger.debug("Doing dry-run import to determine parallel-safe name...") output = execute("import", "-n", ovf) result = /Suggested VM name "(.+?)"/.match(output) if !result raise Vagrant::Errors::VirtualBoxNoName, output: output end suggested_name = result[1].to_s # Append millisecond plus a random to the path in case we're # importing the same box elsewhere. specified_name = "#{suggested_name}_#{(Time.now.to_f * 1000.0).to_i}_#{rand(100000)}" @logger.debug("-- Parallel safe name: #{specified_name}") # Build the specified name param list name_params = [ "--vsys", "0", "--vmname", specified_name, ] # Extract the disks list and build the disk target params disk_params = [] disks = output.scan(/(\d+): Hard disk image: source image=.+, target path=(.+),/) disks.each do |unit_num, path| disk_params << "--vsys" disk_params << "0" disk_params << "--unit" disk_params << unit_num disk_params << "--disk" if Vagrant::Util::Platform.windows? # we use the block form of sub here to ensure that if the specified_name happens to end with a number (which is fairly likely) then # we won't end up having the character sequence of a \ followed by a number be interpreted as a back reference. For example, if # specified_name were "abc123", then "\\abc123\\".reverse would be "\\321cba\\", and the \3 would be treated as a back reference by the sub disk_params << path.reverse.sub("\\#{suggested_name}\\".reverse) { "\\#{specified_name}\\".reverse }.reverse # Replace only last occurrence else disk_params << path.reverse.sub("/#{suggested_name}/".reverse, "/#{specified_name}/".reverse).reverse # Replace only last occurrence end end execute("import", ovf , *name_params, *disk_params, retryable: true) do |type, data| if type == :stdout # Keep track of the stdout so that we can get the VM name output << data elsif type == :stderr # Append the data so we can see the full view total << data.gsub("\r", "") # Break up the lines. We can't get the progress until we see an "OK" lines = total.split("\n") if lines.include?("OK.") # The progress of the import will be in the last line. Do a greedy # regular expression to find what we're looking for. match = /.+(\d{2})%/.match(lines.last) if match current = match[1].to_i if current > last last = current yield current if block_given? end end end end end return get_machine_id specified_name end def max_network_adapters 8 end def read_forwarded_ports(uuid=nil, active_only=false) uuid ||= @uuid @logger.debug("read_forward_ports: uuid=#{uuid} active_only=#{active_only}") results = [] current_nic = nil info = execute("showvminfo", uuid, "--machinereadable", retryable: true) info.split("\n").each do |line| # This is how we find the nic that a FP is attached to, # since this comes first. current_nic = $1.to_i if line =~ /^nic(\d+)=".+?"$/ # If we care about active VMs only, then we check the state # to verify the VM is running. if active_only && line =~ /^VMState="(.+?)"$/ && $1.to_s != "running" return [] end # Parse out the forwarded port information # Forwarding(1)="172.22.8.201tcp32977,tcp,172.22.8.201,32977,,3777" # Forwarding(2)="tcp32978,tcp,,32978,,3777" if line =~ /^Forwarding.+?="(.+?),.+?,(.*?),(.+?),.*?,(.+?)"$/ result = [current_nic, $1.to_s, $3.to_i, $4.to_i, $2] @logger.debug(" - #{result.inspect}") results << result end end results end def read_bridged_interfaces execute("list", "bridgedifs").split("\n\n").collect do |block| info = {} block.split("\n").each do |line| if line =~ /^Name:\s+(.+?)$/ info[:name] = $1.to_s elsif line =~ /^IPAddress:\s+(.+?)$/ info[:ip] = $1.to_s elsif line =~ /^NetworkMask:\s+(.+?)$/ info[:netmask] = $1.to_s elsif line =~ /^Status:\s+(.+?)$/ info[:status] = $1.to_s end end # Return the info to build up the results info end end def read_dhcp_servers execute("list", "dhcpservers", retryable: true).split("\n\n").collect do |block| info = {} block.split("\n").each do |line| if network = line[/^NetworkName:\s+HostInterfaceNetworking-(.+?)$/, 1] info[:network] = network info[:network_name] = "HostInterfaceNetworking-#{network}" elsif ip = line[/^IP:\s+(.+?)$/, 1] info[:ip] = ip elsif netmask = line[/^NetworkMask:\s+(.+?)$/, 1] info[:netmask] = netmask elsif lower = line[/^lowerIPAddress:\s+(.+?)$/, 1] info[:lower] = lower elsif upper = line[/^upperIPAddress:\s+(.+?)$/, 1] info[:upper] = upper end end info end end def read_guest_additions_version output = execute("guestproperty", "get", @uuid, "/VirtualBox/GuestAdd/Version", retryable: true) if output =~ /^Value: (.+?)$/ # Split the version by _ since some distro versions modify it # to look like this: 4.1.2_ubuntu, and the distro part isn't # too important. value = $1.to_s return value.split("_").first end # If we can't get the guest additions version by guest property, try # to get it from the VM info itself. info = execute("showvminfo", @uuid, "--machinereadable", retryable: true) info.split("\n").each do |line| return $1.to_s if line =~ /^GuestAdditionsVersion="(.+?)"$/ end return nil end def read_guest_ip(adapter_number) ip = read_guest_property("/VirtualBox/GuestInfo/Net/#{adapter_number}/V4/IP") if !valid_ip_address?(ip) raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: "/VirtualBox/GuestInfo/Net/#{adapter_number}/V4/IP" end return ip end def read_guest_property(property) output = execute("guestproperty", "get", @uuid, property) if output =~ /^Value: (.+?)$/ $1.to_s else raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: property end end def read_host_only_interfaces execute("list", "hostonlyifs", retryable: true).split("\n\n").collect do |block| info = {} block.split("\n").each do |line| if line =~ /^Name:\s+(.+?)$/ info[:name] = $1.to_s elsif line =~ /^IPAddress:\s+(.+?)$/ info[:ip] = $1.to_s elsif line =~ /^NetworkMask:\s+(.+?)$/ info[:netmask] = $1.to_s elsif line =~ /^IPV6Address:\s+(.+?)$/ info[:ipv6] = $1.to_s.strip elsif line =~ /^IPV6NetworkMaskPrefixLength:\s+(.+?)$/ info[:ipv6_prefix] = $1.to_s.strip elsif line =~ /^Status:\s+(.+?)$/ info[:status] = $1.to_s end end info end end def read_mac_address info = execute("showvminfo", @uuid, "--machinereadable", retryable: true) info.split("\n").each do |line| return $1.to_s if line =~ /^macaddress1="(.+?)"$/ end nil end def read_mac_addresses macs = {} info = execute("showvminfo", @uuid, "--machinereadable", retryable: true) info.split("\n").each do |line| if matcher = /^macaddress(\d+)="(.+?)"$/.match(line) adapter = matcher[1].to_i mac = matcher[2].to_s macs[adapter] = mac end end macs end def read_machine_folder execute("list", "systemproperties", retryable: true).split("\n").each do |line| if line =~ /^Default machine folder:\s+(.+?)$/i return $1.to_s end end nil end def read_network_interfaces nics = {} info = execute("showvminfo", @uuid, "--machinereadable", retryable: true) info.split("\n").each do |line| if line =~ /^nic(\d+)="(.+?)"$/ adapter = $1.to_i type = $2.to_sym nics[adapter] ||= {} nics[adapter][:type] = type elsif line =~ /^hostonlyadapter(\d+)="(.+?)"$/ adapter = $1.to_i network = $2.to_s nics[adapter] ||= {} nics[adapter][:hostonly] = network elsif line =~ /^bridgeadapter(\d+)="(.+?)"$/ adapter = $1.to_i network = $2.to_s nics[adapter] ||= {} nics[adapter][:bridge] = network end end nics end def read_state output = execute("showvminfo", @uuid, "--machinereadable", retryable: true) if output =~ /^name="<inaccessible>"$/ return :inaccessible elsif output =~ /^VMState="(.+?)"$/ return $1.to_sym end nil end def read_used_ports used_ports = Hash.new{|hash, key| hash[key] = Set.new} execute("list", "vms", retryable: true).split("\n").each do |line| if line =~ /^".+?" \{(.+?)\}$/ uuid = $1.to_s # Ignore our own used ports next if uuid == @uuid begin read_forwarded_ports(uuid, true).each do |_, _, hostport, _, hostip| hostip = '*' if hostip.nil? || hostip.empty? used_ports[hostport].add?(hostip) end rescue Vagrant::Errors::VBoxManageError => e raise if !e.extra_data[:stderr].include?("VBOX_E_OBJECT_NOT_FOUND") # VirtualBox could not find the vm. It may have been deleted # by another process after we called 'vboxmanage list vms'? Ignore this error. end end end used_ports end def read_vms results = {} execute("list", "vms", retryable: true).split("\n").each do |line| if line =~ /^"(.+?)" \{(.+?)\}$/ results[$1.to_s] = $2.to_s end end results end def reconfig_host_only(interface) execute("hostonlyif", "ipconfig", interface[:name], "--ipv6", interface[:ipv6], retryable: true) end def remove_dhcp_server(network_name) execute("dhcpserver", "remove", "--netname", network_name, retryable: true) end def set_mac_address(mac) mac = "auto" if !mac execute("modifyvm", @uuid, "--macaddress1", mac, retryable: true) end def set_name(name) retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do begin execute("modifyvm", @uuid, "--name", name) rescue Vagrant::Errors::VBoxManageError => e raise if !e.extra_data[:stderr].include?("VERR_ALREADY_EXISTS") # We got VERR_ALREADY_EXISTS. This means that we're renaming to # a VM name that already exists. Raise a custom error. raise Vagrant::Errors::VirtualBoxNameExists, stderr: e.extra_data[:stderr] end end end def share_folders(folders) is_solaris = begin "SunOS" == read_guest_property("/VirtualBox/GuestInfo/OS/Product") rescue false end folders.each do |folder| # NOTE: Guest additions on Solaris guests do not properly handle # UNC style paths so prevent conversion (See GH-7264) if is_solaris hostpath = folder[:hostpath] else hostpath = Vagrant::Util::Platform.windows_path(folder[:hostpath]) end args = ["--name", folder[:name], "--hostpath", hostpath] args << "--transient" if folder.key?(:transient) && folder[:transient] if folder[:SharedFoldersEnableSymlinksCreate] # Enable symlinks on the shared folder execute("setextradata", @uuid, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{folder[:name]}", "1", retryable: true) end # Add the shared folder execute("sharedfolder", "add", @uuid, *args, retryable: true) end end def ssh_port(expected_port) @logger.debug("Searching for SSH port: #{expected_port.inspect}") # Look for the forwarded port only by comparing the guest port read_forwarded_ports.each do |_, _, hostport, guestport| return hostport if guestport == expected_port end nil end def resume @logger.debug("Resuming paused VM...") execute("controlvm", @uuid, "resume") end def start(mode) command = ["startvm", @uuid, "--type", mode.to_s] retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do r = raw(*command) if r.exit_code == 0 || r.stdout =~ /VM ".+?" has been successfully started/ # Some systems return an exit code 1 for some reason. For that # we depend on the output. return true end # If we reached this point then it didn't work out. raise Vagrant::Errors::VBoxManageError, command: command.inspect, stderr: r.stderr end end def suspend execute("controlvm", @uuid, "savestate", retryable: true) end def unshare_folders(names) names.each do |name| retryable(on: Vagrant::Errors::VBoxManageError, tries: 3, sleep: 1) do begin execute( "sharedfolder", "remove", @uuid, "--name", name, "--transient") execute( "setextradata", @uuid, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{name}") rescue Vagrant::Errors::VBoxManageError => e raise if !e.extra_data[:stderr].include?("VBOX_E_FILE_ERROR") end end end end def verify! # This command sometimes fails if kernel drivers aren't properly loaded # so we just run the command and verify that it succeeded. execute("list", "hostonlyifs", retryable: true) end def verify_image(path) r = raw("import", path.to_s, "--dry-run") return r.exit_code == 0 end def vm_exists?(uuid) 5.times do |i| result = raw("showvminfo", uuid) return true if result.exit_code == 0 # If vboxmanage returned VBOX_E_OBJECT_NOT_FOUND, # then the vm truly does not exist. Any other error might be transient return false if result.stderr.include?("VBOX_E_OBJECT_NOT_FOUND") # Sleep a bit though to give VirtualBox time to fix itself sleep 2 end # If we reach this point, it means that we consistently got the # failure, do a standard vboxmanage now. This will raise an # exception if it fails again. execute("showvminfo", uuid) return true end protected def valid_ip_address?(ip) # Filter out invalid IP addresses # GH-4658 VirtualBox can report an IP address of 0.0.0.0 for FreeBSD guests. if ip == "0.0.0.0" return false else return true end end end end end end
35.321519
153
0.508744
f7a113d58d52139fda113f4945d0b18d55f4e753
1,244
require 'test_helper' class UsersEditTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) end test "unsuccessful edit" do log_in_as(@user) get edit_user_path(@user) assert_template 'users/edit' patch user_path(@user), params: { user: { name: "", email: "foo@invalid", password: "foo", password_confirmation: "bar" } } assert_template 'users/edit' assert_select "div.alert", "The form contains 4 errors." end test "successful edit with friendly fowarding" do get edit_user_path(@user) log_in_as(@user) assert_redirected_to edit_user_url(@user) name = "Foo Bar" email = "[email protected]" patch user_path(@user), params: { user: { name: name, email: email, password: "", password_confirmation: "" } } assert_not flash.empty? assert_redirected_to @user @user.reload assert_equal name, @user.name assert_equal email, @user.email end end
31.1
78
0.518489
26b880b4d9eff30448d92afcd405acfb445f659b
398
require './config/environment' class ApplicationController < Sinatra::Base configure do set :public_folder, 'public' set :views, 'app/views' enable :sessions set :session_secret, "starfish" end get '/' do erb :welcome end helpers do def logged_in? !!session[:user_id] end def current_user User.find(session[:user_id]) end end end
13.724138
43
0.638191
2145a54561ca4fb3ac8e93169c071668ca092907
3,292
module CamaleonCms::FrontendConcern extend ActiveSupport::Concern # visiting sitemap.xml # With hook "on_render_sitemap" you can skip post_types, categories, tags or posts # you can change render file and layout # you can add custom sitemap elements in the attr "custom", like: https://github.com/owen2345/camaleon-cms/issues/106#issuecomment-146232211 # you can customize your content for html or xml format def sitemap r = {layout: (params[:format] == "html" ? nil : false), render: "sitemap", custom: {}, format: params[:format], skip_post_ids: [], skip_posttype_ids: [], skip_cat_ids: [], skip_tag_ids: []} hooks_run("on_render_sitemap", r) @r = r render r[:render], (!r[:layout].nil? ? {layout: r[:layout]} : {}) end # accessing for robots.txt def robots r = {layout: false, render: "robots"} hooks_run("on_render_robots", r) render r[:render], layout: r[:layout] end # rss for current site def rss r = {layout: false, render: "rss"} hooks_run("on_render_rss", r) render r[:render], layout: r[:layout], formats: [:rss] end # save comment from a post def save_comment flash[:comment_submit] = {} @post = current_site.posts.find_by_id(params[:post_id]).decorate user = cama_current_user comment_data = {} flash[:comment_submit][:error] = t('.comments_not_enabled', default: 'This post can not be commented') if [email protected]_commented? if user.present? comment_data[:author] = user.fullname comment_data[:author_email] = user.email elsif current_site.get_option('permit_anonimos_comment', false) user = current_site.get_anonymous_user comment_data[:is_anonymous] = true comment_data[:author] = params[:post_comment][:name] comment_data[:author_email] = params[:post_comment][:email] flash[:comment_submit][:error] = t('camaleon_cms.admin.users.message.error_captcha', default: 'Invalid captcha value') if current_site.is_enable_captcha_for_comments? && !cama_captcha_verified? end unless flash[:comment_submit][:error] if user.present? comment_data[:user_id] = user.id comment_data[:author_url] = params[:post_comment][:url] || "" comment_data[:author_IP] = request.remote_ip.to_s comment_data[:approved] = current_site.front_comment_status comment_data[:agent] = request.user_agent.force_encoding("ISO-8859-1").encode("UTF-8") comment_data[:content] = params[:post_comment][:content] @comment = params[:post_comment][:parent_id].present? ? @post.comments.find_by_id(params[:post_comment][:parent_id]).children.new(comment_data) : @post.comments.main.new(comment_data) if @comment.save flash[:comment_submit][:notice] = t('camaleon_cms.admin.comments.message.created') else flash[:comment_submit][:error] = "#{t('camaleon_cms.common.comment_error', default: 'An error was occurred on save comment')}:<br> #{@comment.errors.full_messages.join(', ')}" end else flash[:comment_submit][:error] = t('camaleon_cms.admin.message.unauthorized') end end params[:format] == 'json' ? render(json: flash.discard(:comment_submit).to_hash) : redirect_to(request.referer || @post.the_url(as_path: true)) end end
49.878788
199
0.690158
39695cf2a5ac27cfde6a232b911d9505ca7788f9
76
class PagesController < ApplicationController def dashboard end end
10.857143
45
0.776316
87fe9e8e36c3fa976a817518d57f7f14c6f8cd3b
2,055
# frozen_string_literal: true module Gql module QueryInterface::Base def self.included(base) base.instance_eval <<-RUBY, __FILE__, __LINE__ + 1 attr_reader :input_key attr_accessor :input_value, :update_type RUBY end # def input_value # @input_value # end # def input_key # @input_key # end # def input_value=(val) # @input_value = val # end def query(obj, input_value = nil) case obj when Gquery then subquery(obj.key) # sending it to subquery allows for caching of gqueries when Input, InitializerInput then execute_input(obj, input_value) when Symbol then subquery(obj) when String then rubel_execute(Command.new(obj)) when Command, Proc then rubel_execute(obj) else fail GqlError.new("Cannot execute a query with #{ obj.inspect }") end end # Returns the results of another gquery. # # Calling it through subquery allows for caching and memoizing. This is # implemented inside submodules/mixins. # def subquery(gquery_key) gquery = get_gquery(gquery_key) raise "Missing gquery: #{gquery_key.inspect}" unless gquery rubel_execute(gquery.command) end def execute_input(input, value = nil) @input_key = input.key # used for the logger # self.input_value = value.to_s # self.input_value = "#{self.input_value}#{input.update_type}" unless self.input_value.include?('%') self.input_value = value self.update_type = input.update_type rubel_execute(input.command) ensure self.input_value = nil end def get_gquery(gquery_or_key) if gquery_or_key.is_a?(::Gquery) gquery_or_key else ::Gquery.get(gquery_or_key) end end def rubel_execute(obj) @rubel.execute(obj) rescue StandardError, SyntaxError => ex raise(obj.is_a?(Command) ? CommandError.new(obj, ex) : ex) end end end
26.688312
113
0.634063
e991dc9754f9014f6de8ecc7d646e589fd274d12
1,122
class Gfan < Formula desc "Computes Gröbner fans and tropical varieties" homepage "http://home.imf.au.dk/jensen/software/gfan/gfan.html" url "http://home.imf.au.dk/jensen/software/gfan/gfan0.5.tar.gz" sha256 "aaeabcf03aad9e426f1ace1f633ffa3200349600314063a7717c20a3e24db329" revision 1 bottle :disable, "Test-bot cannot use the versioned gcc formulae" depends_on "cddlib" depends_on "gcc@5" depends_on "gmp" fails_with :clang fails_with :gcc => "6" patch :DATA def install system "make" system "make", "PREFIX=#{prefix}", "install" doc.install Dir["doc/*"] pkgshare.install "examples", "homepage", "testsuite" end test do system "#{bin}/gfan", "--help" end end __END__ diff --git a/app_minkowski.cpp b/app_minkowski.cpp index d198fc3..939256a 100644 --- a/app_minkowski.cpp +++ b/app_minkowski.cpp @@ -160,7 +160,7 @@ public: //log0 fprintf(Stderr,"4"); f.insert(c); //log0 fprintf(Stderr,"5\n"); - static int i; + //static int i; //log0 fprintf(Stderr,"inserted:%i\n",++i); } log1 fprintf(Stderr,"Resolving symmetries.\n");
24.933333
75
0.672906
7a773f47ca55ec05f063441fd1145bd143ba305e
1,878
# frozen_string_literal: true require 'spec_helper' RSpec.describe BitbucketServer::Representation::Repo do let(:sample_data) do <<~DATA { "slug": "rouge", "id": 1, "name": "rouge", "scmId": "git", "state": "AVAILABLE", "statusMessage": "Available", "forkable": true, "project": { "key": "TEST", "id": 1, "name": "test", "description": "Test", "public": false, "type": "NORMAL", "links": { "self": [ { "href": "http://localhost:7990/projects/TEST" } ] } }, "public": false, "links": { "clone": [ { "href": "http://root@localhost:7990/scm/test/rouge.git", "name": "http" }, { "href": "ssh://git@localhost:7999/test/rouge.git", "name": "ssh" } ], "self": [ { "href": "http://localhost:7990/projects/TEST/repos/rouge/browse" } ] } } DATA end subject { described_class.new(Gitlab::Json.parse(sample_data)) } describe '#project_key' do it { expect(subject.project_key).to eq('TEST') } end describe '#project_name' do it { expect(subject.project_name).to eq('test') } end describe '#slug' do it { expect(subject.slug).to eq('rouge') } end describe '#browse_url' do it { expect(subject.browse_url).to eq('http://localhost:7990/projects/TEST/repos/rouge/browse') } end describe '#clone_url' do it { expect(subject.clone_url).to eq('http://root@localhost:7990/scm/test/rouge.git') } end describe '#description' do it { expect(subject.description).to eq('Test') } end describe '#full_name' do it { expect(subject.full_name).to eq('test/rouge') } end end
22.626506
101
0.521299
7932075a8d7d61a211cf0017b2526271d482f113
129
class RemoveTitleFromComments < ActiveRecord::Migration[6.1] def change remove_column :comments, :title, :string end end
21.5
60
0.75969
5dd0ab156688a66cba4801034109c69a771c786f
279
gem 'minitest' require 'minitest/autorun' # using a global variable because this is only a test $base_path = File.expand_path("#{File.dirname(__FILE__)}/../../") unless $base_path ENV['SNEAQL_DISABLE_SQL_INJECTION_CHECK']="TEST" unless ENV['SNEAQL_DISABLE_SQL_INJECTION_CHECK']
39.857143
97
0.777778
ab7961616b9be06ef4cd8fcd6ef967c2f36ceed0
497
# # Cookbook Name:: newrelic # Attributes:: ruby-agent # # Copyright 2012-2014, Escape Studios # default['newrelic']['ruby-agent']['install_dir'] = '' default['newrelic']['ruby-agent']['app_user'] = 'newrelic' default['newrelic']['ruby-agent']['app_group'] = 'newrelic' default['newrelic']['ruby-agent']['audit_mode'] = false default['newrelic']['ruby-agent']['log_file_count'] = 1 default['newrelic']['ruby-agent']['log_limit_in_kbytes'] = 0 default['newrelic']['ruby-agent']['log_daily'] = true
35.5
60
0.692153
28a87f83451610c7bbabf3669b72d78a11606395
4,386
# frozen_string_literal: true require 'addressable/uri' class Projects::CompareController < Projects::ApplicationController include DiffForPath include DiffHelper include RendersCommits include CompareHelper # Authorize before_action :require_non_empty_project before_action :authorize_download_code! # Defining ivars before_action :define_diffs, only: [:show, :diff_for_path] before_action :define_environment, only: [:show] before_action :define_diff_notes_disabled, only: [:show, :diff_for_path] before_action :define_commits, only: [:show, :diff_for_path, :signatures] before_action :merge_request, only: [:index, :show] # Validation before_action :validate_refs! before_action do push_frontend_feature_flag(:compare_repo_dropdown, source_project, default_enabled: :yaml) end feature_category :source_code_management # Diffs may be pretty chunky, the less is better in this endpoint. # Pagination design guides: https://design.gitlab.com/components/pagination/#behavior COMMIT_DIFFS_PER_PAGE = 20 def index end def show apply_diff_view_cookie! render end def diff_for_path return render_404 unless compare render_diff_for_path(compare.diffs(diff_options)) end def create from_to_vars = { from: params[:from].presence, to: params[:to].presence, from_project_id: params[:from_project_id].presence } if from_to_vars[:from].blank? || from_to_vars[:to].blank? flash[:alert] = "You must select a Source and a Target revision" redirect_to project_compare_index_path(source_project, from_to_vars) else redirect_to project_compare_path(source_project, from_to_vars) end end def signatures respond_to do |format| format.json do render json: { signatures: @commits.select(&:has_signature?).map do |commit| { commit_sha: commit.sha, html: view_to_html_string('projects/commit/_signature', signature: commit.signature) } end } end end end private def validate_refs! valid = [head_ref, start_ref].map { |ref| valid_ref?(ref) } return if valid.all? flash[:alert] = "Invalid branch name" redirect_to project_compare_index_path(source_project) end # target == start_ref == from def target_project strong_memoize(:target_project) do next source_project unless params.key?(:from_project_id) next source_project unless Feature.enabled?(:compare_repo_dropdown, source_project, default_enabled: :yaml) next source_project if params[:from_project_id].to_i == source_project.id target_project = target_projects(source_project).find_by_id(params[:from_project_id]) # Just ignore the field if it points at a non-existent or hidden project next source_project unless target_project && can?(current_user, :download_code, target_project) target_project end end # source == head_ref == to def source_project project end def compare return @compare if defined?(@compare) @compare = CompareService.new(source_project, head_ref).execute(target_project, start_ref) end def start_ref @start_ref ||= Addressable::URI.unescape(params[:from]) end def head_ref return @ref if defined?(@ref) @ref = @head_ref = Addressable::URI.unescape(params[:to]) end def define_commits @commits = compare.present? ? set_commits_for_rendering(@compare.commits) : [] end def define_diffs @diffs = compare.present? ? compare.diffs(diff_options) : [] end def define_environment if compare environment_params = source_project.repository.branch_exists?(head_ref) ? { ref: head_ref } : { commit: compare.commit } environment_params[:find_latest] = true @environment = ::Environments::EnvironmentsByDeploymentsFinder.new(source_project, current_user, environment_params).execute.last end end def define_diff_notes_disabled @diff_notes_disabled = compare.present? end # rubocop: disable CodeReuse/ActiveRecord def merge_request @merge_request ||= MergeRequestsFinder.new(current_user, project_id: target_project.id).execute.opened .find_by(source_project: source_project, source_branch: head_ref, target_branch: start_ref) end # rubocop: enable CodeReuse/ActiveRecord end
28.480519
135
0.727086
6aabb92333621a7f84e1675f8b09dea6001ecece
382
class J < Cask version '803' sha256 'a595ab134a72dd8948ba3930678be41d27796f257f67ceb2ee4df58cdf1a82fa' url "http://www.jsoftware.com/download/j#{version}/install/j#{version}_mac64.zip" homepage 'http://www.jsoftware.com' %w<jbrk jcon jhs jqt>.each do |a| app "j64-#{version}/#{a}.app" end %w<jconsole>.each do |b| binary "j64-#{version}/bin/#{b}" end end
23.875
83
0.688482
ff17f62db042ab3f8c62c4f8033dcac1a6b4a360
217
class CreateActions < ActiveRecord::Migration def change create_table :actions do |t| t.string :action_name t.string :status t.integer :user_id t.timestamps null: false end end end
19.727273
45
0.668203
1cbed343f3aa4db2471fc6da13436f665c214707
2,496
module Workbaskets class EditCertificateController < Workbaskets::BaseController skip_around_action :configure_time_machine, only: [:submitted_for_cross_check] expose(:sub_klass) { "EditCertificate" } expose(:settings_type) { :edit_certificate } expose(:initial_step_url) do edit_edit_certificate_url( workbasket.id, step: :main ) end expose(:read_only_section_url) do edit_certificate_url(workbasket.id) end expose(:submitted_url) do submitted_for_cross_check_edit_certificate_url(workbasket.id) end expose(:form) do WorkbasketForms::EditCertificateForm.new(original_certificate) end expose(:original_certificate) do workbasket_settings.original_certificate .decorate end expose(:certificate) do workbasket_settings.updated_certificate end def new self.workbasket = Workbaskets::Workbasket.create( type: settings_type, user: current_user ) workbasket_settings.update( original_certificate_type_code: params[:certificate_type_code], original_certificate_code: params[:certificate_code] ) redirect_to initial_step_url end def update saver.save! if saver.valid? workbasket_settings.track_step_validations_status!(current_step, true) if submit_for_cross_check_mode? saver.persist! workbasket.submit_for_cross_check!(current_admin: current_user) render json: { redirect_url: submitted_url }, status: :ok else render json: saver.success_ops, status: :ok end else workbasket_settings.track_step_validations_status!(current_step, false) render json: { step: current_step, errors_summary: saver.errors_summary, errors: saver.errors, conformance_errors: saver.conformance_errors }, status: :unprocessable_entity end end private def handle_validate_request!(validator) if validator.valid? render json: {}, status: :ok else render json: { step: :main, errors: validator.errors }, status: :unprocessable_entity end end def check_if_action_is_permitted! true end def submit_for_cross_check_mode? params[:mode] == "submit_for_cross_check" end end end
24.712871
82
0.651843
626275df33358287001bcd29b56ca7c9447d1c04
913
class Daylite::Base < ActiveRecord::Base self.abstract_class = true self.pluralize_table_names = false self.primary_key = "_rowid" self.table_name do self.name.sub("Daylite::", "") end # don't allow to save Daylite::Base objects to DB def readonly? # false true end def method_missing(symbol, *args) guess_attribute = symbol.to_s.camelize(:lower).sub("Id", "ID") if result = attributes[guess_attribute] self.class.class_eval do define_method symbol do return attributes[guess_attribute] end end result else super end end # scopes for all objects scope :alive, -> { self.where( deletiondate: nil)} scope :dead, -> { self.where.not( deletiondate: nil)} # test for whether record has been deleted or not def alive? self.deletiondate.nil? end def dead? ! self.deletiondate.nil? end end
21.232558
66
0.653888
d54da68cb0f1ebd4080a6318e26219b24e0e3737
7,686
# frozen_string_literal: false # # shell/process-controller.rb - # $Release Version: 0.7 $ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # # # require "forwardable" require "sync" class Shell class ProcessController @ProcessControllers = {} @ProcessControllersMonitor = Thread::Mutex.new @ProcessControllersCV = Thread::ConditionVariable.new @BlockOutputMonitor = Thread::Mutex.new @BlockOutputCV = Thread::ConditionVariable.new class << self extend Forwardable def_delegator("@ProcessControllersMonitor", "synchronize", "process_controllers_exclusive") def active_process_controllers process_controllers_exclusive do @ProcessControllers.dup end end def activate(pc) process_controllers_exclusive do @ProcessControllers[pc] ||= 0 @ProcessControllers[pc] += 1 end end def inactivate(pc) process_controllers_exclusive do if @ProcessControllers[pc] if (@ProcessControllers[pc] -= 1) == 0 @ProcessControllers.delete(pc) @ProcessControllersCV.signal end end end end def each_active_object process_controllers_exclusive do for ref in @ProcessControllers.keys yield ref end end end def block_output_synchronize(&b) @BlockOutputMonitor.synchronize(&b) end def wait_to_finish_all_process_controllers process_controllers_exclusive do while [email protected]? Shell::notify("Process finishing, but active shell exists", "You can use Shell#transact or Shell#check_point for more safe execution.") if Shell.debug? for pc in @ProcessControllers.keys Shell::notify(" Not finished jobs in "+pc.shell.to_s) for com in pc.jobs com.notify(" Jobs: %id") end end end @ProcessControllersCV.wait(@ProcessControllersMonitor) end end end end # for shell-command complete finish at this process exit. USING_AT_EXIT_WHEN_PROCESS_EXIT = true at_exit do wait_to_finish_all_process_controllers unless $@ end def initialize(shell) @shell = shell @waiting_jobs = [] @active_jobs = [] @jobs_sync = Sync.new @job_monitor = Thread::Mutex.new @job_condition = Thread::ConditionVariable.new end attr_reader :shell def jobs jobs = [] @jobs_sync.synchronize(:SH) do jobs.concat @waiting_jobs jobs.concat @active_jobs end jobs end def active_jobs @active_jobs end def waiting_jobs @waiting_jobs end def jobs_exist? @jobs_sync.synchronize(:SH) do @active_jobs.empty? or @waiting_jobs.empty? end end def active_jobs_exist? @jobs_sync.synchronize(:SH) do @active_jobs.empty? end end def waiting_jobs_exist? @jobs_sync.synchronize(:SH) do @waiting_jobs.empty? end end # schedule a command def add_schedule(command) @jobs_sync.synchronize(:EX) do ProcessController.activate(self) if @active_jobs.empty? start_job command else @waiting_jobs.push(command) end end end # start a job def start_job(command = nil) @jobs_sync.synchronize(:EX) do if command return if command.active? @waiting_jobs.delete command else command = @waiting_jobs.shift return unless command end @active_jobs.push command command.start # start all jobs that input from the job for job in @waiting_jobs.dup start_job(job) if job.input == command end end end def waiting_job?(job) @jobs_sync.synchronize(:SH) do @waiting_jobs.include?(job) end end def active_job?(job) @jobs_sync.synchronize(:SH) do @active_jobs.include?(job) end end # terminate a job def terminate_job(command) @jobs_sync.synchronize(:EX) do @active_jobs.delete command ProcessController.inactivate(self) if @active_jobs.empty? command.notify("start_job in terminate_job(%id)", Shell::debug?) start_job end end end # kill a job def kill_job(sig, command) @jobs_sync.synchronize(:EX) do if @waiting_jobs.delete command ProcessController.inactivate(self) return elsif @active_jobs.include?(command) begin r = command.kill(sig) ProcessController.inactivate(self) rescue print "Shell: Warn: $!\n" if @shell.verbose? return nil end @active_jobs.delete command r end end end # wait for all jobs to terminate def wait_all_jobs_execution @job_monitor.synchronize do begin while !jobs.empty? @job_condition.wait(@job_monitor) for job in jobs job.notify("waiting job(%id)", Shell::debug?) end end ensure redo unless jobs.empty? end end end # simple fork def sfork(command) pipe_me_in, pipe_peer_out = IO.pipe pipe_peer_in, pipe_me_out = IO.pipe pid = nil pid_mutex = Thread::Mutex.new pid_cv = Thread::ConditionVariable.new Thread.start do ProcessController.block_output_synchronize do STDOUT.flush ProcessController.each_active_object do |pc| for jobs in pc.active_jobs jobs.flush end end pid = fork { Thread.list.each do |th| th.kill unless Thread.current == th end STDIN.reopen(pipe_peer_in) STDOUT.reopen(pipe_peer_out) ObjectSpace.each_object(IO) do |io| if ![STDIN, STDOUT, STDERR].include?(io) io.close end end yield } end pid_cv.signal pipe_peer_in.close pipe_peer_out.close command.notify "job(%name:##{pid}) start", @shell.debug? begin _pid = nil command.notify("job(%id) start to waiting finish.", @shell.debug?) _pid = Process.waitpid(pid, nil) rescue Errno::ECHILD command.notify "warn: job(%id) was done already waitpid." _pid = true ensure command.notify("Job(%id): Wait to finish when Process finished.", @shell.debug?) # when the process ends, wait until the command terminates if USING_AT_EXIT_WHEN_PROCESS_EXIT or _pid else command.notify("notice: Process finishing...", "wait for Job[%id] to finish.", "You can use Shell#transact or Shell#check_point for more safe execution.") redo end @job_monitor.synchronize do terminate_job(command) @job_condition.signal command.notify "job(%id) finish.", @shell.debug? end end end pid_mutex.synchronize do while !pid pid_cv.wait(pid_mutex) end end return pid, pipe_me_in, pipe_me_out end end end
24.793548
102
0.574941
bb1fc021e6680e0b3d4ac09079c1f16cac345a16
1,192
# frozen_string_literal: true require 'spec_helper' RSpec.describe Clusters::Agent do subject { create(:cluster_agent) } it { is_expected.to belong_to(:project).class_name('::Project') } it { is_expected.to have_many(:agent_tokens).class_name('Clusters::AgentToken') } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_length_of(:name).is_at_most(63) } it { is_expected.to validate_uniqueness_of(:name).scoped_to(:project_id) } describe 'validation' do describe 'name validation' do it 'rejects names that do not conform to RFC 1123', :aggregate_failures do %w[Agent agentA agentAagain gent- -agent agent.a agent/a agent>a].each do |name| agent = build(:cluster_agent, name: name) expect(agent).not_to be_valid expect(agent.errors[:name]).to eq(["can contain only lowercase letters, digits, and '-', but cannot start or end with '-'"]) end end it 'accepts valid names', :aggregate_failures do %w[agent agent123 agent-123].each do |name| agent = build(:cluster_agent, name: name) expect(agent).to be_valid end end end end end
33.111111
134
0.677013
3838e40d72f8bbc196868b6ddb4b67b8419d0ecf
1,501
class Envchain < Formula desc "Secure your credentials in environment variables" homepage "https://github.com/sorah/envchain" url "https://github.com/sorah/envchain/archive/v1.0.1.tar.gz" sha256 "09af1fe1cfba3719418f90d59c29c081e1f22b38249f0110305b657bd306e9ae" license "MIT" head "https://github.com/sorah/envchain.git" bottle do cellar :any_skip_relocation sha256 "0e3091b7e3202f68b9bca03aef6df8002048be8e7e6e77be736787e0c7393d7f" => :big_sur sha256 "0a280127849e99bf3313f5d43b7bf1bf38cbffde964ca1c4e3968728b8a52cc8" => :arm64_big_sur sha256 "a8658954176e96b463565ea6b5c891b3635622c550ca32efb8ee2e3baec30062" => :catalina sha256 "3859bb68db413ee3f421351798082c456fbbb82896ef4ca2cdf439cc9d12fdbe" => :mojave sha256 "0d615620e4b69e41aef92971fc1aa9a586be4f75be7813ef73ace103dd182684" => :high_sierra sha256 "42419c23d7dd363b9232918f69fa4ea01270b6eb4dc9c4b1c4d5170ff920fda3" => :sierra sha256 "4e34971c35ec6a716995a5e8d491970809bb5ce6c5651676f70d757b4044c834" => :el_capitan sha256 "1de7c8c17e489b1f832078d3e5c403133accd187f2e666b44bb4da5d1d74f9f7" => :yosemite sha256 "97f5160a1a9ec028afbaf25416de61f976ef7d74031a55c0f265d158627d4afd" => :mavericks end on_linux do depends_on "pkg-config" => :build depends_on "libsecret" depends_on "readline" end def install system "make", "DESTDIR=#{prefix}", "install" end test do assert_match /envchain version #{version}/, shell_output("#{bin}/envchain 2>&1", 2) end end
41.694444
95
0.796136
1ce644608206560ae6090d4f3b65324d2b350fa3
928
# this plugin prints major events like builds starting / passing / failing to console # # it is useful in debugging # # (this plugin is built in and needs no customization) # class MinimalConsoleLogger < BuilderPlugin def build_started(build) puts "Build #{build.label} started" end def build_finished(build) puts "Build #{build.label} " + (build.successful? ? 'finished SUCCESSFULLY' : 'FAILED') end def new_revisions_detected(new_revisions) if new_revisions.last.nil? puts "Changes detected" else puts "New revision #{new_revisions.last.number} detected" end end def build_loop_failed(error) puts "Build loop failed" puts "#{error.class}: #{error.message}" puts error.backtrace.map { |line| " #{line}" }.join("\n") rescue nil end def configuration_modified puts "Configuration modification detected" end end Project.plugin :minimal_console_logger
26.514286
91
0.709052
62a374406647ccc02e204f12cba40a3d014eb339
1,701
# frozen_string_literal: true # Copyright The OpenTelemetry Authors # # SPDX-License-Identifier: Apache-2.0 module OpenTelemetry module SDK module Trace # {Tracer} is the SDK implementation of {OpenTelemetry::Trace::Tracer}. class Tracer < OpenTelemetry::Trace::Tracer # @api private # # Returns a new {Tracer} instance. # # @param [String] name Instrumentation package name # @param [String] version Instrumentation package version # @param [TracerProvider] tracer_provider TracerProvider that initialized the tracer # # @return [Tracer] def initialize(name, version, tracer_provider) @instrumentation_library = InstrumentationLibrary.new(name, version) @tracer_provider = tracer_provider end def start_root_span(name, attributes: nil, links: nil, start_timestamp: nil, kind: nil) start_span(name, with_parent: Context.empty, attributes: attributes, links: links, start_timestamp: start_timestamp, kind: kind) end def start_span(name, with_parent: nil, attributes: nil, links: nil, start_timestamp: nil, kind: nil) name ||= 'empty' with_parent ||= Context.current parent_span_context = OpenTelemetry::Trace.current_span(with_parent).context if parent_span_context.valid? parent_span_id = parent_span_context.span_id trace_id = parent_span_context.trace_id end @tracer_provider.internal_create_span(name, kind, trace_id, parent_span_id, attributes, links, start_timestamp, with_parent, @instrumentation_library) end end end end end
37.8
160
0.678424
611916dcde0104fcdd3ccbb2e8aab527649c3e37
5,058
require 'crichton/lint/base_validator' module Crichton module Lint # class to lint validate the protocols section of a resource descriptor document class ProtocolValidator < BaseValidator # @private list of valid protocol attributes PROTOCOL_PROPERTIES = %w(uri entry_point method headers slt) section :protocols # standard lint validate method def validators [ :check_for_property_issues, :check_transition_equivalence ] end private # high level validation method for errant properties def check_for_property_issues #43 we know the protocol: section exists, check to see if it has a protocol specified add_error('protocols.no_protocol') unless resource_descriptor.protocols resource_descriptor.protocols.each do |protocol_name, protocol| options = {protocol: protocol_name} #44 underlying protocol defined but has no content add_error('protocols.protocol_empty', options) if protocol.empty? check_for_missing_and_empty_properties(protocol, protocol_name) #45, single entry point per protocol verify_single_entry_point(protocol, protocol_name) end end # dispatches a property check based upon the uri def check_for_missing_and_empty_properties(protocol, protocol_name) options = {protocol: protocol_name} # only http is supported now, but future may support multiple protocols protocol.each do |transition_name, transition| # if a transition contains uri_source, then it implies an external resource... if transition.uri_source external_resource_prop_check(transition.descriptor_document, options.merge(action: transition_name)) else protocol_transition_prop_check(transition, options.merge(action: transition_name)) end end end # check if an external resource has other properties besides 'uri_source' def external_resource_prop_check(transition_hash, options) add_warning('protocols.extraneous_props', options) if extraneous_properties?(transition_hash) end # If a transition has 'uri_source' defined, all other properties are extraneous, since it refers to an external resource def extraneous_properties?(transition_prop_hash) transition_prop_hash.keys.any? { |key| PROTOCOL_PROPERTIES.include?(key.to_s) } end # Assorted checks on various properties of a protocol transition def protocol_transition_prop_check(transition, options) #47, 48, required properties uri and method add_error('protocols.property_missing', options.merge(property: 'uri')) unless transition.uri add_error('protocols.property_missing', options.merge(property: 'method')) unless transition.interface_method #53, slt warnings, warn if not existing, and check if it has valid child properties if transition.slt check_slt_properties(transition.slt, options) else add_warning('protocols.property_missing', options.merge(property: 'slt')) unless transition.slt end end # # TODO: write a mime_type verification method # # If slt is defined, it should have the 3 properties below specified def check_slt_properties(slt, options) %w(99th_percentile std_dev requests_per_second).each do |slt_prop| unless slt.keys.include?(slt_prop) add_warning('protocols.missing_slt_property', options.merge(property: slt_prop)) end end end # Check to see there's one and only one entry point into the resource for a protocol def verify_single_entry_point(protocol, protocol_name) entry_point_count = protocol.values.inject(0) { |i, transition| transition.entry_point ? i + 1 : i } unless entry_point_count == 1 add_error('protocols.entry_point_error', error: entry_point_count == 0 ? "No" : "Multiple", protocol: protocol_name) end end # 54 check if the list of transitions found in the protocol section match the transitions in the # states and descriptor sections def check_transition_equivalence protocol_transition_list = build_protocol_transition_list #first look for protocol transitions not found in the descriptor transitions build_descriptor_transition_list.each do |transition| unless protocol_transition_list.include?(transition) add_error('protocols.descriptor_transition_not_found', transition: transition) end end # then check if there is a transition missing for any state transition specified in the states: section build_state_transition_list.each do |transition| unless protocol_transition_list.include?(transition) add_error('protocols.state_transition_not_found', transition: transition) end end end end end end
41.121951
126
0.704033
ed2da92c41423b073b4f08894af51cc735b3ad75
3,349
require './config/environment' require 'sinatra/base' require 'rack-flash' class ApplicationController < Sinatra::Base enable :sessions use Rack::Flash configure do set :session_secret, "secret" set :public_folder, 'public' set :views, 'app/views' end get '/' do erb :index end get '/signup' do if Helpers.is_logged_in?(session) redirect to '/tweets' end erb :"/users/create_user" end post '/signup' do params.each do |label, input| if input.empty? flash[:new_user_error] = "Please enter a value for #{label}" redirect to '/signup' end end user = User.create(:username => params["username"], :email => params["email"], :password => params["password"]) session[:user_id] = user.id redirect to '/tweets' end get '/login' do if Helpers.is_logged_in?(session) redirect to '/tweets' end erb :"/users/login" end post '/login' do user = User.find_by(:username => params["username"]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect to '/tweets' else flash[:login_error] = "Incorrect login. Please try again." redirect to '/login' end end get '/tweets' do if !Helpers.is_logged_in?(session) redirect to '/login' end @tweets = Tweet.all @user = Helpers.current_user(session) erb :"/tweets/tweets" end get '/tweets/new' do if !Helpers.is_logged_in?(session) redirect to '/login' end erb :"/tweets/create_tweet" end post '/tweets' do user = Helpers.current_user(session) if params["content"].empty? flash[:empty_tweet] = "Please enter content for your tweet" redirect to '/tweets/new' end tweet = Tweet.create(:content => params["content"], :user_id => user.id) redirect to '/tweets' end get '/tweets/:id' do if !Helpers.is_logged_in?(session) redirect to '/login' end @tweet = Tweet.find(params[:id]) erb :"tweets/show_tweet" end get '/tweets/:id/edit' do if !Helpers.is_logged_in?(session) redirect to '/login' end @tweet = Tweet.find(params[:id]) if Helpers.current_user(session).id != @tweet.user_id flash[:wrong_user_edit] = "Sorry you can only edit your own tweets" redirect to '/tweets' end erb :"tweets/edit_tweet" end patch '/tweets/:id' do tweet = Tweet.find(params[:id]) if params["content"].empty? flash[:empty_tweet] = "Please enter content for your tweet" redirect to "/tweets/#{params[:id]}/edit" end tweet.update(:content => params["content"]) tweet.save redirect to "/tweets/#{tweet.id}" end post '/tweets/:id/delete' do if !Helpers.is_logged_in?(session) redirect to '/login' end @tweet = Tweet.find(params[:id]) if Helpers.current_user(session).id != @tweet.user_id flash[:wrong_user] = "Sorry you can only delete your own tweets" redirect to '/tweets' end @tweet.delete redirect to '/tweets' end get '/users/:slug' do slug = params[:slug] @user = User.find_by_slug(slug) erb :"users/show" end get '/logout' do if Helpers.is_logged_in?(session) session.clear redirect to '/login' else redirect to '/' end end end
22.47651
115
0.623171
9163f2b0c8661226d78a57aa439e27c23c1130cf
131
class AddNameToOrthologGroup < ActiveRecord::Migration[6.1] def change add_column :ortholog_groups, :name, :string end end
21.833333
59
0.763359
ff8a79a9eeb469ebb2b320d0fb22470a8b9a6d70
510
# frozen_string_literal: true module Jasmine class Server def initialize(port = 8888, application = nil, rack_options = nil, env = ENV) @port = port @application = application @rack_options = rack_options || {} @env = env end def start @env['PORT'] = @port.to_s Rack::Server.start(@rack_options.merge(Port: @port, AccessLog: [], app: @application)) end end end
24.285714
81
0.515686
abd93d2435479e0ac647cd207edf5e4988e34ec5
88,595
# -*- coding: binary -*- # # Rex # require 'rex/ui/text/output/buffer/stdout' # # Project # require 'msf/ui/console/command_dispatcher/encoder' require 'msf/ui/console/command_dispatcher/exploit' require 'msf/ui/console/command_dispatcher/nop' require 'msf/ui/console/command_dispatcher/payload' require 'msf/ui/console/command_dispatcher/auxiliary' require 'msf/ui/console/command_dispatcher/post' module Msf module Ui module Console module CommandDispatcher ### # # Command dispatcher for core framework commands, such as module loading, # session interaction, and other general things. # ### class Core include Msf::Ui::Console::CommandDispatcher # Session command options @@sessions_opts = Rex::Parser::Arguments.new( "-c" => [ true, "Run a command on the session given with -i, or all" ], "-h" => [ false, "Help banner" ], "-i" => [ true, "Interact with the supplied session ID" ], "-l" => [ false, "List all active sessions" ], "-v" => [ false, "List verbose fields" ], "-q" => [ false, "Quiet mode" ], "-d" => [ true, "Detach an interactive session" ], "-k" => [ true, "Terminate session" ], "-K" => [ false, "Terminate all sessions" ], "-s" => [ true, "Run a script on the session given with -i, or all" ], "-r" => [ false, "Reset the ring buffer for the session given with -i, or all"], "-u" => [ true, "Upgrade a win32 shell to a meterpreter session" ]) @@jobs_opts = Rex::Parser::Arguments.new( "-h" => [ false, "Help banner." ], "-k" => [ true, "Terminate the specified job name." ], "-K" => [ false, "Terminate all running jobs." ], "-i" => [ true, "Lists detailed information about a running job." ], "-l" => [ false, "List all running jobs." ], "-v" => [ false, "Print more detailed info. Use with -i and -l" ]) @@threads_opts = Rex::Parser::Arguments.new( "-h" => [ false, "Help banner." ], "-k" => [ true, "Terminate the specified thread ID." ], "-K" => [ false, "Terminate all non-critical threads." ], "-i" => [ true, "Lists detailed information about a thread." ], "-l" => [ false, "List all background threads." ], "-v" => [ false, "Print more detailed info. Use with -i and -l" ]) @@connect_opts = Rex::Parser::Arguments.new( "-h" => [ false, "Help banner." ], "-p" => [ true, "List of proxies to use." ], "-C" => [ false, "Try to use CRLF for EOL sequence." ], "-c" => [ true, "Specify which Comm to use." ], "-i" => [ true, "Send the contents of a file." ], "-P" => [ true, "Specify source port." ], "-S" => [ true, "Specify source address." ], "-s" => [ false, "Connect with SSL." ], "-u" => [ false, "Switch to a UDP socket." ], "-w" => [ true, "Specify connect timeout." ], "-z" => [ false, "Just try to connect, then return." ]) @@grep_opts = Rex::Parser::Arguments.new( "-h" => [ false, "Help banner." ], "-i" => [ false, "Ignore case." ], "-m" => [ true, "Stop after arg matches." ], "-v" => [ false, "Invert match." ], "-A" => [ true, "Show arg lines of output After a match." ], "-B" => [ true, "Show arg lines of output Before a match." ], "-s" => [ true, "Skip arg lines of output before attempting match."], "-k" => [ true, "Keep (include) arg lines at start of output." ], "-c" => [ false, "Only print a count of matching lines." ]) @@search_opts = Rex::Parser::Arguments.new( "-h" => [ false, "Help banner." ]) @@go_pro_opts = Rex::Parser::Arguments.new( "-h" => [ false, "Help banner." ]) # The list of data store elements that cannot be set when in defanged # mode. DefangedProhibitedDataStoreElements = [ "MsfModulePaths" ] # Returns the list of commands supported by this command dispatcher def commands { "?" => "Help menu", "back" => "Move back from the current context", "banner" => "Display an awesome metasploit banner", "cd" => "Change the current working directory", "connect" => "Communicate with a host", "color" => "Toggle color", "exit" => "Exit the console", "go_pro" => "Launch Metasploit web GUI", "grep" => "Grep the output of another command", "help" => "Help menu", "info" => "Displays information about one or more module", "irb" => "Drop into irb scripting mode", "jobs" => "Displays and manages jobs", "kill" => "Kill a job", "load" => "Load a framework plugin", "loadpath" => "Searches for and loads modules from a path", "popm" => "Pops the latest module off the stack and makes it active", "pushm" => "Pushes the active or list of modules onto the module stack", "previous" => "Sets the previously loaded module as the current module", "quit" => "Exit the console", "resource" => "Run the commands stored in a file", "makerc" => "Save commands entered since start to a file", "reload_all" => "Reloads all modules from all defined module paths", "route" => "Route traffic through a session", "save" => "Saves the active datastores", "search" => "Searches module names and descriptions", "sessions" => "Dump session listings and display information about sessions", "set" => "Sets a variable to a value", "setg" => "Sets a global variable to a value", "show" => "Displays modules of a given type, or all modules", "sleep" => "Do nothing for the specified number of seconds", "threads" => "View and manipulate background threads", "unload" => "Unload a framework plugin", "unset" => "Unsets one or more variables", "unsetg" => "Unsets one or more global variables", "use" => "Selects a module by name", "version" => "Show the framework and console library version numbers", "spool" => "Write console output into a file as well the screen" } end # # Initializes the datastore cache # def initialize(driver) super @dscache = {} @cache_payloads = nil @previous_module = nil @module_name_stack = [] end # # Returns the name of the command dispatcher. # def name "Core" end # Indicates the base dir where Metasploit Framework is installed. def msfbase_dir base = __FILE__ while File.symlink?(base) base = File.expand_path(File.readlink(base), File.dirname(base)) end File.expand_path( File.join(File.dirname(base), "..","..","..","..","..") ) end def cmd_color_help print_line "Usage: color <'true'|'false'|'auto'>" print_line print_line "Enable or disable color output." print_line end def cmd_color(*args) case args[0] when "auto" driver.output.auto_color when "true" driver.output.enable_color when "false" driver.output.disable_color else cmd_color_help return end driver.update_prompt end def cmd_reload_all_help print_line "Usage: reload_all" print_line print_line "Reload all modules from all configured module paths. This may take awhile." print_line "See also: loadpath" print_line end # # Reload all module paths that we are aware of # def cmd_reload_all(*args) if args.length > 0 cmd_reload_all_help return end print_status("Reloading modules from all module paths...") framework.modules.reload_modules cmd_banner() end def cmd_resource_help print_line "Usage: resource path1 [path2 ...]" print_line print_line "Run the commands stored in the supplied files. Resource files may also contain" print_line "ruby code between <ruby></ruby> tags." print_line print_line "See also: makerc" print_line end def cmd_resource(*args) if args.empty? cmd_resource_help return false end args.each do |res| good_res = nil if (File.file? res and File.readable? res) good_res = res elsif # let's check to see if it's in the scripts/resource dir (like when tab completed) [ ::Msf::Config.script_directory + File::SEPARATOR + "resource", ::Msf::Config.user_script_directory + File::SEPARATOR + "resource" ].each do |dir| res_path = dir + File::SEPARATOR + res if (File.file?(res_path) and File.readable?(res_path)) good_res = res_path break end end end if good_res driver.load_resource(good_res) else print_error("#{res} is not a valid resource file") next end end end # # Tab completion for the resource command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_resource_tabs(str, words) tabs = [] #return tabs if words.length > 1 if ( str and str =~ /^#{Regexp.escape(File::SEPARATOR)}/ ) # then you are probably specifying a full path so let's just use normal file completion return tab_complete_filenames(str,words) elsif (not words[1] or not words[1].match(/^\//)) # then let's start tab completion in the scripts/resource directories begin [ ::Msf::Config.script_directory + File::SEPARATOR + "resource", ::Msf::Config.user_script_directory + File::SEPARATOR + "resource", "." ].each do |dir| next if not ::File.exist? dir tabs += ::Dir.new(dir).find_all { |e| path = dir + File::SEPARATOR + e ::File.file?(path) and File.readable?(path) } end rescue Exception end else tabs += tab_complete_filenames(str,words) end return tabs end def cmd_makerc_help print_line "Usage: makerc <output rc file>" print_line print_line "Save the commands executed since startup to the specified file." print_line end # # Saves commands executed since the ui started to the specified msfrc file # def cmd_makerc(*args) if args.empty? cmd_makerc_help return false end driver.save_recent_history(args[0]) end def cmd_back_help print_line "Usage: back" print_line print_line "Return to the global dispatcher context" print_line end # # Pop the current dispatcher stack context, assuming it isn't pointed at # the core or database backend stack context. # def cmd_back(*args) if (driver.dispatcher_stack.size > 1 and driver.current_dispatcher.name != 'Core' and driver.current_dispatcher.name != 'Database Backend') # Reset the active module if we have one if (active_module) # Do NOT reset the UI anymore # active_module.reset_ui # Save the module's datastore so that we can load it later # if the module is used again @dscache[active_module.fullname] = active_module.datastore.dup self.active_module = nil end # Destack the current dispatcher driver.destack_dispatcher # Restore the prompt prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar driver.update_prompt("#{prompt}", prompt_char, true) end end def cmd_cd_help print_line "Usage: cd <directory>" print_line print_line "Change the current working directory" print_line end # # Change the current working directory # def cmd_cd(*args) if(args.length == 0) print_error("No path specified") return end begin Dir.chdir(args.join(" ").strip) rescue ::Exception print_error("The specified path does not exist") end end def cmd_banner_help print_line "Usage: banner" print_line print_line "Print a stunning ascii art banner along with version information and module counts" print_line end # # Display one of the fabulous banners. # def cmd_banner(*args) banner = "%cya" + Banner.to_s + "%clr\n\n" if is_apt content = [ "Large pentest? List, sort, group, tag and search your hosts and services\nin Metasploit Pro -- type 'go_pro' to launch it now.", "Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with\nMetasploit Pro -- type 'go_pro' to launch it now.", "Save your shells from AV! Upgrade to advanced AV evasion using dynamic\nexe templates with Metasploit Pro -- type 'go_pro' to launch it now.", "Easy phishing: Set up email templates, landing pages and listeners\nin Metasploit Pro’s wizard -- type 'go_pro' to launch it now.", "Using notepad to track pentests? Have Metasploit Pro report on hosts,\nservices, sessions and evidence -- type 'go_pro' to launch it now.", "Tired of typing ‘set RHOSTS’? Click & pwn with Metasploit Pro\n-- type 'go_pro' to launch it now." ] banner << content.sample # Ruby 1.9-ism! banner << "\n\n" end banner << " =[ %yelmetasploit v#{Msf::Framework::Version} [core:#{Msf::Framework::VersionCore} api:#{Msf::Framework::VersionAPI}]%clr\n" banner << "+ -- --=[ " banner << "#{framework.stats.num_exploits} exploits - #{framework.stats.num_auxiliary} auxiliary - #{framework.stats.num_post} post\n" banner << "+ -- --=[ " oldwarn = nil avdwarn = nil banner << "#{framework.stats.num_payloads} payloads - #{framework.stats.num_encoders} encoders - #{framework.stats.num_nops} nops\n" if ( ::Msf::Framework::RepoRevision.to_i > 0 and ::Msf::Framework::RepoUpdatedDate) tstamp = ::Msf::Framework::RepoUpdatedDate.strftime("%Y.%m.%d") banner << " =[ svn r#{::Msf::Framework::RepoRevision} updated #{::Msf::Framework::RepoUpdatedDaysNote} (#{tstamp})\n" if(::Msf::Framework::RepoUpdatedDays > 7) oldwarn = [] oldwarn << "Warning: This copy of the Metasploit Framework was last updated #{::Msf::Framework::RepoUpdatedDaysNote}." oldwarn << " We recommend that you update the framework at least every other day." oldwarn << " For information on updating your copy of Metasploit, please see:" oldwarn << " https://community.rapid7.com/docs/DOC-1306" oldwarn << "" end end if ::Msf::Framework::EICARCorrupted avdwarn = [] avdwarn << "Warning: This copy of the Metasploit Framework has been corrupted by an installed anti-virus program." avdwarn << " We recommend that you disable your anti-virus or exclude your Metasploit installation path," avdwarn << " then restore the removed files from quarantine or reinstall the framework. For more info: " avdwarn << " https://community.rapid7.com/docs/DOC-1273" avdwarn << "" end # Display the banner print_line(banner) if(oldwarn) oldwarn.map{|line| print_line(line) } end if(avdwarn) avdwarn.map{|line| print_error(line) } end end def cmd_connect_help print_line "Usage: connect [options] <host> <port>" print_line print_line "Communicate with a host, similar to interacting via netcat, taking advantage of" print_line "any configured session pivoting." print @@connect_opts.usage end # # Talk to a host # def cmd_connect(*args) if args.length < 2 or args.include?("-h") cmd_connect_help return false end crlf = false commval = nil fileval = nil proxies = nil srcaddr = nil srcport = nil ssl = false udp = false cto = nil justconn = false aidx = 0 @@connect_opts.parse(args) do |opt, idx, val| case opt when "-C" crlf = true aidx = idx + 1 when "-c" commval = val aidx = idx + 2 when "-i" fileval = val aidx = idx + 2 when "-P" srcport = val aidx = idx + 2 when "-p" proxies = val aidx = idx + 2 when "-S" srcaddr = val aidx = idx + 2 when "-s" ssl = true aidx = idx + 1 when "-w" cto = val.to_i aidx = idx + 2 when "-u" udp = true aidx = idx + 1 when "-z" justconn = true aidx = idx + 1 end end commval = "Local" if commval =~ /local/i if fileval begin raise "Not a file" if File.ftype(fileval) != "file" infile = ::File.open(fileval) rescue print_error("Can't read from '#{fileval}': #{$!}") return false end end args = args[aidx .. -1] if args.length < 2 print_error("You must specify a host and port") return false end host = args[0] port = args[1] comm = nil if commval begin if Rex::Socket::Comm.const_defined?(commval) comm = Rex::Socket::Comm.const_get(commval) end rescue NameError end if not comm session = framework.sessions.get(commval) if session.kind_of?(Msf::Session::Comm) comm = session end end if not comm print_error("Invalid comm '#{commval}' selected") return false end end begin klass = udp ? ::Rex::Socket::Udp : ::Rex::Socket::Tcp sock = klass.create({ 'Comm' => comm, 'Proxies' => proxies, 'SSL' => ssl, 'PeerHost' => host, 'PeerPort' => port, 'LocalHost' => srcaddr, 'LocalPort' => srcport, 'Timeout' => cto, 'Context' => { 'Msf' => framework } }) rescue print_error("Unable to connect: #{$!}") return false end print_status("Connected to #{host}:#{port}") if justconn sock.close infile.close if infile return true end cin = infile || driver.input cout = driver.output begin # Console -> Network c2n = framework.threads.spawn("ConnectConsole2Network", false, cin, sock) do |input, output| while true begin res = input.gets break if not res if crlf and (res =~ /^\n$/ or res =~ /[^\r]\n$/) res.gsub!(/\n$/, "\r\n") end output.write res rescue ::EOFError, ::IOError break end end end # Network -> Console n2c = framework.threads.spawn("ConnectNetwork2Console", false, sock, cout, c2n) do |input, output, cthr| while true begin res = input.read(65535) break if not res output.print res rescue ::EOFError, ::IOError break end end Thread.kill(cthr) end c2n.join rescue ::Interrupt c2n.kill n2c.kill end sock.close rescue nil infile.close if infile true end # # Instructs the driver to stop executing. # def cmd_exit(*args) forced = false forced = true if (args[0] and args[0] =~ /-y/i) if(framework.sessions.length > 0 and not forced) print_status("You have active sessions open, to exit anyway type \"exit -y\"") return end driver.stop end alias cmd_quit cmd_exit def cmd_sleep_help print_line "Usage: sleep <seconds>" print_line print_line "Do nothing the specified number of seconds. This is useful in rc scripts." print_line end # # Causes process to pause for the specified number of seconds # def cmd_sleep(*args) return if not (args and args.length == 1) Rex::ThreadSafe.sleep(args[0].to_f) end def cmd_info_help print_line "Usage: info <module name> [mod2 mod3 ...]" print_line print_line "Queries the supplied module or modules for information. If no module is given," print_line "show info for the currently active module." print_line end # # Displays information about one or more module. # def cmd_info(*args) if (args.length == 0) if (active_module) print(Serializer::ReadableText.dump_module(active_module)) return true else cmd_info_help return false end elsif args.include? "-h" cmd_info_help return false end args.each { |name| mod = framework.modules.create(name) if (mod == nil) print_error("Invalid module: #{name}") else print(Serializer::ReadableText.dump_module(mod)) end } end # # Tab completion for the info command (same as use) # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_info_tabs(str, words) cmd_use_tabs(str, words) end def cmd_irb_help print_line "Usage: irb" print_line print_line "Drop into an interactive Ruby environment" print_line end # # Goes into IRB scripting mode # def cmd_irb(*args) defanged? print_status("Starting IRB shell...\n") begin Rex::Ui::Text::IrbShell.new(binding).run rescue print_error("Error during IRB: #{$!}\n\n#{[email protected]("\n")}") end # Reset tab completion if (driver.input.supports_readline) driver.input.reset_tab_completion end end def cmd_jobs_help print_line "Usage: jobs [options]" print_line print_line "Active job manipulation and interaction." print @@jobs_opts.usage() end # # Displays and manages running jobs for the active instance of the # framework. # def cmd_jobs(*args) # Make the default behavior listing all jobs if there were no options # or the only option is the verbose flag if (args.length == 0 or args == ["-v"]) args.unshift("-l") end verbose = false dump_list = false dump_info = false job_id = nil # Parse the command options @@jobs_opts.parse(args) { |opt, idx, val| case opt when "-v" verbose = true when "-l" dump_list = true # Terminate the supplied job name when "-k" if (not framework.jobs.has_key?(val)) print_error("No such job") else print_line("Stopping job: #{val}...") framework.jobs.stop_job(val) end when "-K" print_line("Stopping all jobs...") framework.jobs.each_key do |i| framework.jobs.stop_job(i) end when "-i" # Defer printing anything until the end of option parsing # so we can check for the verbose flag. dump_info = true job_id = val when "-h" cmd_jobs_help return false end } if (dump_list) print("\n" + Serializer::ReadableText.dump_jobs(framework, verbose) + "\n") end if (dump_info) if (job_id and framework.jobs[job_id.to_s]) job = framework.jobs[job_id.to_s] mod = job.ctx[0] output = "\n" output += "Name: #{mod.name}" output += ", started at #{job.start_time}" if job.start_time print_line(output) if (mod.options.has_options?) show_options(mod) end if (verbose) mod_opt = Serializer::ReadableText.dump_advanced_options(mod,' ') print_line("\nModule advanced options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0) end else print_line("Invalid Job ID") end end end # # Tab completion for the jobs command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_jobs_tabs(str, words) if words.length == 1 return @@jobs_opts.fmt.keys end if @@jobs_opts.fmt[words[1]][0] and (words.length == 2) return framework.jobs.keys end [] end def cmd_kill_help print_line "Usage: kill <job1> [job2 ...]" print_line print_line "Equivalent to 'jobs -k job1 -k job2 ...'" print @@jobs_opts.usage() end def cmd_kill(*args) cmd_jobs("-k", *args) end # # Tab completion for the kill command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_kill_tabs(str, words) return [] if words.length > 1 framework.jobs.keys end def cmd_threads_help print_line "Usage: threads [options]" print_line print_line "Background thread management." print_line @@threads_opts.usage() end # # Displays and manages running background threads # def cmd_threads(*args) # Make the default behavior listing all jobs if there were no options # or the only option is the verbose flag if (args.length == 0 or args == ["-v"]) args.unshift("-l") end verbose = false dump_list = false dump_info = false thread_id = nil # Parse the command options @@threads_opts.parse(args) { |opt, idx, val| case opt when "-v" verbose = true when "-l" dump_list = true # Terminate the supplied thread id when "-k" val = val.to_i if not framework.threads[val] print_error("No such thread") else print_line("Terminating thread: #{val}...") framework.threads.kill(val) end when "-K" print_line("Killing all non-critical threads...") framework.threads.each_index do |i| t = framework.threads[i] next if not t next if t[:tm_crit] framework.threads.kill(i) end when "-i" # Defer printing anything until the end of option parsing # so we can check for the verbose flag. dump_info = true thread_id = val.to_i when "-h" cmd_threads_help return false end } if (dump_list) tbl = Table.new( Table::Style::Default, 'Header' => "Background Threads", 'Prefix' => "\n", 'Postfix' => "\n", 'Columns' => [ 'ID', 'Status', 'Critical', 'Name', 'Started' ] ) framework.threads.each_index do |i| t = framework.threads[i] next if not t tbl << [ i.to_s, t.status || "dead", t[:tm_crit] ? "True" : "False", t[:tm_name].to_s, t[:tm_time].to_s ] end print(tbl.to_s) end if (dump_info) thread = framework.threads[thread_id] if (thread) output = "\n" output += " ID: #{thread_id}\n" output += "Name: #{thread[:tm_name]}\n" output += "Info: #{thread.status || "dead"}\n" output += "Crit: #{thread[:tm_crit] ? "True" : "False"}\n" output += "Time: #{thread[:tm_time].to_s}\n" if (verbose) output += "\n" output += "Thread Source\n" output += "=============\n" thread[:tm_call].each do |c| output += " #{c.to_s}\n" end output += "\n" end print(output +"\n") else print_line("Invalid Thread ID") end end end # # Tab completion for the threads command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_threads_tabs(str, words) if words.length == 1 return @@threads_opts.fmt.keys end if @@threads_opts.fmt[words[1]][0] and (words.length == 2) return framework.threads.each_index.map{ |idx| idx.to_s } end [] end def cmd_load_help print_line "Usage: load <path> [var=val var=val ...]" print_line print_line "Loads a plugin from the supplied path. If path is not absolute, fist looks" print_line "in the user's plugin directory (#{Msf::Config.user_plugin_directory}) then" print_line "in the framework root plugin directory (#{Msf::Config.plugin_directory})." print_line "The optional var=val options are custom parameters that can be passed to plugins." print_line end # # Loads a plugin from the supplied path. If no absolute path is supplied, # the framework root plugin directory is used. # def cmd_load(*args) defanged? if (args.length == 0) cmd_load_help return false end # Default to the supplied argument path. path = args.shift opts = { 'LocalInput' => driver.input, 'LocalOutput' => driver.output, 'ConsoleDriver' => driver } # Parse any extra options that should be passed to the plugin args.each { |opt| k, v = opt.split(/\=/) opts[k] = v if (k and v) } # If no absolute path was supplied, check the base and user plugin directories if (path !~ /#{File::SEPARATOR}/) plugin_file_name = path # If the plugin isn't in the user directory (~/.msf3/plugins/), use the base path = Msf::Config.user_plugin_directory + File::SEPARATOR + plugin_file_name if not File.exists?( path + ".rb" ) # If the following "path" doesn't exist it will be caught when we attempt to load path = Msf::Config.plugin_directory + File::SEPARATOR + plugin_file_name end end # Load that plugin! begin if (inst = framework.plugins.load(path, opts)) print_status("Successfully loaded plugin: #{inst.name}") end rescue ::Exception => e elog("Error loading plugin #{path}: #{e}\n\n#{e.backtrace.join("\n")}", src = 'core', level = 0, from = caller) print_error("Failed to load plugin from #{path}: #{e}") end end # # Tab completion for the load command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_load_tabs(str, words) tabs = [] if (not words[1] or not words[1].match(/^\//)) # then let's start tab completion in the scripts/resource directories begin [ Msf::Config.user_plugin_directory, Msf::Config.plugin_directory ].each do |dir| next if not ::File.exist? dir tabs += ::Dir.new(dir).find_all { |e| path = dir + File::SEPARATOR + e ::File.file?(path) and File.readable?(path) } end rescue Exception end else tabs += tab_complete_filenames(str,words) end return tabs.map{|e| e.sub(/.rb/, '')} end def cmd_route_help print_line "Usage: route [add/remove/get/flush/print] subnet netmask [comm/sid]" print_line print_line "Route traffic destined to a given subnet through a supplied session." print_line "The default comm is Local." print_line end # # This method handles the route command which allows a user to specify # which session a given subnet should route through. # def cmd_route(*args) if (args.length == 0) cmd_route_help return false end arg = args.shift case arg when "add", "remove", "del" if (args.length < 3) print_error("Missing arguments to route #{arg}.") return false end # Satisfy check to see that formatting is correct unless Rex::Socket::RangeWalker.new(args[0]).length == 1 print_error "Invalid IP Address" return false end unless Rex::Socket::RangeWalker.new(args[1]).length == 1 print_error "Invalid Subnet mask" return false end gw = nil # Satisfy case problems args[2] = "Local" if (args[2] =~ /local/i) begin # If the supplied gateway is a global Comm, use it. if (Rex::Socket::Comm.const_defined?(args[2])) gw = Rex::Socket::Comm.const_get(args[2]) end rescue NameError end # If we still don't have a gateway, check if it's a session. if ((gw == nil) and (session = framework.sessions.get(args[2])) and (session.kind_of?(Msf::Session::Comm))) gw = session elsif (gw == nil) print_error("Invalid gateway specified.") return false end if arg == "remove" or arg == "del" worked = Rex::Socket::SwitchBoard.remove_route(args[0], args[1], gw) if worked print_status("Route removed") else print_error("Route not found") end else worked = Rex::Socket::SwitchBoard.add_route(args[0], args[1], gw) if worked print_status("Route added") else print_error("Route already exists") end end when "get" if (args.length == 0) print_error("You must supply an IP address.") return false end comm = Rex::Socket::SwitchBoard.best_comm(args[0]) if ((comm) and (comm.kind_of?(Msf::Session))) print_line("#{args[0]} routes through: Session #{comm.sid}") else print_line("#{args[0]} routes through: Local") end when "flush" Rex::Socket::SwitchBoard.flush_routes when "print" tbl = Table.new( Table::Style::Default, 'Header' => "Active Routing Table", 'Prefix' => "\n", 'Postfix' => "\n", 'Columns' => [ 'Subnet', 'Netmask', 'Gateway', ], 'ColProps' => { 'Subnet' => { 'MaxWidth' => 17 }, 'Netmask' => { 'MaxWidth' => 17 }, }) Rex::Socket::SwitchBoard.each { |route| if (route.comm.kind_of?(Msf::Session)) gw = "Session #{route.comm.sid}" else gw = route.comm.name.split(/::/)[-1] end tbl << [ route.subnet, route.netmask, gw ] } print(tbl.to_s) else cmd_route_help end end # # Tab completion for the route command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_route_tabs(str, words) if words.length == 1 return %w{add remove get flush print} end ret = [] case words[1] when "remove", "del" Rex::Socket::SwitchBoard.each { |route| case words.length when 2 ret << route.subnet when 3 if route.subnet == words[2] ret << route.netmask end when 4 if route.subnet == words[2] ret << route.comm.sid.to_s if route.comm.kind_of? Msf::Session end end } ret when "add" # We can't really complete the subnet and netmask args without # diving pretty deep into all sessions, so just be content with # completing sids for the last arg if words.length == 4 ret = framework.sessions.keys.map { |k| k.to_s } end # The "get" command takes one arg, but we can't complete it either... end ret end def cmd_save_help print_line "Usage: save" print_line print_line "Save the active datastore contents to disk for automatic use across restarts of the console" print_line print_line "The configuration is stored in #{Msf::Config.config_file}" print_line end # # Saves the active datastore contents to disk for automatic use across # restarts of the console. # def cmd_save(*args) defanged? # Save the console config driver.save_config # Save the framework's datastore begin framework.save_config if (active_module) active_module.save_config end rescue log_error("Save failed: #{$!}") return false end print_line("Saved configuration to: #{Msf::Config.config_file}") end def cmd_loadpath_help print_line "Usage: loadpath </path/to/modules>" print_line print_line "Loads modules from the given directory which should contain subdirectories for" print_line "module types, e.g. /path/to/modules/exploits" print_line end # # Adds one or more search paths. # def cmd_loadpath(*args) defanged? if (args.length == 0 or args.include? "-h") cmd_loadpath_help return true end totals = {} overall = 0 curr_path = nil begin # Walk the list of supplied search paths attempting to add each one # along the way args.each { |path| curr_path = path # Load modules, but do not consult the cache if (counts = framework.modules.add_module_path(path)) counts.each_pair { |type, count| totals[type] = (totals[type]) ? (totals[type] + count) : count overall += count } end } rescue NameError, RuntimeError log_error("Failed to add search path #{curr_path}: #{$!}") return true end added = "Loaded #{overall} modules:\n" totals.each_pair { |type, count| added << " #{count} #{type}#{count != 1 ? 's' : ''}\n" } print(added) end # # Tab completion for the loadpath command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_loadpath_tabs(str, words) return [] if words.length > 1 # This custom completion might better than Readline's... We'll leave it for now. #tab_complete_filenames(str,words) paths = [] if (File.directory?(str)) paths = Dir.entries(str) paths = paths.map { |f| if File.directory? File.join(str,f) File.join(str,f) end } paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' } else d = Dir.glob(str + "*").map { |f| f if File.directory?(f) } d.delete_if { |f| f.nil? or f == '.' or f == '..' } # If there's only one possibility, descend to the next level if (1 == d.length) paths = Dir.entries(d[0]) paths = paths.map { |f| if File.directory? File.join(d[0],f) File.join(d[0],f) end } paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' } else paths = d end end paths.sort! return paths end def cmd_search_help print_line "Usage: search [keywords]" print_line print_line "Keywords:" { 'app' => 'Modules that are client or server attacks', 'author' => 'Modules written by this author', 'bid' => 'Modules with a matching Bugtraq ID', 'cve' => 'Modules with a matching CVE ID', 'edb' => 'Modules with a matching Exploit-DB ID', 'name' => 'Modules with a matching descriptive name', 'osvdb' => 'Modules with a matching OSVDB ID', 'platform' => 'Modules affecting this platform', 'ref' => 'Modules with a matching ref', 'type' => 'Modules of a specific type (exploit, auxiliary, or post)', }.each_pair do |keyword, description| print_line " #{keyword.ljust 10}: #{description}" end print_line print_line "Examples:" print_line " search cve:2009 type:exploit app:client" print_line end # # Searches modules for specific keywords # def cmd_search(*args) match = '' @@search_opts.parse(args) { |opt, idx, val| case opt when "-t" print_error("Deprecated option. Use type:#{val} instead") cmd_search_help return when "-h" cmd_search_help return else match += val + " " end } if framework.db and framework.db.migrated and framework.db.modules_cached search_modules_sql(match) return end print_warning("Database not connected or cache not built, using slow search") tbl = generate_module_table("Matching Modules") [ framework.exploits, framework.auxiliary, framework.post, framework.payloads, framework.nops, framework.encoders ].each do |mset| mset.each do |m| o = mset.create(m[0]) rescue nil # Expected if modules are loaded without the right pre-requirements next if not o if not o.search_filter(match) tbl << [ o.fullname, o.disclosure_date.to_s, o.rank_to_s, o.name ] end end end print_line(tbl.to_s) end # Prints table of modules matching the search_string. # # @param (see Msf::DBManager#search_modules) # @return [void] def search_modules_sql(search_string) tbl = generate_module_table("Matching Modules") framework.db.search_modules(search_string).each do |o| tbl << [ o.fullname, o.disclosure_date.to_s, RankingName[o.rank].to_s, o.name ] end print_line(tbl.to_s) end # # Tab completion for the search command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_search_tabs(str, words) if words.length == 1 return @@search_opts.fmt.keys end case (words[-1]) when "-r" return RankingName.sort.map{|r| r[1]} when "-t" return %w{auxiliary encoder exploit nop payload post} end [] end def cmd_spool_help print_line "Usage: spool <off>|<filename>" print_line print_line "Example:" print_line " spool /tmp/console.log" print_line end def cmd_spool(*args) if args.include?('-h') or args.empty? cmd_spool_help return end color = driver.output.config[:color] if args[0] == "off" driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new) msg = "Spooling is now disabled" else driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(args[0])) msg = "Spooling to file #{args[0]}..." end # Restore color and prompt driver.output.config[:color] = color prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar driver.update_prompt("#{prompt} #{active_module.type}(%bld%red#{active_module.shortname}%clr) ", prompt_char, true) print_status(msg) return end def cmd_sessions_help print_line "Usage: sessions [options]" print_line print_line "Active session manipulation and interaction." print(@@sessions_opts.usage()) end # # Provides an interface to the sessions currently active in the framework. # def cmd_sessions(*args) begin method = nil quiet = false verbose = false sid = nil cmds = [] script = nil reset_ring = false # any arguments that don't correspond to an option or option arg will # be put in here extra = [] # Parse the command options @@sessions_opts.parse(args) { |opt, idx, val| case opt when "-q" quiet = true # Run a command on all sessions, or the session given with -i when "-c" method = 'cmd' if (val) cmds << val end when "-v" verbose = true # Do something with the supplied session identifier instead of # all sessions. when "-i" sid = val # Display the list of active sessions when "-l" method = 'list' when "-k" method = 'kill' sid = val if val if not sid print_error("Specify a session to kill") return false end when "-K" method = 'killall' when "-d" method = 'detach' sid = val # Run a script on all meterpreter sessions when "-s" if not script method = 'scriptall' script = val end # Upload and exec to the specific command session when "-u" method = 'upexec' sid = val # Reset the ring buffer read pointer when "-r" reset_ring = true method = 'reset_ring' # Display help banner when "-h" cmd_sessions_help return false else extra << val end } if sid and not framework.sessions.get(sid) print_error("Invalid session id") return false end if method.nil? and sid method = 'interact' end # Now, perform the actual method case method when 'cmd' if (cmds.length < 1) print_error("No command specified!") return false end cmds.each do |cmd| if sid sessions = [ sid ] else sessions = framework.sessions.keys.sort end sessions.each do |s| session = framework.sessions.get(s) print_status("Running '#{cmd}' on #{session.type} session #{s} (#{session.session_host})") if (session.type == "meterpreter") # If session.sys is nil, dont even try.. if not (session.sys) print_error("Session #{s} does not have stdapi loaded, skipping...") next end c, c_args = cmd.split(' ', 2) begin process = session.sys.process.execute(c, c_args, { 'Channelized' => true, 'Hidden' => true }) rescue ::Rex::Post::Meterpreter::RequestError print_error("Failed: #{$!.class} #{$!}") end if process and process.channel and (data = process.channel.read) print_line(data) end elsif session.type == "shell" if (output = session.shell_command(cmd)) print_line(output) end end # If the session isn't a meterpreter or shell type, it # could be a VNC session (which can't run commands) or # something custom (which we don't know how to run # commands on), so don't bother. end end when 'kill' if ((session = framework.sessions.get(sid))) print_status("Killing session #{sid}") session.kill else print_error("Invalid session identifier: #{sid}") end when 'killall' print_status("Killing all sessions...") framework.sessions.each_sorted do |s| if ((session = framework.sessions.get(s))) session.kill end end when 'detach' if ((session = framework.sessions.get(sid))) print_status("Detaching session #{sid}") if (session.interactive?) session.detach() end else print_error("Invalid session identifier: #{sid}") end when 'interact' if ((session = framework.sessions.get(sid))) if (session.interactive?) print_status("Starting interaction with #{session.name}...\n") if (quiet == false) self.active_session = session session.interact(driver.input.dup, driver.output) self.active_session = nil if (driver.input.supports_readline) driver.input.reset_tab_completion end else print_error("Session #{sid} is non-interactive.") end else print_error("Invalid session identifier: #{sid}") end when 'scriptall' if (script.nil?) print_error("No script specified!") return false end script_paths = {} script_paths['meterpreter'] = Msf::Sessions::Meterpreter.find_script_path(script) script_paths['shell'] = Msf::Sessions::CommandShell.find_script_path(script) if sid print_status("Running script #{script} on session #{sid}...") sessions = [ sid ] else print_status("Running script #{script} on all sessions...") sessions = framework.sessions.keys.sort end sessions.each do |s| if ((session = framework.sessions.get(s))) if (script_paths[session.type]) print_status("Session #{s} (#{session.session_host}):") begin session.execute_file(script_paths[session.type], extra) rescue ::Exception => e log_error("Error executing script: #{e.class} #{e}") end end end end when 'upexec' if ((session = framework.sessions.get(sid))) if (session.interactive?) if (session.type == "shell") # XXX: check for windows? session.init_ui(driver.input, driver.output) session.execute_script('spawn_meterpreter', nil) session.reset_ui else print_error("Session #{sid} is not a command shell session.") end else print_error("Session #{sid} is non-interactive.") end else print_error("Invalid session identifier: #{sid}") end when 'reset_ring' sessions = sid ? [ sid ] : framework.sessions.keys sessions.each do |sidx| s = framework.sessions[sidx] next if not (s and s.respond_to?(:ring_seq)) s.reset_ring_sequence print_status("Reset the ring buffer pointer for Session #{sidx}") end when 'list',nil print_line print(Serializer::ReadableText.dump_sessions(framework, :verbose => verbose)) print_line end rescue IOError, EOFError, Rex::StreamClosedError print_status("Session stream closed.") rescue ::Interrupt raise $! rescue ::Exception log_error("Session manipulation failed: #{$!} #{$!.backtrace.inspect}") end # Reset the active session self.active_session = nil return true end # # Tab completion for the sessions command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_sessions_tabs(str, words) if words.length == 1 return @@sessions_opts.fmt.keys end case words[-1] when "-i", "-k", "-d", "-u" return framework.sessions.keys.map { |k| k.to_s } when "-c" # Can't really complete commands hehe when "-s" # XXX: Complete scripts end [] end def cmd_set_help print_line "Usage: set [option] [value]" print_line print_line "Set the given option to value. If value is omitted, print the current value." print_line "If both are omitted, print options that are currently set." print_line print_line "If run from a module context, this will set the value in the module's" print_line "datastore. Use -g to operate on the global datastore" print_line end # # Sets a name to a value in a context aware environment. # def cmd_set(*args) # Figure out if these are global variables global = false if (args[0] == '-g') args.shift global = true end # Decide if this is an append operation append = false if (args[0] == '-a') args.shift append = true end # Determine which data store we're operating on if (active_module and global == false) datastore = active_module.datastore else global = true datastore = self.framework.datastore end # Dump the contents of the active datastore if no args were supplied if (args.length == 0) # If we aren't dumping the global data store, then go ahead and # dump it first if (!global) print("\n" + Msf::Serializer::ReadableText.dump_datastore( "Global", framework.datastore)) end # Dump the active datastore print("\n" + Msf::Serializer::ReadableText.dump_datastore( (global) ? "Global" : "Module: #{active_module.refname}", datastore) + "\n") return true elsif (args.length == 1) if (not datastore[args[0]].nil?) print_line("#{args[0]} => #{datastore[args[0]]}") return true else print_error("Unknown variable") cmd_set_help return false end end # Set the supplied name to the supplied value name = args[0] value = args[1, args.length-1].join(' ') if (name.upcase == "TARGET") # Different targets can have different architectures and platforms # so we need to rebuild the payload list whenever the target # changes. @cache_payloads = nil end # Security check -- make sure the data store element they are setting # is not prohibited if global and DefangedProhibitedDataStoreElements.include?(name) defanged? end # If the driver indicates that the value is not valid, bust out. if (driver.on_variable_set(global, name, value) == false) print_error("The value specified for #{name} is not valid.") return true end if append datastore[name] = datastore[name] + value else datastore[name] = value end print_line("#{name} => #{datastore[name]}") end # # Tab completion for the set command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_set_tabs(str, words) # A value has already been specified return [] if words.length > 2 # A value needs to be specified if words.length == 2 return tab_complete_option(str, words) end res = cmd_unset_tabs(str, words) || [ ] # There needs to be a better way to register global options, but for # now all we have is an ad-hoc list of opts that the shell treats # specially. res += %w{ ConsoleLogging LogLevel MinimumRank SessionLogging TimestampOutput Prompt PromptChar PromptTimeFormat } mod = active_module if (not mod) return res end mod.options.sorted.each { |e| name, opt = e res << name } # Exploits provide these three default options if (mod.exploit?) res << 'PAYLOAD' res << 'NOP' res << 'TARGET' end if (mod.exploit? or mod.payload?) res << 'ENCODER' end if (mod.auxiliary?) res << "ACTION" end if (mod.exploit? and mod.datastore['PAYLOAD']) p = framework.payloads.create(mod.datastore['PAYLOAD']) if (p) p.options.sorted.each { |e| name, opt = e res << name } end end return res end def cmd_setg_help print_line "Usage: setg [option] [value]" print_line print_line "Exactly like set -g, set a value in the global datastore." print_line end # # Sets the supplied variables in the global datastore. # def cmd_setg(*args) args.unshift('-g') cmd_set(*args) end # # Tab completion for the setg command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_setg_tabs(str, words) cmd_set_tabs(str, words) end def cmd_show_help global_opts = %w{all encoders nops exploits payloads auxiliary plugins options} print_status("Valid parameters for the \"show\" command are: #{global_opts.join(", ")}") module_opts = %w{ advanced evasion targets actions } print_status("Additional module-specific parameters are: #{module_opts.join(", ")}") end # # Displays the list of modules based on their type, or all modules if # no type is provided. # def cmd_show(*args) mod = self.active_module args << "all" if (args.length == 0) args.each { |type| case type when '-h' cmd_show_help when 'all' show_encoders show_nops show_exploits show_payloads show_auxiliary show_post show_plugins when 'encoders' show_encoders when 'nops' show_nops when 'exploits' show_exploits when 'payloads' show_payloads when 'auxiliary' show_auxiliary when 'post' show_post when 'options' if (mod) show_options(mod) else show_global_options end when 'advanced' if (mod) show_advanced_options(mod) else print_error("No module selected.") end when 'evasion' if (mod) show_evasion_options(mod) else print_error("No module selected.") end when 'sessions' if (active_module and active_module.respond_to?(:compatible_sessions)) sessions = active_module.compatible_sessions else sessions = framework.sessions.keys.sort end print_line print(Serializer::ReadableText.dump_sessions(framework, :session_ids => sessions)) print_line when "plugins" show_plugins when "targets" if (mod and mod.exploit?) show_targets(mod) else print_error("No exploit module selected.") end when "actions" if (mod and (mod.auxiliary? or mod.post?)) show_actions(mod) else print_error("No auxiliary module selected.") end else print_error("Invalid parameter \"#{type}\", use \"show -h\" for more information") end } end # # Tab completion for the show command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_show_tabs(str, words) return [] if words.length > 1 res = %w{all encoders nops exploits payloads auxiliary post plugins options} if (active_module) res.concat(%w{ advanced evasion targets actions }) if (active_module.respond_to? :compatible_sessions) res << "sessions" end end return res end def cmd_unload_help print_line "Usage: unload <plugin name>" print_line print_line "Unloads a plugin by its symbolic name. Use 'show plugins' to see a list of" print_line "currently loaded plugins." print_line end # # Unloads a plugin by its name. # def cmd_unload(*args) if (args.length == 0) cmd_unload_help return false end # Walk the plugins array framework.plugins.each { |plugin| # Unload the plugin if it matches the name we're searching for if (plugin.name == args[0]) print("Unloading plugin #{args[0]}...") framework.plugins.unload(plugin) print_line("unloaded.") break end } end # # Tab completion for the unload command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_unload_tabs(str, words) return [] if words.length > 1 tabs = [] framework.plugins.each { |k| tabs.push(k.name) } return tabs end def cmd_unset_help print_line "Usage: unset [-g] var1 var2 var3 ..." print_line print_line "The unset command is used to unset one or more variables." print_line "To flush all entires, specify 'all' as the variable name." print_line "With -g, operates on global datastore variables." print_line end # # Unsets a value if it's been set. # def cmd_unset(*args) # Figure out if these are global variables global = false if (args[0] == '-g') args.shift global = true end # Determine which data store we're operating on if (active_module and global == false) datastore = active_module.datastore else datastore = framework.datastore end # No arguments? No cookie. if (args.length == 0) cmd_unset_help return false end # If all was specified, then flush all of the entries if args[0] == 'all' print_line("Flushing datastore...") # Re-import default options into the module's datastore if (active_module and global == false) active_module.import_defaults # Or simply clear the global datastore else datastore.clear end return true end while ((val = args.shift)) if (driver.on_variable_unset(global, val) == false) print_error("The variable #{val} cannot be unset at this time.") next end print_line("Unsetting #{val}...") datastore.delete(val) end end # # Tab completion for the unset command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_unset_tabs(str, words) datastore = active_module ? active_module.datastore : self.framework.datastore datastore.keys end def cmd_unsetg_help print_line "Usage: unsetg var1 [var2 ...]" print_line print_line "Exactly like unset -g, unset global variables, or all" print_line end # # Unsets variables in the global data store. # def cmd_unsetg(*args) args.unshift('-g') cmd_unset(*args) end # # Tab completion for the unsetg command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_unsetg_tabs(str, words) self.framework.datastore.keys end alias cmd_unsetg_help cmd_unset_help def cmd_use_help print_line "Usage: use module_name" print_line print_line "The use command is used to interact with a module of a given name." print_line end # # Uses a module. # def cmd_use(*args) if (args.length == 0) cmd_use_help return false end # Try to create an instance of the supplied module name mod_name = args[0] begin if ((mod = framework.modules.create(mod_name)) == nil) print_error("Failed to load module: #{mod_name}") return false end rescue Rex::AmbiguousArgumentError => info print_error(info.to_s) rescue NameError => info log_error("The supplied module name is ambiguous: #{$!}.") end return false if (mod == nil) # Enstack the command dispatcher for this module type dispatcher = nil case mod.type when MODULE_ENCODER dispatcher = Msf::Ui::Console::CommandDispatcher::Encoder when MODULE_EXPLOIT dispatcher = Msf::Ui::Console::CommandDispatcher::Exploit when MODULE_NOP dispatcher = Msf::Ui::Console::CommandDispatcher::Nop when MODULE_PAYLOAD dispatcher = Msf::Ui::Console::CommandDispatcher::Payload when MODULE_AUX dispatcher = Msf::Ui::Console::CommandDispatcher::Auxiliary when MODULE_POST dispatcher = Msf::Ui::Console::CommandDispatcher::Post else print_error("Unsupported module type: #{mod.type}") return false end # If there's currently an active module, enqueque it and go back if (active_module) @previous_module = active_module cmd_back() end if (dispatcher != nil) driver.enstack_dispatcher(dispatcher) end # Update the active module self.active_module = mod # If a datastore cache exists for this module, then load it up if @dscache[active_module.fullname] active_module.datastore.update(@dscache[active_module.fullname]) end @cache_payloads = nil mod.init_ui(driver.input, driver.output) # Update the command prompt prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar driver.update_prompt("#{prompt} #{mod.type}(%bld%red#{mod.shortname}%clr) ", prompt_char, true) end # # Command to take to the previously active module # def cmd_previous() if @previous_module self.cmd_use(@previous_module.fullname) else print_error("There isn't a previous module at the moment") end end # # Help for the 'previous' command # def cmd_previous_help print_line "Usage: previous" print_line print_line "Set the previously loaded module as the current module" print_line end # # Command to enqueque a module on the module stack # def cmd_pushm(*args) # could check if each argument is a valid module, but for now let them hang themselves if args.count > 0 args.each do |arg| @module_name_stack.push(arg) # Note new modules are appended to the array and are only module (full)names end else #then just push the active module if active_module #print_status "Pushing the active module" @module_name_stack.push(active_module.fullname) else print_error("There isn't an active module and you didn't specify a module to push") return self.cmd_pushm_help end end end # # Tab completion for the pushm command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_pushm_tabs(str, words) tab_complete_module(str, words) end # # Help for the 'pushm' command # def cmd_pushm_help print_line "Usage: pushm [module1 [,module2, module3...]]" print_line print_line "push current active module or specified modules onto the module stack" print_line end # # Command to dequeque a module from the module stack # def cmd_popm(*args) if (args.count > 1 or not args[0].respond_to?("to_i")) return self.cmd_popm_help elsif args.count == 1 # then pop 'n' items off the stack, but don't change the active module if args[0].to_i >= @module_name_stack.count # in case they pass in a number >= the length of @module_name_stack @module_name_stack = [] print_status("The module stack is empty") else @module_name_stack.pop[args[0]] end else #then just pop the array and make that the active module pop = @module_name_stack.pop if pop return self.cmd_use(pop) else print_error("There isn't anything to pop, the module stack is empty") end end end # # Help for the 'popm' command # def cmd_popm_help print_line "Usage: popm [n]" print_line print_line "pop the latest module off of the module stack and make it the active module" print_line "or pop n modules off the stack, but don't change the active module" print_line end # # Tab completion for the use command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completd def cmd_use_tabs(str, words) return [] if words.length > 1 tab_complete_module(str, words) end # # Returns the revision of the framework and console library # def cmd_version(*args) svn_console_version = "$Revision: 15168 $" svn_metasploit_version = Msf::Framework::Revision.match(/ (.+?) \$/)[1] rescue nil if svn_metasploit_version print_line("Framework: #{Msf::Framework::Version}.#{svn_metasploit_version}") else print_line("Framework: #{Msf::Framework::Version}") end print_line("Console : #{Msf::Framework::Version}.#{svn_console_version.match(/ (.+?) \$/)[1]}") return true end def cmd_grep_help print_line "Usage: grep [options] pattern cmd" print_line print_line "Grep the results of a console command (similar to Linux grep command)" print(@@grep_opts.usage()) end # # Greps the output of another console command, usage is similar the shell grep command # grep [options] pattern other_cmd [other command's args], similar to the shell's grep [options] pattern file # however it also includes -k to keep lines and -s to skip lines. grep -k 5 is useful for keeping table headers # # @param args [Array<String>] Args to the grep command minimally including a pattern & a command to search # @return [String,nil] Results matching the regular expression given def cmd_grep(*args) return cmd_grep_help if args.length < 2 match_mods = {:insensitive => false} output_mods = {:count => false, :invert => false} @@grep_opts.parse(args.dup) do |opt, idx, val| case opt when "-h" return cmd_grep_help when "-m" # limit to arg matches match_mods[:max] = val.to_i # delete opt and val from args list args.shift(2) when "-A" # also return arg lines after a match output_mods[:after] = val.to_i # delete opt and val from args list args.shift(2) when "-B" # also return arg lines before a match output_mods[:before] = val.to_i # delete opt and val from args list args.shift(2) when "-v" # invert match match_mods[:invert] = true # delete opt from args list args.shift when "-i" # case insensitive match_mods[:insensitive] = true args.shift when "-c" # just count matches output_mods[:count] = true args.shift when "-k" # keep arg number of lines at the top of the output, useful for commands with table headers in output output_mods[:keep] = val.to_i args.shift(2) when "-s" # skip arg number of lines at the top of the output, useful for avoiding undesirable matches output_mods[:skip] = val.to_i args.shift(2) end end # after deleting parsed options, the only args left should be the pattern, the cmd to run, and cmd args pattern = args.shift if match_mods[:insensitive] rx = Regexp.new(pattern, true) else rx = Regexp.new(pattern) end cmd = args.join(" ") # get a ref to the current console driver orig_driver = self.driver # redirect output after saving the old ones and getting a new output buffer to use for redirect orig_driver_output = orig_driver.output orig_driver_input = orig_driver.input # we use a rex buffer but add a write method to the instance, which is # required in order to be valid $stdout temp_output = Rex::Ui::Text::Output::Buffer.new temp_output.extend Rex::Ui::Text::Output::Buffer::Stdout orig_driver.init_ui(orig_driver_input,temp_output) # run the desired command to be grepped orig_driver.run_single(cmd) # restore original output orig_driver.init_ui(orig_driver_input,orig_driver_output) # restore the prompt so we don't get "msf > >". prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar mod = active_module if mod # if there is an active module, give them the fanciness they have come to expect driver.update_prompt("#{prompt} #{mod.type}(%bld%red#{mod.shortname}%clr) ", prompt_char, true) else driver.update_prompt("#{prompt}", prompt_char, true) end # dump the command's output so we can grep it cmd_output = temp_output.dump_buffer # Bail if the command failed if cmd_output =~ /Unknown command:/ print_error("Unknown command: #{args[0]}.") return false end # put lines into an array so we can access them more easily and split('\n') doesn't work on the output obj. all_lines = cmd_output.lines.select {|line| line} # control matching based on remaining match_mods (:insensitive was already handled) if match_mods[:invert] statement = 'not line =~ rx' else statement = 'line =~ rx' end our_lines = [] count = 0 all_lines.each_with_index do |line, line_num| next if (output_mods[:skip] and line_num < output_mods[:skip]) our_lines << line if (output_mods[:keep] and line_num < output_mods[:keep]) # we don't wan't to keep processing if we have a :max and we've reached it already (not counting skips/keeps) break if match_mods[:max] and count >= match_mods[:max] if eval statement count += 1 # we might get a -A/after and a -B/before at the same time our_lines += retrieve_grep_lines(all_lines,line_num,output_mods[:before], output_mods[:after]) end end # now control output based on remaining output_mods such as :count return print_status(count.to_s) if output_mods[:count] our_lines.each {|line| print line} end # # Tab completion for the grep command # # @param str [String] the string currently being typed before tab was hit # @param words [Array<String>] the previously completed words on the command line. words is always # at least 1 when tab completion has reached this stage since the command itself has been completed def cmd_grep_tabs(str, words) tabs = @@grep_opts.fmt.keys || [] # default to use grep's options # if not an opt, use normal tab comp. # @todo uncomment out next line when tab_completion normalization is complete RM7649 or # replace with new code that permits "nested" tab completion # tabs = driver.get_all_commands if (str and str =~ /\w/) tabs end # # Tab complete module names # def tab_complete_module(str, words) res = [] framework.modules.module_types.each do |mtyp| mset = framework.modules.module_names(mtyp) mset.each do |mref| res << mtyp + '/' + mref end end return res.sort end # # Provide tab completion for option values # def tab_complete_option(str, words) opt = words[1] res = [] mod = active_module # With no active module, we have nothing to compare if (not mod) return res end # Well-known option names specific to exploits if (mod.exploit?) return option_values_payloads() if opt.upcase == 'PAYLOAD' return option_values_targets() if opt.upcase == 'TARGET' return option_values_nops() if opt.upcase == 'NOPS' return option_values_encoders() if opt.upcase == 'StageEncoder' end # Well-known option names specific to auxiliaries if (mod.auxiliary?) return option_values_actions() if opt.upcase == 'ACTION' end # The ENCODER option works for payloads and exploits if ((mod.exploit? or mod.payload?) and opt.upcase == 'ENCODER') return option_values_encoders() end # Well-known option names specific to post-exploitation if (mod.post? or mod.exploit?) return option_values_sessions() if opt.upcase == 'SESSION' end # Is this option used by the active module? if (mod.options.include?(opt)) res.concat(option_values_dispatch(mod.options[opt], str, words)) end # How about the selected payload? if (mod.exploit? and mod.datastore['PAYLOAD']) p = framework.payloads.create(mod.datastore['PAYLOAD']) if (p and p.options.include?(opt)) res.concat(option_values_dispatch(p.options[opt], str, words)) end end return res end # # Provide possible option values based on type # def option_values_dispatch(o, str, words) res = [] res << o.default.to_s if o.default case o.class.to_s when 'Msf::OptAddress' case o.name.upcase when 'RHOST' option_values_target_addrs().each do |addr| res << addr end when 'LHOST' rh = self.active_module.datastore["RHOST"] if rh and not rh.empty? res << Rex::Socket.source_address(rh) else res << Rex::Socket.source_address() end else end when 'Msf::OptAddressRange' case str when /\/$/ res << str+'32' res << str+'24' res << str+'16' when /\-$/ res << str+str[0, str.length - 1] else option_values_target_addrs().each do |addr| res << addr+'/32' res << addr+'/24' res << addr+'/16' end end when 'Msf::OptPort' case o.name.upcase when 'RPORT' option_values_target_ports().each do |port| res << port end end if (res.empty?) res << (rand(65534)+1).to_s end when 'Msf::OptEnum' o.enums.each do |val| res << val end when 'Msf::OptPath' files = tab_complete_filenames(str,words) res += files if files end return res end # # Provide valid payload options for the current exploit # def option_values_payloads return @cache_payloads if @cache_payloads @cache_payloads = active_module.compatible_payloads.map { |refname, payload| refname } @cache_payloads end # # Provide valid session options for the current post-exploit module # def option_values_sessions active_module.compatible_sessions.map { |sid| sid.to_s } end # # Provide valid target options for the current exploit # def option_values_targets res = [] if (active_module.targets) 1.upto(active_module.targets.length) { |i| res << (i-1).to_s } end return res end # # Provide valid action options for the current auxiliary module # def option_values_actions res = [] if (active_module.actions) active_module.actions.each { |i| res << i.name } end return res end # # Provide valid nops options for the current exploit # def option_values_nops framework.nops.map { |refname, mod| refname } end # # Provide valid encoders options for the current exploit or payload # def option_values_encoders framework.encoders.map { |refname, mod| refname } end # # Provide the target addresses # def option_values_target_addrs res = [ ] res << Rex::Socket.source_address() return res if not framework.db.active # List only those hosts with matching open ports? mport = self.active_module.datastore['RPORT'] if (mport) mport = mport.to_i hosts = {} framework.db.each_service(framework.db.workspace) do |service| if (service.port == mport) hosts[ service.host.address ] = true end end hosts.keys.each do |host| res << host end # List all hosts in the database else framework.db.each_host(framework.db.workspace) do |host| res << host.address end end return res end # # Provide the target ports # def option_values_target_ports res = [ ] return res if not framework.db.active return res if not self.active_module.datastore['RHOST'] host = framework.db.has_host?(framework.db.workspace, self.active_module.datastore['RHOST']) return res if not host framework.db.each_service(framework.db.workspace) do |service| if (service.host_id == host.id) res << service.port.to_s end end return res end def cmd_go_pro_help print_line "Usage: go_pro" print_line print_line "Launch the Metasploit web GUI" print_line end def cmd_go_pro(*args) @@go_pro_opts.parse(args) do |opt, idx, val| case opt when "-h" cmd_go_pro_help return false end end unless is_apt print_line " This command is only available on deb package installations," print_line " such as Kali Linux." return false end unless is_metasploit_debian_package_installed print_warning "You need to install the 'metasploit' package first." print_warning "Type 'apt-get install -y metasploit' to do this now, then exit" print_warning "and restart msfconsole to try again." return false end # If I've gotten this far, I know that this is apt-installed, the # metasploit package is here, and I'm ready to rock. if is_metasploit_service_running launch_metasploit_browser else print_status "Starting the Metasploit services. This can take a little time." start_metasploit_service select(nil,nil,nil,3) if is_metasploit_service_running launch_metasploit_browser else print_error "Metasploit services aren't running. Type 'service metasploit start' and try again." end end return true end protected # # Go_pro methods -- these are used to start and connect to # Metasploit Community / Pro. # # Note that this presumes a default port. def launch_metasploit_browser cmd = "/usr/bin/xdg-open" unless ::File.executable_real? cmd print_warning "Can't figure out your default browser, please visit https://localhost:3790" print_warning "to start Metasploit Community / Pro." return false end svc_log = File.expand_path(File.join(msfbase_dir, ".." , "engine", "prosvc_stdout.log")) return unless ::File.readable_real? svc_log really_started = false # This method is a little lame but it's a short enough file that it # shouldn't really matter that we open and close it a few times. timeout = 0 until really_started select(nil,nil,nil,3) log_data = ::File.open(svc_log, "rb") {|f| f.read f.stat.size} really_started = log_data =~ /^\[\*\] Ready/ # This is webserver ready if really_started print_line print_good "Metasploit Community / Pro is up and running, connecting now." print_good "If this is your first time connecting, you will be presented with" print_good "a self-signed certificate warning. Accept it to create a new user." select(nil,nil,nil,7) browser_pid = ::Process.spawn(cmd, "https://localhost:3790") ::Process.detach(browser_pid) elsif timeout >= 200 # 200 * 3 seconds is 10 minutes and that is tons of time. print_line print_warning "For some reason, Community / Pro didn't start in a timely fashion." print_warning "You might want to restart the Metasploit services by typing" print_warning "'service metasploit restart' . Sorry it didn't work out." return false else print "." timeout += 1 end end end def start_metasploit_service cmd = File.expand_path(File.join(msfbase_dir, '..', '..', '..', 'scripts', 'start.sh')) return unless ::File.executable_real? cmd %x{#{cmd}}.each_line do |line| print_status line.chomp end end def is_metasploit_service_running cmd = "/usr/sbin/service" system("#{cmd} metasploit status >/dev/null") # Both running returns true, otherwise, false. end def is_metasploit_debian_package_installed cmd = "/usr/bin/dpkg" return unless ::File.executable_real? cmd installed_packages = %x{#{cmd} -l 'metasploit'} installed_packages.each_line do |line| if line =~ /^.i metasploit / # Yes, trailing space return true end end return false end # Determines if this is an apt-based install def is_apt File.exists?(File.expand_path(File.join(msfbase_dir, '.apt'))) end # # Module list enumeration # def show_encoders(regex = nil, minrank = nil, opts = nil) # :nodoc: # If an active module has been selected and it's an exploit, get the # list of compatible encoders and display them if (active_module and active_module.exploit? == true) show_module_set("Compatible Encoders", active_module.compatible_encoders, regex, minrank, opts) else show_module_set("Encoders", framework.encoders, regex, minrank, opts) end end def show_nops(regex = nil, minrank = nil, opts = nil) # :nodoc: show_module_set("NOP Generators", framework.nops, regex, minrank, opts) end def show_exploits(regex = nil, minrank = nil, opts = nil) # :nodoc: show_module_set("Exploits", framework.exploits, regex, minrank, opts) end def show_payloads(regex = nil, minrank = nil, opts = nil) # :nodoc: # If an active module has been selected and it's an exploit, get the # list of compatible payloads and display them if (active_module and active_module.exploit? == true) show_module_set("Compatible Payloads", active_module.compatible_payloads, regex, minrank, opts) else show_module_set("Payloads", framework.payloads, regex, minrank, opts) end end def show_auxiliary(regex = nil, minrank = nil, opts = nil) # :nodoc: show_module_set("Auxiliary", framework.auxiliary, regex, minrank, opts) end def show_post(regex = nil, minrank = nil, opts = nil) # :nodoc: show_module_set("Post", framework.post, regex, minrank, opts) end def show_options(mod) # :nodoc: mod_opt = Serializer::ReadableText.dump_options(mod, ' ') print("\nModule options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0) # If it's an exploit and a payload is defined, create it and # display the payload's options if (mod.exploit? and mod.datastore['PAYLOAD']) p = framework.payloads.create(mod.datastore['PAYLOAD']) if (!p) print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n") return end p.share_datastore(mod.datastore) if (p) p_opt = Serializer::ReadableText.dump_options(p, ' ') print("\nPayload options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0) end end # Print the selected target if (mod.exploit? and mod.target) mod_targ = Serializer::ReadableText.dump_exploit_target(mod, ' ') print("\nExploit target:\n\n#{mod_targ}\n") if (mod_targ and mod_targ.length > 0) end # Uncomment this line if u want target like msf2 format #print("\nTarget: #{mod.target.name}\n\n") end def show_global_options columns = [ 'Option', 'Current Setting', 'Description' ] tbl = Table.new( Table::Style::Default, 'Header' => 'Global Options:', 'Prefix' => "\n", 'Postfix' => "\n", 'Columns' => columns ) [ [ 'ConsoleLogging', framework.datastore['ConsoleLogging'] || '', 'Log all console input and output' ], [ 'LogLevel', framework.datastore['LogLevel'] || '', 'Verbosity of logs (default 0, max 5)' ], [ 'MinimumRank', framework.datastore['MinimumRank'] || '', 'The minimum rank of exploits that will run without explicit confirmation' ], [ 'SessionLogging', framework.datastore['SessionLogging'] || '', 'Log all input and output for sessions' ], [ 'TimestampOutput', framework.datastore['TimestampOutput'] || '', 'Prefix all console output with a timestamp' ], [ 'Prompt', framework.datastore['Prompt'] || '', "The prompt string, defaults to \"#{Msf::Ui::Console::Driver::DefaultPrompt}\"" ], [ 'PromptChar', framework.datastore['PromptChar'] || '', "The prompt character, defaults to \"#{Msf::Ui::Console::Driver::DefaultPromptChar}\"" ], [ 'PromptTimeFormat', framework.datastore['PromptTimeFormat'] || '', 'A format for timestamp escapes in the prompt, see ruby\'s strftime docs' ], ].each { |r| tbl << r } print(tbl.to_s) end def show_targets(mod) # :nodoc: mod_targs = Serializer::ReadableText.dump_exploit_targets(mod, ' ') print("\nExploit targets:\n\n#{mod_targs}\n") if (mod_targs and mod_targs.length > 0) end def show_actions(mod) # :nodoc: mod_actions = Serializer::ReadableText.dump_auxiliary_actions(mod, ' ') print("\nAuxiliary actions:\n\n#{mod_actions}\n") if (mod_actions and mod_actions.length > 0) end def show_advanced_options(mod) # :nodoc: mod_opt = Serializer::ReadableText.dump_advanced_options(mod, ' ') print("\nModule advanced options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0) # If it's an exploit and a payload is defined, create it and # display the payload's options if (mod.exploit? and mod.datastore['PAYLOAD']) p = framework.payloads.create(mod.datastore['PAYLOAD']) if (!p) print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n") return end p.share_datastore(mod.datastore) if (p) p_opt = Serializer::ReadableText.dump_advanced_options(p, ' ') print("\nPayload advanced options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0) end end end def show_evasion_options(mod) # :nodoc: mod_opt = Serializer::ReadableText.dump_evasion_options(mod, ' ') print("\nModule evasion options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0) # If it's an exploit and a payload is defined, create it and # display the payload's options if (mod.exploit? and mod.datastore['PAYLOAD']) p = framework.payloads.create(mod.datastore['PAYLOAD']) if (!p) print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n") return end p.share_datastore(mod.datastore) if (p) p_opt = Serializer::ReadableText.dump_evasion_options(p, ' ') print("\nPayload evasion options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0) end end end def show_plugins # :nodoc: tbl = Table.new( Table::Style::Default, 'Header' => 'Plugins', 'Prefix' => "\n", 'Postfix' => "\n", 'Columns' => [ 'Name', 'Description' ] ) framework.plugins.each { |plugin| tbl << [ plugin.name, plugin.desc ] } print(tbl.to_s) end def show_module_set(type, module_set, regex = nil, minrank = nil, opts = nil) # :nodoc: tbl = generate_module_table(type) module_set.sort.each { |refname, mod| o = nil begin o = mod.new rescue ::Exception end next if not o # handle a search string, search deep if( not regex or o.name.match(regex) or o.description.match(regex) or o.refname.match(regex) or o.references.map{|x| [x.ctx_id + '-' + x.ctx_val, x.to_s]}.join(' ').match(regex) or o.author.to_s.match(regex) ) if (not minrank or minrank <= o.rank) show = true if opts mod_opt_keys = o.options.keys.map { |x| x.downcase } opts.each do |opt,val| if mod_opt_keys.include?(opt.downcase) == false or (val != nil and o.datastore[opt] != val) show = false end end end if (opts == nil or show == true) tbl << [ refname, o.disclosure_date||"", o.rank_to_s, o.name ] end end end } print(tbl.to_s) end def generate_module_table(type) # :nodoc: Table.new( Table::Style::Default, 'Header' => type, 'Prefix' => "\n", 'Postfix' => "\n", 'Columns' => [ 'Name', 'Disclosure Date', 'Rank', 'Description' ] ) end # # Returns an array of lines at the provided line number plus any before and/or after lines requested # from all_lines by supplying the +before+ and/or +after+ parameters which are always positive # # @param all_lines [Array<String>] An array of all lines being considered for matching # @param line_num [Integer] The line number in all_lines which has satisifed the match # @param after [Integer] The number of lines after the match line to include (should always be positive) # @param before [Integer] The number of lines before the match line to include (should always be positive) # @return [Array<String>] Array of lines including the line at line_num and any +before+ and/or +after+ def retrieve_grep_lines(all_lines,line_num, before = nil, after = nil) after = after.to_i.abs before = before.to_i.abs start = line_num - before start = 0 if start < 0 finish = line_num + after return all_lines.slice(start..finish) end end end end end end
27.394867
149
0.662396
e2db40403c4343ab9378b038f233974061a197e9
1,397
class Glfw < Formula desc "Multi-platform library for OpenGL applications" homepage "https://www.glfw.org/" url "https://github.com/glfw/glfw/archive/3.3.3.tar.gz" sha256 "aa9922b55a464d5bab58fcbe5a619f517d54e3dc122361c116de573670006a7a" license "Zlib" head "https://github.com/glfw/glfw.git" bottle do sha256 cellar: :any, arm64_big_sur: "9f64dee7187b644ba98c6009890a5761d575516a10e055de2c75bb7c88e1ffdb" sha256 cellar: :any, big_sur: "68cf1e73ab3d2f826847607a07b7204a317c696ff635d0789d35b52df3dfe8dd" sha256 cellar: :any, catalina: "8d87eeccf2a8376c8e29fbc46f0d47e02738b5f999ab8aeacdd148d53c6d15bc" sha256 cellar: :any, mojave: "f2fe8dcb33b5dd0a53d5d05fe609bf270206c51e37d7a996bbb2a2089b6de2fd" end depends_on "cmake" => :build def install args = std_cmake_args + %w[ -DGLFW_USE_CHDIR=TRUE -DGLFW_USE_MENUBAR=TRUE -DBUILD_SHARED_LIBS=TRUE ] system "cmake", *args, "." system "make", "install" end test do (testpath/"test.c").write <<~EOS #define GLFW_INCLUDE_GLU #include <GLFW/glfw3.h> #include <stdlib.h> int main() { if (!glfwInit()) exit(EXIT_FAILURE); glfwTerminate(); return 0; } EOS system ENV.cc, "test.c", "-o", "test", "-I#{include}", "-L#{lib}", "-lglfw" system "./test" end end
29.104167
106
0.666428
f87f92c05227749ca6aa05f4d713b6bf5b6d3e95
38,166
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module GkeHub module V1beta1 # Membership contains information about a member cluster. # @!attribute [r] name # @return [::String] # Output only. The full, unique name of this Membership resource in the # format `projects/*/locations/*/memberships/{membership_id}`, set during # creation. # # `membership_id` must be a valid RFC 1123 compliant DNS label: # # 1. At most 63 characters in length # 2. It must consist of lower case alphanumeric characters or `-` # 3. It must start and end with an alphanumeric character # # Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, # with a maximum length of 63 characters. # @!attribute [rw] labels # @return [::Google::Protobuf::Map{::String => ::String}] # Optional. GCP labels for this membership. # @!attribute [rw] description # @return [::String] # Optional. Description of this membership, limited to 63 characters. # Must match the regex: `[a-zA-Z0-9][a-zA-Z0-9_\-\.\ ]*` # @!attribute [rw] endpoint # @return [::Google::Cloud::GkeHub::V1beta1::MembershipEndpoint] # Optional. Endpoint information to reach this member. # @!attribute [r] state # @return [::Google::Cloud::GkeHub::V1beta1::MembershipState] # Output only. State of the Membership resource. # @!attribute [rw] authority # @return [::Google::Cloud::GkeHub::V1beta1::Authority] # Optional. How to identify workloads from this Membership. # See the documentation on Workload Identity for more details: # https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity # @!attribute [r] create_time # @return [::Google::Protobuf::Timestamp] # Output only. When the Membership was created. # @!attribute [r] update_time # @return [::Google::Protobuf::Timestamp] # Output only. When the Membership was last updated. # @!attribute [r] delete_time # @return [::Google::Protobuf::Timestamp] # Output only. When the Membership was deleted. # @!attribute [rw] external_id # @return [::String] # Optional. An externally-generated and managed ID for this Membership. This # ID may be modified after creation, but this is not recommended. For GKE # clusters, external_id is managed by the Hub API and updates will be # ignored. # # The ID must match the regex: `[a-zA-Z0-9][a-zA-Z0-9_\-\.]*` # # If this Membership represents a Kubernetes cluster, this value should be # set to the UID of the `kube-system` namespace object. # @!attribute [r] last_connection_time # @return [::Google::Protobuf::Timestamp] # Output only. For clusters using Connect, the timestamp of the most recent # connection established with Google Cloud. This time is updated every # several minutes, not continuously. For clusters that do not use GKE # Connect, or that have never connected successfully, this field will be # unset. # @!attribute [r] unique_id # @return [::String] # Output only. Google-generated UUID for this resource. This is unique across # all Membership resources. If a Membership resource is deleted and another # resource with the same name is created, it gets a different unique_id. # @!attribute [rw] infrastructure_type # @return [::Google::Cloud::GkeHub::V1beta1::Membership::InfrastructureType] # Optional. The infrastructure type this Membership is running on. class Membership include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # @!attribute [rw] key # @return [::String] # @!attribute [rw] value # @return [::String] class LabelsEntry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Specifies the infrastructure type of a Membership. Infrastructure type is # used by Hub to control infrastructure-specific behavior, including pricing. # # Each GKE distribution (on-GCP, on-Prem, on-X,...) will set this field # automatically, but Attached Clusters customers should specify a type # during registration. module InfrastructureType # No type was specified. Some Hub functionality may require a type be # specified, and will not support Memberships with this value. INFRASTRUCTURE_TYPE_UNSPECIFIED = 0 # Private infrastructure that is owned or operated by customer. This # includes GKE distributions such as GKE-OnPrem and GKE-OnBareMetal. ON_PREM = 1 # Public cloud infrastructure. MULTI_CLOUD = 2 end end # MembershipEndpoint contains information needed to contact a Kubernetes API, # endpoint and any additional Kubernetes metadata. # @!attribute [rw] gke_cluster # @return [::Google::Cloud::GkeHub::V1beta1::GkeCluster] # Optional. Specific information for a GKE-on-GCP cluster. # @!attribute [rw] on_prem_cluster # @return [::Google::Cloud::GkeHub::V1beta1::OnPremCluster] # Optional. Specific information for a GKE On-Prem cluster. # @!attribute [rw] multi_cloud_cluster # @return [::Google::Cloud::GkeHub::V1beta1::MultiCloudCluster] # Optional. Specific information for a GKE Multi-Cloud cluster. # @!attribute [r] kubernetes_metadata # @return [::Google::Cloud::GkeHub::V1beta1::KubernetesMetadata] # Output only. Useful Kubernetes-specific metadata. # @!attribute [rw] kubernetes_resource # @return [::Google::Cloud::GkeHub::V1beta1::KubernetesResource] # Optional. The in-cluster Kubernetes Resources that should be applied for a # correctly registered cluster, in the steady state. These resources: # # * Ensure that the cluster is exclusively registered to one and only one # Hub Membership. # * Propagate Workload Pool Information available in the Membership # Authority field. # * Ensure proper initial configuration of default Hub Features. class MembershipEndpoint include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # KubernetesResource contains the YAML manifests and configuration for # Membership Kubernetes resources in the cluster. After CreateMembership or # UpdateMembership, these resources should be re-applied in the cluster. # @!attribute [rw] membership_cr_manifest # @return [::String] # Input only. The YAML representation of the Membership CR. This field is # ignored for GKE clusters where Hub can read the CR directly. # # Callers should provide the CR that is currently present in the cluster # during CreateMembership or UpdateMembership, or leave this field empty if # none exists. The CR manifest is used to validate the cluster has not been # registered with another Membership. # @!attribute [r] membership_resources # @return [::Array<::Google::Cloud::GkeHub::V1beta1::ResourceManifest>] # Output only. Additional Kubernetes resources that need to be applied to the # cluster after Membership creation, and after every update. # # This field is only populated in the Membership returned from a successful # long-running operation from CreateMembership or UpdateMembership. It is not # populated during normal GetMembership or ListMemberships requests. To get # the resource manifest after the initial registration, the caller should # make a UpdateMembership call with an empty field mask. # @!attribute [r] connect_resources # @return [::Array<::Google::Cloud::GkeHub::V1beta1::ResourceManifest>] # Output only. The Kubernetes resources for installing the GKE Connect agent # # This field is only populated in the Membership returned from a successful # long-running operation from CreateMembership or UpdateMembership. It is not # populated during normal GetMembership or ListMemberships requests. To get # the resource manifest after the initial registration, the caller should # make a UpdateMembership call with an empty field mask. # @!attribute [rw] resource_options # @return [::Google::Cloud::GkeHub::V1beta1::ResourceOptions] # Optional. Options for Kubernetes resource generation. class KubernetesResource include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # ResourceOptions represent options for Kubernetes resource generation. # @!attribute [rw] connect_version # @return [::String] # Optional. The Connect agent version to use for connect_resources. Defaults # to the latest GKE Connect version. The version must be a currently # supported version, obsolete versions will be rejected. # @!attribute [rw] v1beta1_crd # @return [::Boolean] # Optional. Use `apiextensions/v1beta1` instead of `apiextensions/v1` for # CustomResourceDefinition resources. # This option should be set for clusters with Kubernetes apiserver versions # <1.16. # @!attribute [rw] k8s_version # @return [::String] # Optional. Major version of the Kubernetes cluster. This is only used to # determine which version to use for the CustomResourceDefinition resources, # `apiextensions/v1beta1` or`apiextensions/v1`. class ResourceOptions include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # ResourceManifest represents a single Kubernetes resource to be applied to # the cluster. # @!attribute [rw] manifest # @return [::String] # YAML manifest of the resource. # @!attribute [rw] cluster_scoped # @return [::Boolean] # Whether the resource provided in the manifest is `cluster_scoped`. # If unset, the manifest is assumed to be namespace scoped. # # This field is used for REST mapping when applying the resource in a # cluster. class ResourceManifest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # GkeCluster contains information specific to GKE clusters. # @!attribute [rw] resource_link # @return [::String] # Immutable. Self-link of the GCP resource for the GKE cluster. For example: # # //container.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster # # Zonal clusters are also supported. # @!attribute [r] cluster_missing # @return [::Boolean] # Output only. If cluster_missing is set then it denotes that the GKE cluster # no longer exists in the GKE Control Plane. class GkeCluster include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # OnPremCluster contains information specific to GKE On-Prem clusters. # @!attribute [rw] resource_link # @return [::String] # Immutable. Self-link of the GCP resource for the GKE On-Prem cluster. For # example: # # //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/vmwareClusters/my-cluster # //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/bareMetalClusters/my-cluster # @!attribute [r] cluster_missing # @return [::Boolean] # Output only. If cluster_missing is set then it denotes that # API(gkeonprem.googleapis.com) resource for this GKE On-Prem cluster no # longer exists. # @!attribute [rw] admin_cluster # @return [::Boolean] # Immutable. Whether the cluster is an admin cluster. class OnPremCluster include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # MultiCloudCluster contains information specific to GKE Multi-Cloud clusters. # @!attribute [rw] resource_link # @return [::String] # Immutable. Self-link of the GCP resource for the GKE Multi-Cloud cluster. # For example: # # //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/awsClusters/my-cluster # //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/azureClusters/my-cluster # @!attribute [r] cluster_missing # @return [::Boolean] # Output only. If cluster_missing is set then it denotes that # API(gkemulticloud.googleapis.com) resource for this GKE Multi-Cloud cluster # no longer exists. class MultiCloudCluster include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # KubernetesMetadata provides informational metadata for Memberships # representing Kubernetes clusters. # @!attribute [r] kubernetes_api_server_version # @return [::String] # Output only. Kubernetes API server version string as reported by # '/version'. # @!attribute [r] node_provider_id # @return [::String] # Output only. Node providerID as reported by the first node in the list of # nodes on the Kubernetes endpoint. On Kubernetes platforms that support # zero-node clusters (like GKE-on-GCP), the node_count will be zero and the # node_provider_id will be empty. # @!attribute [r] node_count # @return [::Integer] # Output only. Node count as reported by Kubernetes nodes resources. # @!attribute [r] vcpu_count # @return [::Integer] # Output only. vCPU count as reported by Kubernetes nodes resources. # @!attribute [r] memory_mb # @return [::Integer] # Output only. The total memory capacity as reported by the sum of all # Kubernetes nodes resources, defined in MB. # @!attribute [r] update_time # @return [::Google::Protobuf::Timestamp] # Output only. The time at which these details were last updated. This # update_time is different from the Membership-level update_time since # EndpointDetails are updated internally for API consumers. class KubernetesMetadata include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Authority encodes how Google will recognize identities from this Membership. # See the workload identity documentation for more details: # https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity # @!attribute [rw] issuer # @return [::String] # Optional. A JSON Web Token (JWT) issuer URI. `issuer` must start with # `https://` and be a valid URL with length <2000 characters. # # If set, then Google will allow valid OIDC tokens from this issuer to # authenticate within the workload_identity_pool. OIDC discovery will be # performed on this URI to validate tokens from the issuer. # # Clearing `issuer` disables Workload Identity. `issuer` cannot be directly # modified; it must be cleared (and Workload Identity disabled) before using # a new issuer (and re-enabling Workload Identity). # @!attribute [r] workload_identity_pool # @return [::String] # Output only. The name of the workload identity pool in which `issuer` will # be recognized. # # There is a single Workload Identity Pool per Hub that is shared # between all Memberships that belong to that Hub. For a Hub hosted in # \\{PROJECT_ID}, the workload pool format is `{PROJECT_ID}.hub.id.goog`, # although this is subject to change in newer versions of this API. # @!attribute [r] identity_provider # @return [::String] # Output only. An identity provider that reflects the `issuer` in the # workload identity pool. # @!attribute [rw] oidc_jwks # @return [::String] # Optional. OIDC verification keys for this Membership in JWKS format (RFC # 7517). # # When this field is set, OIDC discovery will NOT be performed on `issuer`, # and instead OIDC tokens will be validated using this field. class Authority include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # State of the Membership resource. # @!attribute [r] code # @return [::Google::Cloud::GkeHub::V1beta1::MembershipState::Code] # Output only. The current state of the Membership resource. # @!attribute [rw] description # @return [::String] # This field is never set by the Hub Service. # @!attribute [rw] update_time # @return [::Google::Protobuf::Timestamp] # This field is never set by the Hub Service. class MembershipState include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # Code describes the state of a Membership resource. module Code # The code is not set. CODE_UNSPECIFIED = 0 # The cluster is being registered. CREATING = 1 # The cluster is registered. READY = 2 # The cluster is being unregistered. DELETING = 3 # The Membership is being updated. UPDATING = 4 # The Membership is being updated by the Hub Service. SERVICE_UPDATING = 5 end end # Request message for `GkeHubMembershipService.ListMemberships` method. # @!attribute [rw] parent # @return [::String] # Required. The parent (project and location) where the Memberships will be # listed. Specified in the format `projects/*/locations/*`. # @!attribute [rw] page_size # @return [::Integer] # Optional. When requesting a 'page' of resources, `page_size` specifies # number of resources to return. If unspecified or set to 0, all resources # will be returned. # @!attribute [rw] page_token # @return [::String] # Optional. Token returned by previous call to `ListMemberships` which # specifies the position in the list from where to continue listing the # resources. # @!attribute [rw] filter # @return [::String] # Optional. Lists Memberships that match the filter expression, following the # syntax outlined in https://google.aip.dev/160. # # Examples: # # - Name is `bar` in project `foo-proj` and location `global`: # # name = "projects/foo-proj/locations/global/membership/bar" # # - Memberships that have a label called `foo`: # # labels.foo:* # # - Memberships that have a label called `foo` whose value is `bar`: # # labels.foo = bar # # - Memberships in the CREATING state: # # state = CREATING # @!attribute [rw] order_by # @return [::String] # Optional. One or more fields to compare and use to sort the output. # See https://google.aip.dev/132#ordering. class ListMembershipsRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Response message for the `GkeHubMembershipService.ListMemberships` method. # @!attribute [rw] resources # @return [::Array<::Google::Cloud::GkeHub::V1beta1::Membership>] # The list of matching Memberships. # @!attribute [rw] next_page_token # @return [::String] # A token to request the next page of resources from the # `ListMemberships` method. The value of an empty string means that # there are no more resources to return. # @!attribute [rw] unreachable # @return [::Array<::String>] # List of locations that could not be reached while fetching this list. class ListMembershipsResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for `GkeHubMembershipService.GetMembership` method. # @!attribute [rw] name # @return [::String] # Required. The Membership resource name in the format # `projects/*/locations/*/memberships/*`. class GetMembershipRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for the `GkeHubMembershipService.CreateMembership` method. # @!attribute [rw] parent # @return [::String] # Required. The parent (project and location) where the Memberships will be # created. Specified in the format `projects/*/locations/*`. # @!attribute [rw] membership_id # @return [::String] # Required. Client chosen ID for the membership. `membership_id` must be a # valid RFC 1123 compliant DNS label: # # 1. At most 63 characters in length # 2. It must consist of lower case alphanumeric characters or `-` # 3. It must start and end with an alphanumeric character # # Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, # with a maximum length of 63 characters. # @!attribute [rw] resource # @return [::Google::Cloud::GkeHub::V1beta1::Membership] # Required. The membership to create. # @!attribute [rw] request_id # @return [::String] # Optional. A request ID to identify requests. Specify a unique request ID # so that if you must retry your request, the server will know to ignore # the request if it has already been completed. The server will guarantee # that for at least 60 minutes after the first request. # # For example, consider a situation where you make an initial request and # the request times out. If you make the request again with the same request # ID, the server can check if original operation with the same request ID # was received, and if so, will ignore the second request. This prevents # clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is # not supported (00000000-0000-0000-0000-000000000000). class CreateMembershipRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for `GkeHubMembershipService.DeleteMembership` method. # @!attribute [rw] name # @return [::String] # Required. The Membership resource name in the format # `projects/*/locations/*/memberships/*`. # @!attribute [rw] request_id # @return [::String] # Optional. A request ID to identify requests. Specify a unique request ID # so that if you must retry your request, the server will know to ignore # the request if it has already been completed. The server will guarantee # that for at least 60 minutes after the first request. # # For example, consider a situation where you make an initial request and # the request times out. If you make the request again with the same request # ID, the server can check if original operation with the same request ID # was received, and if so, will ignore the second request. This prevents # clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is # not supported (00000000-0000-0000-0000-000000000000). class DeleteMembershipRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for `GkeHubMembershipService.UpdateMembership` method. # @!attribute [rw] name # @return [::String] # Required. The membership resource name in the format: # `projects/[project_id]/locations/global/memberships/[membership_id]` # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Required. Mask of fields to update. At least one field path must be # specified in this mask. # @!attribute [rw] resource # @return [::Google::Cloud::GkeHub::V1beta1::Membership] # Required. Only fields specified in update_mask are updated. # If you specify a field in the update_mask but don't specify its value here # that field will be deleted. # If you are updating a map field, set the value of a key to null or empty # string to delete the key from the map. It's not possible to update a key's # value to the empty string. # If you specify the update_mask to be a special path "*", fully replaces all # user-modifiable fields to match `resource`. # @!attribute [rw] request_id # @return [::String] # Optional. A request ID to identify requests. Specify a unique request ID # so that if you must retry your request, the server will know to ignore # the request if it has already been completed. The server will guarantee # that for at least 60 minutes after the first request. # # For example, consider a situation where you make an initial request and # the request times out. If you make the request again with the same request # ID, the server can check if original operation with the same request ID # was received, and if so, will ignore the second request. This prevents # clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is # not supported (00000000-0000-0000-0000-000000000000). class UpdateMembershipRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Request message for `GkeHubMembershipService.GenerateConnectManifest` # method. # . # @!attribute [rw] name # @return [::String] # Required. The Membership resource name the Agent will associate with, in # the format `projects/*/locations/*/memberships/*`. # @!attribute [rw] connect_agent # @return [::Google::Cloud::GkeHub::V1beta1::ConnectAgent] # Optional. The connect agent to generate manifest for. # @!attribute [rw] version # @return [::String] # Optional. The Connect agent version to use. Defaults to the most current # version. # @!attribute [rw] is_upgrade # @return [::Boolean] # Optional. If true, generate the resources for upgrade only. Some resources # generated only for installation (e.g. secrets) will be excluded. # @!attribute [rw] registry # @return [::String] # Optional. The registry to fetch the connect agent image from. Defaults to # gcr.io/gkeconnect. # @!attribute [rw] image_pull_secret_content # @return [::String] # Optional. The image pull secret content for the registry, if not public. class GenerateConnectManifestRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # GenerateConnectManifestResponse contains manifest information for # installing/upgrading a Connect agent. # @!attribute [rw] manifest # @return [::Array<::Google::Cloud::GkeHub::V1beta1::ConnectAgentResource>] # The ordered list of Kubernetes resources that need to be applied to the # cluster for GKE Connect agent installation/upgrade. class GenerateConnectManifestResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # ConnectAgentResource represents a Kubernetes resource manifest for Connect # Agent deployment. # @!attribute [rw] type # @return [::Google::Cloud::GkeHub::V1beta1::TypeMeta] # Kubernetes type of the resource. # @!attribute [rw] manifest # @return [::String] # YAML manifest of the resource. class ConnectAgentResource include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # TypeMeta is the type information needed for content unmarshalling of # Kubernetes resources in the manifest. # @!attribute [rw] kind # @return [::String] # Kind of the resource (e.g. Deployment). # @!attribute [rw] api_version # @return [::String] # APIVersion of the resource (e.g. v1). class TypeMeta include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The information required from end users to use GKE Connect. # @!attribute [rw] name # @return [::String] # Do not set. # @!attribute [rw] proxy # @return [::String] # Optional. URI of a proxy if connectivity from the agent to # gkeconnect.googleapis.com requires the use of a proxy. Format must be in # the form `http(s)://{proxy_address}`, depending on the HTTP/HTTPS protocol # supported by the proxy. This will direct the connect agent's outbound # traffic through a HTTP(S) proxy. # @!attribute [rw] namespace # @return [::String] # Optional. Namespace for GKE Connect agent resources. Defaults to # `gke-connect`. # # The Connect Agent is authorized automatically when run in the default # namespace. Otherwise, explicit authorization must be granted with an # additional IAM binding. class ConnectAgent include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request to validate the existing state of the membership CR in the # cluster. # @!attribute [rw] parent # @return [::String] # Required. The parent (project and location) where the Memberships will be # created. Specified in the format `projects/*/locations/*`. # @!attribute [rw] cr_manifest # @return [::String] # Optional. The YAML of the membership CR in the cluster. Empty if the # membership CR does not exist. # @!attribute [rw] intended_membership # @return [::String] # Required. The intended membership name under the `parent`. This method only # does validation in anticipation of a CreateMembership call with the same # name. class ValidateExclusivityRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The response of exclusivity artifacts validation result status. # @!attribute [rw] status # @return [::Google::Rpc::Status] # The validation result. # # * `OK` means that exclusivity is validated, assuming the manifest produced # by GenerateExclusivityManifest is successfully applied. # * `ALREADY_EXISTS` means that the Membership CRD is already owned by # another Hub. See `status.message` for more information. class ValidateExclusivityResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request to generate the manifests for exclusivity artifacts. # @!attribute [rw] name # @return [::String] # Required. The Membership resource name in the format # `projects/*/locations/*/memberships/*`. # @!attribute [rw] crd_manifest # @return [::String] # Optional. The YAML manifest of the membership CRD retrieved by # `kubectl get customresourcedefinitions membership`. # Leave empty if the resource does not exist. # @!attribute [rw] cr_manifest # @return [::String] # Optional. The YAML manifest of the membership CR retrieved by # `kubectl get memberships membership`. # Leave empty if the resource does not exist. class GenerateExclusivityManifestRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The response of the exclusivity artifacts manifests for the client to apply. # @!attribute [rw] crd_manifest # @return [::String] # The YAML manifest of the membership CRD to apply if a newer version of the # CRD is available. Empty if no update needs to be applied. # @!attribute [rw] cr_manifest # @return [::String] # The YAML manifest of the membership CR to apply if a new version of the # CR is available. Empty if no update needs to be applied. class GenerateExclusivityManifestResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents the metadata of the long-running operation. # @!attribute [r] create_time # @return [::Google::Protobuf::Timestamp] # Output only. The time the operation was created. # @!attribute [r] end_time # @return [::Google::Protobuf::Timestamp] # Output only. The time the operation finished running. # @!attribute [r] target # @return [::String] # Output only. Server-defined resource path for the target of the operation. # @!attribute [r] verb # @return [::String] # Output only. Name of the verb executed by the operation. # @!attribute [r] status_detail # @return [::String] # Output only. Human-readable status of the operation, if any. # @!attribute [r] cancel_requested # @return [::Boolean] # Output only. Identifies whether the user has requested cancellation # of the operation. Operations that have successfully been cancelled # have [Operation.error][] value with a # {::Google::Rpc::Status#code google.rpc.Status.code} of 1, corresponding to # `Code.CANCELLED`. # @!attribute [r] api_version # @return [::String] # Output only. API version used to start the operation. class OperationMetadata include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end end end end
49.890196
111
0.618404
edc9a1b6bbcfd0459ee8c15c042d1fc17f77e792
233
# frozen_string_literal: true require 'spec_helper' describe 'ufw::params' do on_supported_os.each do |os, os_facts| context "on #{os}" do let(:facts) { os_facts } it { is_expected.to compile } end end end
16.642857
40
0.656652
d56e86208e687443cd2f6954cf6b115f6ea423c2
3,811
=begin #Xero Payroll AU #This is the Xero Payroll API for orgs in Australia region. The version of the OpenAPI document: 2.3.7 Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.3.1 =end require 'spec_helper' require 'json' require 'date' # Unit tests for XeroRuby::PayrollAu::PayRun # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe 'PayRun' do before do # run before each test @instance = XeroRuby::PayrollAu::PayRun.new end after do # run after each test end describe 'test an instance of PayRun' do it 'should create an instance of PayRun' do expect(@instance).to be_instance_of(XeroRuby::PayrollAu::PayRun) end end describe 'test attribute "payroll_calendar_id"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pay_run_id"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pay_run_period_start_date"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pay_run_period_end_date"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "pay_run_status"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "payment_date"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "payslip_message"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "updated_date_utc"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "payslips"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "wages"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "deductions"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "tax"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "_super"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "reimbursement"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "net_pay"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "validation_errors"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
28.871212
102
0.71005
bfdfd0ee8340d891e45f2e9f3d093519f77e15e3
8,036
FactoryBot.define do sequence :email do |n| "test#{n}@example.com" end sequence :public_name do |n| "name#{n}" end sequence :conference_acronym do |n| "frabcon#{n}" end sequence :room_names do |n| "Room #{n}" end sequence :event_title do |n| "Introducing frap part #{n}" end trait :admin_role do role 'admin' end trait :crew_role do role 'crew' end trait :conference_orga_role do role 'orga' end trait :conference_coordinator_role do role 'coordinator' end trait :conference_reviewer_role do role 'reviewer' end trait :three_days do after :create do |conference| conference.days << create(:day, conference: conference, start_date: Date.today.since(1.days).since(11.hours), end_date: Date.today.since(1.days).since(23.hours)) conference.days << create(:day, conference: conference, start_date: Date.today.since(2.days).since(10.hours), end_date: Date.today.since(2.days).since(24.hours)) conference.days << create(:day, conference: conference, start_date: Date.today.since(3.days).since(10.hours), end_date: Date.today.since(3.days).since(17.hours)) end end trait :with_rooms do after :create do |conference| conference.rooms << create(:room, conference: conference) end end trait :with_events do after :create do |conference| conference.events << create(:event, conference: conference, room: conference.rooms.first, state: 'confirmed', public: true, start_time: Date.today.since(1.days).since(11.hours)) conference.events << create(:event, conference: conference, room: conference.rooms.first, state: 'confirmed', public: true, start_time: Date.today.since(2.days).since(15.hours)) conference.events << create(:event, conference: conference, room: conference.rooms.first, state: 'confirmed', public: true, start_time: Date.today.since(3.days).since(11.hours)) end end trait :with_speakers do after :create do |conference| conference.events.each do |event| speaker = create(:person) create(:event_person, event: event, person: speaker, event_role: 'speaker', role_state: 'confirmed') create(:availability, conference: conference, person: speaker) end end end trait :with_parent_conference do after :create do |conference| unless conference.subs.any? conference.parent = create(:three_day_conference_with_events, title: "#{conference.title} parent") end end end trait :with_sub_conference do after :create do |conference| if conference.main_conference? create(:conference, parent: conference, title: "#{conference.title} sub") end end end factory :user do person email { generate(:email) } password 'frab23' password_confirmation { password } sign_in_count 0 confirmed_at { Time.now } factory :admin_user, traits: [:admin_role] factory :crew_user, traits: [:crew_role] end factory :conference_user do conference after :build do |cu| user = build(:crew_user) user.conference_users << cu cu.user = user end factory :conference_orga, traits: [:conference_orga_role] factory :conference_coordinator, traits: [:conference_coordinator_role] factory :conference_reviewer, traits: [:conference_reviewer_role] end factory :conference_export do conference locale 'en' tarball { File.open(File.join(Rails.root, 'test', 'fixtures', 'tarball.tar.gz')) } end factory :person do first_name 'Fred' last_name 'Besen' email { generate(:email) } email_confirmation { email } public_name { generate(:public_name) } country_of_origin 'Spain' professional_background ['Developer'] gender 'Female' include_in_mailings true invitation_to_mattermost true end factory :attendee do person conference status 'invited' end factory :invited do person conference email { generate(:email) } end factory :expense do name 'Kiste Bier' value 22.5 person conference end factory :day do start_date { Date.today.since(1.days).since(11.hours) } end_date { Date.today.since(1.days).since(23.hours) } end factory :room do name { generate(:room_names) } end factory :conference do title 'FrabCon' acronym { generate(:conference_acronym) } timeslot_duration 15 default_timeslots 4 max_timeslots 20 feedback_enabled true expenses_enabled true transport_needs_enabled true schedule_public true timezone 'Berlin' parent nil factory :three_day_conference, traits: [:three_days, :with_sub_conference] factory :three_day_conference_with_events, traits: [:three_days, :with_rooms, :with_events, :with_sub_conference] factory :three_day_conference_with_events_and_speakers, traits: [:three_days, :with_rooms, :with_events, :with_sub_conference, :with_speakers] factory :sub_conference_with_events, traits: [:with_rooms, :with_events, :with_parent_conference] end factory :call_for_participation do start_date { Date.today.ago(1.days) } end_date { Date.today.since(6.days) } conference end factory :notification do reject_body 'reject body text' reject_subject 'rejected subject' accept_body 'accept body text' accept_subject 'accepted subject' schedule_body 'schedule body text' schedule_subject 'schedule subject' locale 'en' conference end factory :availability do conference person day { conference.days.first } start_date { conference.days.first.start_date.since(2.hours) } end_date { conference.days.first.start_date.since(3.hours) } end factory :language do code 'EN' factory :english_language do end factory :german_language do code 'DE' end end factory :event do title { generate(:event_title) } subtitle 'Getting started organizing your conference' time_slots 4 other_presenters "" start_time '10:00' description 'A description of a conference' conference { create(:three_day_conference) } iff_before ['2015'] public_type "Conferencers" desired_outcome "desired_outcome" phone_number 12345678 event_type "Workshop" projector true track group "group" recipient_travel_stipend "[email protected]" travel_support ["Hotel"] past_travel_assistance ["2017"] end factory :track do conference_id 3 name 'Name' created_at { Date.today.ago(1.days) } updated_at { Date.today.since(6.days) } color "fefd7f" end factory :event_person do person event event_role 'speaker' created_at { Date.today.ago(1.days) } updated_at { Date.today.since(6.days) } factory :confirmed_event_person do role_state 'confirmed' end end factory :event_rating do event person rating 3.0 comment 'blah' end factory :event_feedback do rating 3.0 comment 'doh' end factory :ticket do event remote_ticket_id '1234' end factory :mail_template do conference name 'template one' subject 'subject one' content '|first_name #first_name| |last_name #last_name| |public_name #public_name|' end end
26.876254
146
0.629791
6a0f3cbbc2bf6d35a41883bab62b2b6e09b46a03
816
Pod::Spec.new do |s| s.name = "Sora" s.version = "2021.2" s.summary = "Sora iOS SDK" s.description = <<-DESC A library to develop Sora client applications. DESC s.homepage = "https://github.com/shiguredo/sora-ios-sdk" s.license = { :type => "Apache License, Version 2.0" } s.authors = { "Shiguredo Inc." => "https://shiguredo.jp/" } s.platform = :ios, "12.1" s.source = { :git => "https://github.com/shiguredo/sora-ios-sdk.git", :tag => s.version } s.source_files = "Sora/**/*.swift" s.resources = ['Sora/*.xib'] s.dependency "WebRTC", '93.4577.8.0' s.dependency "Starscream", "4.0.4" s.pod_target_xcconfig = { 'ARCHS' => 'arm64', 'ARCHS[config=Debug]' => '$(ARCHS_STANDARD)' } end
32.64
66
0.547794
9188c4fd7813a2d48e5b3de2678dc12b854c85df
188
class CreateQuestions < ActiveRecord::Migration[6.0] def change create_table :questions do |t| t.text :content t.string :difficulty t.timestamps end end end
17.090909
52
0.664894
e874818c5c2399b773eacf5570547a4515ad6cb1
133
# frozen_string_literal: true class AddMetaCategory < ActiveRecord::Migration[4.2] def change # replaced by fixture end end
16.625
52
0.75188
08f7bfd140cc11f3f30a6583d81dd34b79f6433d
732
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false config.logger = Slf4jLogger.new ActiveRecord::Base.logger = config.logger
43.058824
82
0.777322
d5f45cc58c292d2e30453eea873f2270a2bc1342
768
Pod::Spec.new do |s| s.name = "STGTISensorTag" s.version = "1.0.3" s.ios.deployment_target = '9.0' s.tvos.deployment_target = '9.0' s.summary = "iOS framework to interface with the TI Sensor Tag" s.description = "By adding the STGTISensorTag framework to your iOS app you will be able to enable, configure, read and disable the various sensors on the TI Sensor Tag" s.homepage = "https://github.com/AndreMuis/STGTISensorTag" s.license = { :type => "MIT", :file => "LICENSE" } s.author = "AndreMuis" s.source = { :git => "https://github.com/AndreMuis/STGTISensorTag.git", :tag => "1.0.3" } s.source_files = "STGTISensorTag/**/*.{swift}" s.framework = "CoreBluetooth" end
51.2
175
0.619792
1a24871b157ba675e5635014732fdf1fdee75936
40
module JekyllCsvy VERSION = "0.4" end
10
17
0.7
1cfe98f1774cb9416a229bacb797bd3f6f708cbc
476
class Feature < ActiveRecord::Base include PgSearch multisearchable :against => [:title] belongs_to :page belongs_to :primary_asset, :class_name => 'Asset' belongs_to :secondary_asset, :class_name => 'Asset' positioned :page_id track_user_edits validations_from_schema # Returns the options required for generating a URL to this model. This is # currently used with searches. # # @return Hash def searchable_url_opts [page, self] end end
21.636364
76
0.731092
267436e2d2c7e1fc4370d1e0cc50f39d37ab7469
487
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= KIT_APP_PATHS['GEMFILE'] require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) if KIT_APP_PATHS['GEM_LIB'] $LOAD_PATH.unshift KIT_APP_PATHS['GEM_LIB'] end if KIT_APP_PATHS['GEM_APP'] $LOAD_PATH.unshift KIT_APP_PATHS['GEM_APP'] end if KIT_APP_PATHS['GEM_SPEC_LIB'] $LOAD_PATH.unshift KIT_APP_PATHS['GEM_SPEC_LIB'] end if KIT_APP_PATHS['GEM_SPEC_APP'] $LOAD_PATH.unshift KIT_APP_PATHS['GEM_SPEC_APP'] end
23.190476
61
0.770021
91306ad3437a7ce2e2f0b0f07fcd0f0428c79476
797
# sbJson 1 writer tests - browse categories # History: # Stan Smith 2017-05-31 original script require 'minitest/autorun' require 'json' require 'adiwg-mdtranslator' require_relative 'sbjson_test_parent' class TestWriterSbJsonBrowseCategory < TestWriterSbJsonParent # get input JSON for test @@jsonIn = TestWriterSbJsonParent.getJson('browseCategory.json') def test_browseCategories metadata = ADIWG::Mdtranslator.translate( file: @@jsonIn, reader: 'mdJson', validate: 'normal', writer: 'sbJson', showAllTags: false) expect = ['Data', 'Document', 'Collection', 'Project', 'Image', 'Report', 'Physical Item'] hJsonOut = JSON.parse(metadata[:writerOutput]) got = hJsonOut['browseCategories'] assert_equal expect, got end end
23.441176
96
0.706399
e9614db1d638287408e20ce7427152702f72658e
197
class CreateGames < ActiveRecord::Migration[5.0] def change create_table :games do |t| t.string :state t.references :user, foreign_key: true t.timestamps end end end
17.909091
48
0.659898
e980e6d43a0a584c535d62a0e19f1c9e895ba8ae
398
FactoryBot.define do factory :user, class: "Platforms::User" do name { "Joe Bloggs" } platform_id { "10" } thumbnail_url { "http://mypic" } web_url { "http://myprofile" } email { "[email protected]" } admin { false } association :platforms_network, factory: :network trait :alternate do platform_id { "11" } end end end
23.411765
53
0.562814
331740f740ef15e04777ed0653000a48c7215136
1,309
module Courses class ValidateCustomAgeRangeService def execute(age_range_in_years, course) error_message = "#{age_range_in_years} is invalid. You must enter a valid age range." valid_age_range_regex = Regexp.new(/^(?<from>\d{1,2})_to_(?<to>\d{1,2})$/) if valid_age_range_regex.match(age_range_in_years) from_age = get_ages(age_range_in_years, valid_age_range_regex)["from"] to_age = get_ages(age_range_in_years, valid_age_range_regex)["to"] if from_age_invalid?(from_age) course.errors.add(:age_range_in_years, error_message) elsif to_age_invalid?(to_age) course.errors.add(:age_range_in_years, error_message) elsif to_age - from_age < 4 course.errors.add(:age_range_in_years, "#{age_range_in_years} is invalid. Your age range must cover at least 4 years.") end else course.errors.add(:age_range_in_years, error_message) end end private def get_ages(age_range_in_years, valid_age_range_regex) valid_age_range_regex.match(age_range_in_years)&.named_captures&.transform_values { |year| year.to_i } end def from_age_invalid?(from_age) from_age < 3 || from_age > 15 end def to_age_invalid?(to_age) to_age < 7 || to_age > 19 end end end
35.378378
129
0.695951
f84115528e09b2560be3ea479870b10367ced470
1,601
class User < ApplicationRecord attr_accessor :remember_token, :activation_token before_save :downcase_email before_create :create_activation_digest validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+\.*[a-z\d]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 }, allow_nil: true def self.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def self.new_token SecureRandom.urlsafe_base64 end def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end def forget update_attribute(:remember_digest, nil) end def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end def activate update_columns(activated: true, activated_at: Time.zone.now) end def send_activation_email UserMailer.account_activation(self).deliver_now end private def downcase_email self.email.downcase! end def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end end
26.245902
78
0.689569
7a0dac54ac1f06e5926540e36b8ff8f80186cf36
4,775
# encoding: utf-8 require "logstash/codecs/base" class LogStash::Codecs::Ansi < LogStash::Codecs::Base config_name "ansi" config :columns, :validate => :number, :default => 0 config :indent, :validate => :number, :default => 4 config :fields, :validate => :array, :default => ["message"] config :highlighters, :validate => :array public def register @colors = { "Black" => "0", "Red" => "1", "Green" => "2", "Yellow" => "3", "Blue" => "4", "Magenta" => "5", "Cyan" => "6", "White" => "7", "Default" => "9" } if @columns <= 0 then @columns = detect_terminal_width if @columns <= 0 then @columns = 80 end end @lineIndent = "" while @lineIndent.length <= @indent do @lineIndent << " " end @highlighters.each do |highlighter| highlighter["pattern"] = Regexp.new highlighter["match"] end @fields.each do |definition| if definition["highlighters"] then definition["highlighters"].each do |highlighter| highlighter["pattern"] = Regexp.new highlighter["match"] highlighter["replacement"] = "" set_highlighter highlighter["replacement"], highlighter highlighter["replacement"] << '\0' end end end end # def register public def decode(data) raise "Not implemented" end # def decode public def encode(event) line_highlighter = { "background" => "Default", "foreground" => "Default", "bold" => "false" } message = "" @highlighters.each do |highlighter| value = event[highlighter["field"]] if value =~ highlighter["pattern"] then line_highlighter = highlighter break end end set_highlighter message, line_highlighter # Render fields isFirst = true @fields.each do |definition| if !isFirst then message << " " else isFirst = false end value = event[definition["field"]] if definition["formatter"] then value = (value.instance_eval definition["formatter"]) end if definition["highlighters"] then definition["highlighters"].each do |highlighter| replacement = highlighter["replacement"] set_highlighter replacement, line_highlighter value = value.gsub highlighter["pattern"], replacement end end message << value.to_s set_highlighter message, line_highlighter end # Wrap and indent lines currentIndex = 0 cnt = 0 wrap_index = 0 while currentIndex < message.length do if cnt == @columns then if currentIndex - wrap_index > @columns / 2 then message.insert currentIndex, @lineIndent cnt = @lineIndent.length else message.insert wrap_index, "\n" message.insert wrap_index + 1, @lineIndent cnt = @lineIndent.length + (currentIndex - wrap_index) end currentIndex += @lineIndent.length wrap_index = 0 end chr = message[currentIndex] if chr == " " || chr == "_" then wrap_index = currentIndex + 1 end if chr == "\r" then # ignore elsif chr == "\n" then message.insert currentIndex + 1, @lineIndent currentIndex += @lineIndent.length + 1 cnt = @lineIndent.length + 1 elsif chr == "\x1B" then while currentIndex < message.length do chr = message[currentIndex] if chr == "m" then break end currentIndex += 1 end else cnt += 1 end currentIndex += 1 end if cnt < @columns then message << "\n" end # Publish message @on_event.call(event, message) end # def encode def set_highlighter(message, highlighter) message << "\x1B[" if highlighter["bold"] == "true" then message << "1" else message << "0" end if highlighter["foreground"] then message << ";3" message << @colors[highlighter["foreground"]] end if highlighter["background"] then message << ";4" message << @colors[highlighter["background"]] end message << "m" end def detect_terminal_width if (ENV['COLUMNS'] =~ /^\d+$/) then return ENV['COLUMNS'].to_i end conResult = `mode con`.scan(/Columns:\s*(\d+)/) if conResult.length > 0 then width = conResult[0][0].to_i if width > 0 then return width end end width = `tput cols`.to_i if width > 0 then return width end width = (`stty size`.scan(/\d+/).map { |s| s.to_i }.reverse)[0] return width rescue return 0 end end # class LogStash::Codecs::Dots
23.522167
98
0.573194
62f74bc611a2f618b0736dc16349426f61bc9783
4,659
require 'rails_helper' require 'sorbet-runtime' require 'sorbet-rails/sorbet_utils' module SorbetUtilsExampleModule end class SorbetUtilsExampleClass extend T::Sig sig { void } def no_param_method; end sig { params(p1: String, p2: T.class_of(String)).void } def method_req_args(p1, p2); end sig { params(p1: T.any(String, Integer), p2: T.nilable(String)).void } def method_req_kwarg(p1:, p2:); end sig { params(p1: SorbetUtilsExampleModule, p2: T.nilable(T.any(String, Integer))).void } def method_mixed(p1, p2:); end sig { params(p1: T::Hash[String, T.untyped], p2: Integer).void } def method_with_rest(p1, *p2); end sig { params(p1: T::Array[String], p2: T::Set[Integer], p3: Integer).void } def method_with_keyrest(p1, p2:, **p3); end sig { params(p1: String, p2: T.proc.params(p3: T.class_of(String)).void).void } def method_with_block(*p1, &p2); end sig { params(p1: T.proc.params(p3: T.class_of(String)).returns(T.nilable(String))).void } def method_with_block_return(&p1); end def method_without_sig(p1, p2, *p3, p4:, **p5, &p6); end end RSpec.describe SorbetRails::SorbetUtils do Parameter = ::Parlour::RbiGenerator::Parameter it 'works with no_param_method' do method_def = SorbetUtilsExampleClass.instance_method(:no_param_method) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([]) end it 'works with method_req_args' do method_def = SorbetUtilsExampleClass.instance_method(:method_req_args) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new('p1', type: 'String'), Parameter.new('p2', type: 'T.class_of(String)'), ]) end it 'works with method_req_kwarg' do method_def = SorbetUtilsExampleClass.instance_method(:method_req_kwarg) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new('p1', type: 'T.any(Integer, String)'), # sorbet re-order the types Parameter.new('p2', type: 'T.nilable(String)'), ]) end it 'works with method_mixed' do method_def = SorbetUtilsExampleClass.instance_method(:method_mixed) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new('p1', type: 'SorbetUtilsExampleModule'), Parameter.new('p2', type: 'T.nilable(T.any(Integer, String))'), ]) end it 'works with method_with_rest' do method_def = SorbetUtilsExampleClass.instance_method(:method_with_rest) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new('p1', type: 'T::Hash[String, T.untyped]'), Parameter.new('*p2', type: 'Integer'), ]) end it 'works with method_with_keyrest' do method_def = SorbetUtilsExampleClass.instance_method(:method_with_keyrest) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new('p1', type: 'T::Array[String]'), Parameter.new('p2', type: 'T::Set[Integer]'), Parameter.new('**p3', type: 'Integer'), ]) end it 'works with method_with_block' do method_def = SorbetUtilsExampleClass.instance_method(:method_with_block) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new('*p1', type: 'String'), Parameter.new('&p2', type: 'T.proc.params(p3: T.class_of(String)).void'), ]) end it 'works with method_with_block_return' do method_def = SorbetUtilsExampleClass.instance_method(:method_with_block_return) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) expect(parameters).to match_array([ Parameter.new( '&p1', type: 'T.proc.params(p3: T.class_of(String)).returns(T.nilable(String))', ), ]) end it 'works with method_without_sig' do method_def = SorbetUtilsExampleClass.instance_method(:method_without_sig) parameters = SorbetRails::SorbetUtils.parameters_from_method_def(method_def) # method_without_sig(p1, p2, *p3, p4:, **p5, &p6); end expect(parameters).to match_array([ Parameter.new('p1', type: 'T.untyped'), Parameter.new('p2', type: 'T.untyped'), Parameter.new('*p3', type: 'T.untyped'), Parameter.new('p4', type: 'T.untyped'), Parameter.new('**p5', type: 'T.untyped'), Parameter.new('&p6', type: 'T.untyped'), ]) end end
36.97619
91
0.707233
bb57e52b207ecfdd97ae15ed70547130a04a8b50
10,014
class Admin::CustomFieldsController < Admin::AdminBaseController before_action :field_type_is_valid, :only => [:new, :create] CHECKBOX_TO_BOOLEAN = ->(v) { if v == false || v == true v elsif v == "1" true else false end } HASH_VALUES = ->(v) { if v.is_a?(Array) v elsif v.is_a?(Hash) v.values elsif v == nil nil else raise ArgumentError.new("Illegal argument given to transformer: #{v.to_inspect}") end } CategoryAttributeSpec = EntityUtils.define_builder( [:category_id, :fixnum, :to_integer, :mandatory] ) OptionAttribute = EntityUtils.define_builder( [:id, :mandatory], [:sort_priority, :fixnum, :to_integer, :mandatory], [:title_attributes, :hash, :to_hash, :mandatory] ) CUSTOM_FIELD_SPEC = [ [:name_attributes, :hash, :mandatory], [:category_attributes, collection: CategoryAttributeSpec], [:sort_priority, :fixnum, :optional], [:required, :bool, :optional, default: false, transform_with: CHECKBOX_TO_BOOLEAN], [:search_filter, :bool, :optional, default: false, transform_with: CHECKBOX_TO_BOOLEAN] ] TextFieldSpec = [ [:search_filter, :bool, const_value: false] ] + CUSTOM_FIELD_SPEC NumericFieldSpec = [ [:min, :mandatory], [:max, :mandatory], [:allow_decimals, :bool, :mandatory, transform_with: CHECKBOX_TO_BOOLEAN], [:search_filter, :bool, :optional, default: false, transform_with: CHECKBOX_TO_BOOLEAN] ] + CUSTOM_FIELD_SPEC DropdownFieldSpec = [ [:option_attributes, :mandatory, transform_with: HASH_VALUES, collection: OptionAttribute], [:search_filter, :bool, :optional, default: false, transform_with: CHECKBOX_TO_BOOLEAN], ] + CUSTOM_FIELD_SPEC CheckboxFieldSpec = [ [:option_attributes, :mandatory, transform_with: HASH_VALUES, collection: OptionAttribute], [:search_filter, :bool, :optional, default: false, transform_with: CHECKBOX_TO_BOOLEAN] ] + CUSTOM_FIELD_SPEC DateFieldSpec = [ [:search_filter, :bool, const_value: false] ] + CUSTOM_FIELD_SPEC TextFieldEntity = EntityUtils.define_builder(*TextFieldSpec) NumericFieldEntity = EntityUtils.define_builder(*NumericFieldSpec) DropdownFieldEntity = EntityUtils.define_builder(*DropdownFieldSpec) CheckboxFieldEntity = EntityUtils.define_builder(*CheckboxFieldSpec) DateFieldEntity = EntityUtils.define_builder(*DateFieldSpec) def index @selected_left_navi_link = "listing_fields" @community = @current_community @custom_fields = @current_community.custom_fields shapes = @current_community.shapes price_in_use = shapes.any? { |s| s[:price_enabled] } make_onboarding_popup render locals: { show_price_filter: price_in_use } end def new @selected_left_navi_link = "listing_fields" @community = @current_community @custom_field = params[:field_type].constantize.new #before filter checks valid field types and prevents code injection if params[:field_type] == "CheckboxField" @min_option_count = 1 @custom_field.options = [CustomFieldOption.new(sort_priority: 1)] else @min_option_count = 2 @custom_field.options = [CustomFieldOption.new(sort_priority: 1), CustomFieldOption.new(sort_priority: 2)] end end def create @selected_left_navi_link = "listing_fields" @community = @current_community # Hack for comma/dot issue. Consider creating an app-wide comma/dot handling mechanism params[:custom_field][:min] = ParamsService.parse_float(params[:custom_field][:min]) if params[:custom_field][:min].present? params[:custom_field][:max] = ParamsService.parse_float(params[:custom_field][:max]) if params[:custom_field][:max].present? custom_field_entity = build_custom_field_entity(params[:field_type], params[:custom_field]) @custom_field = params[:field_type].constantize.new(custom_field_entity) #before filter checks valid field types and prevents code injection @custom_field.entity_type = :for_listing @custom_field.community = @current_community success = if valid_categories?(@current_community, params[:custom_field][:category_attributes]) @custom_field.save else false end if success # Onboarding wizard step recording state_changed = Admin::OnboardingWizard.new(@current_community.id) .update_from_event(:custom_field_created, @custom_field) if state_changed record_event(flash, "km_record", {km_event: "Onboarding filter created"}) flash[:show_onboarding_popup] = true end redirect_to admin_custom_fields_path else flash[:error] = "Listing field saving failed" render :new end end def build_custom_field_entity(type, params) params = params.respond_to?(:to_unsafe_hash) ? params.to_unsafe_hash : params case type when "TextField" TextFieldEntity.call(params) when "NumericField" NumericFieldEntity.call(params) when "DropdownField" DropdownFieldEntity.call(params) when "CheckboxField" CheckboxFieldEntity.call(params) when "DateField" DateFieldEntity.call(params) end end def edit @selected_tribe_navi_tab = "admin" @selected_left_navi_link = "listing_fields" @community = @current_community if params[:field_type] == "CheckboxField" @min_option_count = 1 else @min_option_count = 2 end @custom_field = @current_community.custom_fields.find(params[:id]) end def update @custom_field = @current_community.custom_fields.find(params[:id]) # Hack for comma/dot issue. Consider creating an app-wide comma/dot handling mechanism params[:custom_field][:min] = ParamsService.parse_float(params[:custom_field][:min]) if params[:custom_field][:min].present? params[:custom_field][:max] = ParamsService.parse_float(params[:custom_field][:max]) if params[:custom_field][:max].present? custom_field_params = params[:custom_field].merge( sort_priority: @custom_field.sort_priority ) custom_field_entity = build_custom_field_entity(@custom_field.type, custom_field_params) @custom_field.update_attributes(custom_field_entity) redirect_to admin_custom_fields_path end def edit_price @selected_tribe_navi_tab = "admin" @selected_left_navi_link = "listing_fields" @community = @current_community end def edit_location @selected_tribe_navi_tab = "admin" @selected_left_navi_link = "listing_fields" @community = @current_community end def edit_expiration @selected_tribe_navi_tab = "admin" @selected_left_navi_link = "listing_fields" @community = @current_community render_expiration_form(listing_expiration_enabled: !@current_community.hide_expiration_date) end def update_price # To cents params[:community][:price_filter_min] = MoneyUtil.parse_str_to_money(params[:community][:price_filter_min], @current_community.currency).cents if params[:community][:price_filter_min] params[:community][:price_filter_max] = MoneyUtil.parse_str_to_money(params[:community][:price_filter_max], @current_community.currency).cents if params[:community][:price_filter_max] price_params = params.require(:community).permit( :show_price_filter, :price_filter_min, :price_filter_max ) success = @current_community.update_attributes(price_params) if success redirect_to admin_custom_fields_path else flash[:error] = "Price field editing failed" render :action => :edit_price end end def update_location location_params = params.require(:community).permit(:listing_location_required) success = @current_community.update_attributes(location_params) if success redirect_to admin_custom_fields_path else flash[:error] = "Location field editing failed" render :action => :edit_location end end def update_expiration listing_expiration_enabled = params[:listing_expiration_enabled] == "enabled" success = @current_community.update_attributes( { hide_expiration_date: !listing_expiration_enabled }) if success redirect_to admin_custom_fields_path else flash[:error] = "Expiration field editing failed" render_expiration_form(listing_expiration_enabled: !@current_community.hide_expiration_date) end end def render_expiration_form(listing_expiration_enabled:) render :edit_expiration, locals: { listing_expiration_enabled: listing_expiration_enabled } end def destroy @custom_field = CustomField.find(params[:id]) success = if custom_field_belongs_to_community?(@custom_field, @current_community) @custom_field.destroy end flash[:error] = "Field doesn't belong to current community" unless success redirect_to admin_custom_fields_path end def order sort_priorities = params[:order].each_with_index.map do |custom_field_id, index| [custom_field_id, index] end.inject({}) do |hash, ids| custom_field_id, sort_priority = ids hash.merge(custom_field_id.to_i => sort_priority) end @current_community.custom_fields.each do |custom_field| custom_field.update_attributes(:sort_priority => sort_priorities[custom_field.id]) end render body: nil, status: 200 end private # Return `true` if all the category id's belong to `community` def valid_categories?(community, category_attributes) is_community_category = category_attributes.map do |category| community.categories.any? { |community_category| community_category.id == category[:category_id].to_i } end is_community_category.all? end def custom_field_belongs_to_community?(custom_field, community) community.custom_fields.include?(custom_field) end private def field_type_is_valid redirect_to admin_custom_fields_path unless CustomField::VALID_TYPES.include?(params[:field_type]) end end
32.407767
187
0.72828
bb7be5f7f100f1403af55e53ef28ad7f8b59f8f6
1,827
require 'rack' require 'kramdown' require 'erb' require 'pathname' module GrantFront class Engine attr_accessor :request, :tree def call(env) @request = Rack::Request.new(env) status = 200 headers = {'Content-Type' => 'text/html'} body = ERB.new(application_template).result(binding) [status, headers, [body]] end private def policy_link_to "<a href=#{request.script_name}>Policy</a>" end def policies_tag raw = "" policies = GrantFront::Policy.all(rake: false) raw += "<div><ul>" raw += policies.map do |policy| raw = "<li" if '/' + policy.urn == request.path_info raw += " class='active'" end raw += "><a href=#{request.script_name}/#{policy.urn}>#{policy.name}</a>" raw += "</li>" end.join("\n") raw += "</ul></div>" raw end def policy_tag policies = GrantFront::Policy.all(rake: false) classes = policies.inject([]) do |arr, policy| arr << policy.klass if '/' + policy.urn == request.path_info arr end classes = nil if classes.count == 0 text = Diagram.new(rake: false, classes: classes).create Kramdown::Document.new(text).to_html end def application_template root_path = Pathname.new(File.expand_path('..', File.dirname(__FILE__))) templates_path = File.join(root_path, 'templates') application_layout = File.expand_path('application.html.erb', File.join(templates_path, 'layouts')) File.read(application_layout) end # end private class << self def prototype @prototype ||= new end def call(env) prototype.call(env) end end end end
24.689189
107
0.56705
1a6f2447be8002f0cb68132565ea4ce0e6c55c26
891
# frozen_string_literal: true require_relative 'test_helper' class TestHeLocale < Test::Unit::TestCase def setup Faker::Config.locale = 'he' end def teardown Faker::Config.locale = nil end def test_he_address_methods assert Faker::Address.city_prefix.is_a? String assert Faker::Address.city.is_a? String assert Faker::Address.street_prefix.is_a? String assert Faker::Address.building_number.is_a? String assert Faker::Address.street_name.is_a? String assert Faker::Address.street_address.is_a? String assert Faker::Address.default_country.is_a? String assert_equal('ישראל', Faker::Address.default_country) end def test_he_name_methods assert Faker::Name.first_name.is_a? String assert Faker::Name.last_name.is_a? String assert Faker::Name.name_with_middle.is_a? String assert Faker::Name.name.is_a? String end end
27.84375
57
0.750842
87b1f95a6bea8ee60d7aa4370826c5fabe744f8b
949
# The Book of Ruby - http://www.sapphiresteel.com puts( "Main thread: #{Thread.main.inspect}" ) puts( Thread.new{ }.inspect ) puts( Thread.new{ sleep }.kill.inspect ) puts( Thread.new{ sleep }.inspect ) puts( Thread.new{ Thread.stop }.inspect ) puts( Thread.new{ for i in (1..100) do i += 1 end }.inspect ) puts( "Main thread: #{Thread.main.inspect}" ) puts( "\n--- Compare Thread status and Thread inspect ---" ) thread1 = Thread.new{ } puts( "thread1.status: #{thread1.status}, thread1.inspect #{thread1.inspect}" ) thread2 = Thread.new{ raise( "Exception raised!" ) } puts( "thread2.status: #{thread2.status.inspect}, thread2.inspect #{thread2.inspect}" ) # NOTE: critical is only available in Ruby 1.8 or earlier Thread.critical = true # prohibits scheduling of any existing thread (e.g by sleep) thread3 = Thread.new{ sleep }.kill puts( "thread3.status: #{thread3.status}, thread3.inspect #{thread3.inspect}" )
35.148148
87
0.680717
7a60524c9095a272bb4834bdc34f6dc53a261819
1,766
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `rails # db:schema:load`. When creating a new database, `rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_03_02_120535) do create_table "microposts", force: :cascade do |t| t.text "content" t.integer "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "picture" t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at" t.index ["user_id"], name: "index_microposts_on_user_id" end create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "password_digest" t.string "remember_digest" t.boolean "admin" t.string "activation_digest" t.boolean "activated", default: false t.datetime "activated_at" t.string "reset_digest" t.datetime "reset_sent_at" t.index ["email"], name: "index_users_on_email", unique: true end add_foreign_key "microposts", "users" add_foreign_key "microposts", "users" end
40.136364
89
0.735561
d536a9439be46de88eab13fd352a6f13e324b99b
3,065
############################################################################### # Copyright (c) 2017 Cisco and/or its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### # # See README-develop-beaker-scripts.md (Section: Test Script Variable Reference) # for information regarding: # - test script general prequisites # - command return codes # - A description of the 'tests' hash and its usage # ############################################################################### require File.expand_path('../../lib/utilitylib.rb', __FILE__) # Test hash top-level keys tests = { master: master, agent: agent, platform: 'n(3|7|9)k', resource_name: 'cisco_object_group_entry', } # Skip -ALL- tests if a top-level platform/os key exludes this platform skip_unless_supported(tests) tests[:seq_10_v4] = { title_pattern: 'ipv4 address beaker 10', manifest_props: { address: '1.2.3.4 2.3.4.5' }, } tests[:seq_10_v6] = { desc: 'IPv6 Seq 10', title_pattern: 'ipv6 address beaker6 10', manifest_props: { address: '1:1::1/64' }, } tests[:seq_20_v4] = { title_pattern: 'ipv4 port beakerp 20', manifest_props: { port: 'eq 40' }, } tests[:seq_30_v4] = { desc: 'IPv4 Seq 30', title_pattern: 'ipv4 port beakerp 30', manifest_props: { port: 'range 300 550' }, } def dependency_manifest(_tests, _id) " cisco_object_group { 'ipv4 address beaker': ensure => present, } cisco_object_group { 'ipv6 address beaker6': ensure => present, } cisco_object_group { 'ipv4 port beakerp': ensure => present, } " end def cleanup logger.info('Testcase Cleanup:') resource_absent_cleanup(agent, 'cisco_object_group_entry') resource_absent_cleanup(agent, 'cisco_object_group') end ################################################################# # TEST CASE EXECUTION ################################################################# test_name "TestCase :: #{tests[:resource_name]}" do cleanup teardown { cleanup } # --------------------------------------------------------- logger.info("\n#{'-' * 60}\nSection 1. ObjectGroup Testing") test_harness_run(tests, :seq_10_v4) test_harness_run(tests, :seq_10_v6) test_harness_run(tests, :seq_20_v4) test_harness_run(tests, :seq_30_v4) # --------------------------------------------------------- skipped_tests_summary(tests) end logger.info("TestCase :: #{tests[:resource_name]} :: End")
28.37963
80
0.579772
e22ae07a77401ce7edede5aca955012a8fc8af72
1,533
require 'spec_helper' describe Saml::Elements::Conditions do let(:conditions) { build(:conditions) } describe "Optional fields" do [:not_before, :not_on_or_after, :audience_restriction].each do |field| it "should have the #{field} field" do conditions.should respond_to(field) end it "should allow #{field} to blank" do conditions.send("#{field}=", nil) conditions.should be_valid conditions.send("#{field}=", "") conditions.should be_valid end end end describe "parse" do let(:conditions_xml) { File.read(File.join('spec','fixtures','artifact_response.xml')) } let(:conditions) { Saml::Elements::Conditions.parse(conditions_xml, :single => true) } it "should parse the StatusCode" do conditions.should be_a(Saml::Elements::Conditions) end it "should parse the not on or after attribute" do conditions.not_on_or_after.should == Time.parse("2011-08-31T08:51:05Z") end it "should parse the not before attribute" do conditions.not_before.should == Time.parse("2011-08-31T08:51:05Z") end it "should parse the AudienceRestriction" do conditions.audience_restriction.should be_a(Saml::Elements::AudienceRestriction) end end describe "initialize" do it "should set the audience restriction if audience is present" do condition = Saml::Elements::Conditions.new(:audience => "audience") condition.audience_restriction.audience.should == "audience" end end end
29.480769
92
0.682975
1c1b064a0a03322433d237e5192a6b028bfafe5e
104
class Status < ActiveRecord::Base has_many :tickets attr_accessible :name acts_as_paranoid end
17.333333
33
0.769231
edac88af498c461e0f05b55e1246455afb0ea8c5
190
# frozen_string_literal: true class WelcomeMailer < CustomMailer def welcome_email(user) @user = user mail(to: @user.email, subject: 'Babywearing Account Registration') end end
21.111111
70
0.742105
ff8c0bdae2e289a58f3f5e7d9687c47e472f455a
496
require 'spec_helper' require 'tempfile' describe Kommando do it 'has a version number' do expect(Kommando::VERSION).not_to be nil end describe 'initialization' do it 'requires cmd as an argument' do k = Kommando.new "uptime" expect(k).to be_an_instance_of(Kommando) end it 'accepts additional options as the second argument' do k = Kommando.new "uptime", { output: true } expect(k).to be_an_instance_of(Kommando) end end end
20.666667
61
0.667339
082bbe0d9d11f04ba7cd17ad4b3f199cbbebf963
924
################################## ##### SET THESE VARIABLES ######## ################################## server "epsilon.jumpstart.ge", :web, :app, :db, primary: true # server where app is located # server "parlvote.jumpstart.ge", :web, :app, :db, primary: true # server where app is located set :application, "Voting-Records" # unique name of application set :user, "vrd"# name of user on server # set :user, "zura"# name of user on server set :ngnix_conf_file_loc, "production/nginx.conf" # location of nginx conf file set :unicorn_init_file_loc, "production/unicorn_init.sh" # location of unicor init shell file set :github_account_name, "JumpStartGeorgia" # name of accout on git hub set :github_repo_name, "Parliament-Voting" # name of git hub repo set :git_branch_name, "master" # name of branch to deploy set :rails_env, "production" # name of environment: production, staging, ... ##################################
57.75
94
0.656926
5dc0f55db880bb12f4ec1f155ab1a8fbe002dcfa
1,241
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'query Jira service' do include GraphqlHelpers let_it_be(:current_user) { create(:user) } let_it_be(:project) { create(:project) } let_it_be(:jira_integration) { create(:jira_integration, project: project) } let_it_be(:bugzilla_integration) { create(:bugzilla_integration, project: project) } let_it_be(:redmine_integration) { create(:redmine_integration, project: project) } let(:query) do %( query { project(fullPath: "#{project.full_path}") { services { nodes { type active } } } } ) end let(:services) { graphql_data.dig('project', 'services', 'nodes')} it_behaves_like 'unauthorized users cannot read services' context 'when user can access project services' do before do project.add_maintainer(current_user) post_graphql(query, current_user: current_user) end it_behaves_like 'a working graphql query' it 'retuns list of jira imports' do service_types = services.map { |s| s['type'] } expect(service_types).to match_array(%w(BugzillaService JiraService RedmineService)) end end end
25.854167
90
0.660757
bbd1c5c4d6b8e098349365525f7ef5d34b3c58ba
4,170
#!/usr/bin/env ruby require "sinatra" require "open3" if ARGV[0] == "onboot" File.open("/etc/init/dokku-installer.conf", "w") do |f| f.puts "start on runlevel [2345]" f.puts "exec #{File.absolute_path(__FILE__)} selfdestruct" end File.open("/etc/nginx/conf.d/dokku-installer.conf", "w") do |f| f.puts "upstream dokku-installer { server 127.0.0.1:2000; }" f.puts "server {" f.puts " listen 80;" f.puts " location / {" f.puts " proxy_pass http://dokku-installer;" f.puts " }" f.puts "}" end puts "Installed Upstart service and default Nginx virtualhost for installer to run on boot." exit end version = "v0.2.0" dokku_root = ENV["DOKKU_ROOT"] || "/home/dokku" admin_key = `cat /root/.ssh/authorized_keys`.split("\n").first hostname = `bash -c '[[ $(dig +short $HOSTNAME) ]] && echo $HOSTNAME || curl icanhazip.com'`.strip template = DATA.read set :port, 2000 set :environment, :production disable :protection get "/" do ERB.new(template).result binding end post "/setup" do if params[:vhost] == "true" File.open("#{dokku_root}/VHOST", "w") {|f| f.write params[:hostname] } else `rm #{dokku_root}/VHOST` end File.open("#{dokku_root}/HOSTNAME", "w") {|f| f.write params[:hostname] } Open3.capture2("sshcommand acl-add dokku admin", :stdin_data => params[:key]) Thread.new { `rm /etc/nginx/conf.d/dokku-installer.conf && /etc/init.d/nginx stop && /etc/init.d/nginx start` `rm /etc/init/dokku-installer.conf && stop dokku-installer` }.run if ARGV[0] == "selfdestruct" end __END__ <html> <head> <title>Dokku Setup</title> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div class="container" style="width: 640px;"> <form id="form" role="form"> <h1>Dokku Setup <small><%= version %></small></h1> <div class="form-group"> <h3><small style="text-transform: uppercase;">Admin Access</small></h3> <label for="key">Public Key</label><br /> <textarea class="form-control" name="key" rows="7" id="key"><%= admin_key %></textarea> </div> <div class="form-group"> <h3><small style="text-transform: uppercase;">Hostname Configuration</small></h3> <div class="form-group"> <label for="hostname">Hostname</label> <input class="form-control" type="text" id="hostname" name="hostname" value="<%= hostname %>" /> </div> <div class="checkbox"> <label><input id="vhost" name="vhost" type="checkbox" value="true"> Use <abbr title="Nginx will be run on port 80 and backend to your apps based on hostname">virtualhost naming</abbr> for apps</label> </div> <p>Your app URLs will look like:</p> <pre id="example">http://hostname:port</pre> </div> <button type="button" onclick="setup()" class="btn btn-primary">Finish Setup</button> <span style="padding-left: 20px;" id="result"></span> </form> </div> <div id="error-output"></div> <script> function setup() { if ($.trim($("#key").val()) == "") { alert("Your admin public key cannot be blank.") return } if ($.trim($("#hostname").val()) == "") { alert("Your hostname cannot be blank.") return } data = $("#form").serialize() $("input,textarea,button").prop("disabled", true); $.post('/setup', data) .done(function() { $("#result").html("Success!") window.location.href = "https://github.com/progrium/dokku#deploy-an-app"; }) .fail(function(data) { $("#result").html("Something went wrong...") $("#error-output").html(data.responseText) }); } function update() { if ($("#vhost").is(":checked") && !isNaN($("#hostname").val()[0])) { alert("In order to use virtualhost naming, the hostname must not be an IP but a valid domain name.") $("#vhost").prop('checked', false); } if ($("#vhost").is(':checked')) { $("#example").html("http://&lt;app-name&gt;."+$("#hostname").val()) } else { $("#example").html("http://"+$("#hostname").val()+":&lt;app-port&gt;") } } $("#vhost").change(update); $("#hostname").change(update); update(); </script> </body> </html>
34.46281
204
0.628777
5d9947a7a4900576709440ba71d654701f226e52
159
class RenameEnterredOnToEnteredOn < ActiveRecord::Migration[4.2] def change rename_column :transplant_registrations, :enterred_on, :entered_on end end
26.5
70
0.805031
611be2b866f6d50fc5da744fc5350eb0e3e133ac
1,071
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_11_01 module Models # # Reference to another subresource. # class SubResource include MsRestAzure # @return [String] Resource ID. attr_accessor :id # # Mapper for SubResource class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'SubResource', type: { name: 'Composite', class_name: 'SubResource', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } } } } } end end end end
22.787234
70
0.528478
03085a62c56b5425adee94d565adcd8b3765439a
3,351
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? || SITE_CONFIG['serve_static_assets'] || false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
41.8875
117
0.763951
bf17325bb17a8b4365216a079f7ba2020c96a7b4
3,409
# use SSHKit directly instead of Capistrano require 'sshkit' require 'sshkit/dsl' include SSHKit::DSL deploy_tag = ENV['DEPLOY_TAG'] hostname = ENV['SERVER_HOST'] user = ENV['SERVER_USER'] dockerhub_user = ENV['DOCKERHUB_USER'] dockerhub_pass = ENV['DOCKERHUB_PASS'] dockerhub_org = ENV['DOCKERHUB_ORG'] port = ENV['SERVER_PORT'] deploy_env = ENV['DEPLOY_ENV'] || :production deploy_path = ENV['APP_NAME'] server = SSHKit::Host.new(hostname: hostname, port: port, user: user) namespace :deploy do desc 'copy to server files needed to run and manage Docker containers' task :configs do on server do within deploy_path do upload! File.expand_path('../../docker/overrides/production.docker-compose.yml', __dir__), 'docker-compose.yml' upload! File.expand_path('../../docker', __dir__), '.', recursive: true execute 'apt', 'install', 'ruby' execute 'gem', 'install', 'handsome_fencer-circle_c_i' execute 'handsome_fencer-circle_c_i', 'expose', 'production' end end end desc 'copy production key to server' task :production_key do on server do within deploy_path do upload! '.circleci/keys/production.key', '.circleci/keys/production.key' end end end desc 'expose production environment' task :expose_production_environment do on server do within deploy_path do execute 'apt', 'install', 'ruby' execute 'gem', 'install', 'handsome_fencer-circle_c_i' execute 'handsome_fencer-circle_c_i', 'expose', 'production' end end end end namespace :docker do desc 'logs into Docker Hub for pushing and pulling' task :login do on server do execute "mkdir -p #{deploy_path}" within deploy_path do execute 'docker', 'login', '-u', dockerhub_user, '-p', dockerhub_pass end end end desc 'stops all Docker containers via Docker Compose' task stop: 'deploy:configs' do on server do within deploy_path do with rails_env: deploy_env, deploy_tag: deploy_tag do execute 'docker-compose', 'stop' end end end end desc 'starts all Docker containers via Docker Compose' task start: 'deploy:configs' do on server do within deploy_path do with rails_env: deploy_env, deploy_tag: deploy_tag do execute 'docker-compose', 'up', '-d' execute 'echo', deploy_tag , '>', 'deploy.tag' end end end end desc 'pulls images from Docker Hub' task pull: 'docker:login' do on server do within deploy_path do ["#{deploy_path}_app", "#{deploy_path}_web"].each do |image_name| execute 'docker', 'pull', "#{dockerhub_org}/#{image_name}:#{deploy_tag}" end execute 'docker', 'pull', 'postgres:9.4.5' end end end desc 'runs database migrations in application container via Docker Compose' task migrate: 'deploy:configs' do on server do within deploy_path do with rails_env: deploy_env, deploy_tag: deploy_tag do execute 'docker-compose', 'run', 'app', "bin/rails", 'db:create', 'db:migrate' end end end end desc 'pulls images, stops old containers, updates the database, and starts new containers' task deploy: %w{docker:pull docker:stop docker:migrate docker:start } end
26.84252
119
0.652391
035de363ed155311377d4497384f4f70a0795db4
907
require 'telesign' require 'telesignenterprise' customer_id = 'FFFFFFFF-EEEE-DDDD-1234-AB1234567890' api_key = 'EXAMPLE----TE8sTgg45yusumoN6BYsBVkh+yRJ5czgsnCehZaOYldPJdmFh6NeX8kunZ2zU1YWaUw/0wV6xfw==' phone_number = 'phone_number' verify_code = Telesign::Util.random_with_n_digits(5) verify_client = TelesignEnterprise::VerifyClient.new(customer_id, api_key) response = verify_client.voice(phone_number, verify_code: verify_code) reference_id = response.json['reference_id'] print 'Please enter the verification code you were sent: ' user_entered_verify_code = gets.strip if verify_code == user_entered_verify_code puts 'Your code is correct.' response = verify_client.completion(reference_id) if response.ok and response.json['status']['code'] == 1900 puts 'Completion successfully reported.' else puts 'Error reporting completion.' end else puts 'Your code is incorrect.' end
29.258065
100
0.791621
d5816d3767c528353760b424847232900e317507
779
Pod::Spec.new do |s| s.name = 'WolfGraph' s.version = '0.2.2' s.summary = 'A Swift-based general graph structure with value semantics.' s.homepage = 'https://github.com/wolfmcnally/WolfGraph' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Wolf McNally' => '[email protected]' } s.source = { :git => 'https://github.com/wolfmcnally/WolfGraph.git', :tag => s.version.to_s } s.source_files = 'Sources/WolfGraph/**/*' s.swift_version = '5.0' s.ios.deployment_target = '11.0' s.macos.deployment_target = '10.13' s.tvos.deployment_target = '11.0' s.module_name = 'WolfGraph' s.dependency 'WolfCore' s.dependency 'WolfGraphics' end
32.458333
107
0.577664
912156fbc29907e3ae24b765f678051277ca4fbf
204
# frozen_string_literal: true module QA module Scenario module Test module Integration class OAuth < Test::Instance::All tags :oauth end end end end end
14.571429
41
0.602941
8752cb59689e36c929cc34a9fbc88d310e0d9749
144
require 'test_helper' class AdvertSelectorTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, AdvertSelector end end
18
50
0.784722
083183c8c684f9a27cf711b8d6480fae52436188
1,005
require 'spec_helper' describe SimpleDeploy::Stack::Execute do include_context 'stubbed config' include_context 'double stubbed stack', :name => 'my_stack', :environment => 'my_env' before do @ssh_mock = mock 'ssh' options = { :instances => @instances, :environment => @environment, :ssh_user => @ssh_user, :ssh_key => @ssh_key, :stack => @stack_stub, :name => @name } SimpleDeploy::Stack::SSH.should_receive(:new). with(options). and_return @ssh_mock @execute = SimpleDeploy::Stack::Execute.new options end it "should call execute with the given options" do options = { :sudo => true, :command => 'uname' } @ssh_mock.should_receive(:execute). with(options). and_return true @execute.execute(options).should be_true end end
32.419355
69
0.533333
1a81289dc8e50271e6b24f54fa40e6e59fd83134
659
class RemoveChpSeriesFromESourceCharts < ActiveRecord::Migration[5.2] def up ActiveRecord::Base.transaction do # Remove old series OutputElementSerie.find_by(gquery: 'collective_chps_in_source_of_electricity_in_households').destroy! OutputElementSerie.find_by(gquery: 'chps_in_source_of_electricity_in_buildings').destroy! OutputElementSerie.find_by(gquery: 'chp_electricity_in_source_of_heat_and_electricity_in_agriculture').destroy! OutputElementSerie.find_by(gquery: 'chp_heat_in_source_of_heat_and_electricity_in_agriculture').destroy! end end def down raise ActiveRecord::IrreversibleMigration end end
41.1875
117
0.811836
61f4658779035a410bd64690cb526849e0601ea1
4,120
# frozen_string_literal: true require "ripper" module ActionviewPrecompiler module RipperASTParser class Node < ::Array attr_reader :type def initialize(type, arr, opts = {}) @type = type super(arr) end def children to_a end def inspect typeinfo = type && type != :list ? ':' + type.to_s + ', ' : '' 's(' + typeinfo + map(&:inspect).join(", ") + ')' end def fcall? type == :command || type == :fcall end def fcall_named?(name) fcall? && self[0].type == :@ident && self[0][0] == name end def argument_nodes raise unless fcall? return [] if self[1].nil? self[1][0...-1] end def string? type == :string_literal end def to_string raise unless string? raise "fixme" unless self[0].type == :string_content raise "fixme" unless self[0][0].type == :@tstring_content self[0][0][0] end def hash? type == :bare_assoc_hash || type == :hash end def to_hash if type == :bare_assoc_hash hash_from_body(self[0]) elsif type == :hash && self[0] == nil {} elsif type == :hash && self[0].type == :assoclist_from_args hash_from_body(self[0][0]) else raise "not a hash? #{inspect}" end end def hash_from_body(body) body.map do |hash_node| return nil if hash_node.type != :assoc_new [hash_node[0], hash_node[1]] end.to_h end def symbol? type == :@label || type == :symbol_literal end def to_symbol if type == :@label && self[0] =~ /\A(.+):\z/ $1.to_sym elsif type == :symbol_literal && self[0].type == :symbol && self[0][0].type == :@ident self[0][0][0].to_sym else raise "not a symbol?: #{self.inspect}" end end end class NodeParser < ::Ripper PARSER_EVENTS.each do |event| arity = PARSER_EVENT_TABLE[event] if /_new\z/ =~ event.to_s && arity == 0 module_eval(<<-eof, __FILE__, __LINE__ + 1) def on_#{event}(*args) Node.new(:list, args, lineno: lineno(), column: column()) end eof elsif /_add(_.+)?\z/ =~ event.to_s module_eval(<<-eof, __FILE__, __LINE__ + 1) begin; undef on_#{event}; rescue NameError; end def on_#{event}(list, item) list.push(item) list end eof else module_eval(<<-eof, __FILE__, __LINE__ + 1) begin; undef on_#{event}; rescue NameError; end def on_#{event}(*args) Node.new(:#{event}, args, lineno: lineno(), column: column()) end eof end end SCANNER_EVENTS.each do |event| module_eval(<<-End, __FILE__, __LINE__ + 1) def on_#{event}(tok) Node.new(:@#{event}, [tok], lineno: lineno(), column: column()) end End end end class RenderCallParser < NodeParser attr_reader :render_calls METHODS_TO_PARSE = %w(render render_to_string layout) def initialize(*args) super @render_calls = [] end private def on_fcall(name, *args) on_render_call(super) end def on_command(name, *args) on_render_call(super) end def on_render_call(node) METHODS_TO_PARSE.each do |method| if node.fcall_named?(method) @render_calls << [method, node] return node end end node end def on_arg_paren(content) content end end extend self def parse_render_nodes(code) parser = RenderCallParser.new(code) parser.parse parser.render_calls.group_by(&:first).collect do |method, nodes| [ method.to_sym, nodes.collect { |v| v[1] } ] end.to_h end end end
23.542857
94
0.517476
87c8ced4d485ceb8184d3aa204c433d11e550704
2,491
require 'pathname' module Precious module Views class Overview < Layout attr_reader :results, :ref, :allow_editing, :newable HIDDEN_PATHS = ['.gitkeep'] def title "Overview of #{@ref}" end # def editable # false # end def current_path @path ? @path : '/' end def breadcrumb if @path path = Pathname.new(@path) breadcrumb = [%{<nav aria-label="Breadcrumb"><ol><li class="breadcrumb-item"><a href="#{overview_path}">Home</a></li>}] path.descend do |crumb| title = crumb.basename if title == path.basename breadcrumb << %{<li class="breadcrumb-item" aria-current="page">#{CGI.escape(title.to_s)}</li>} else breadcrumb << %{<li class="breadcrumb-item"><a href="#{overview_path}/#{crumb}/">#{CGI.escape(title.to_s)}</a></li>} end end breadcrumb << %{</ol></nav>} breadcrumb.join("\n") else 'Home' end end def files_folders if has_results files_and_folders = [] @results.each do |result| result_path = result.url_path result_path = result_path.sub(/^#{Regexp.escape(@path)}\//, '') unless @path.nil? if result_path.include?('/') # result contains a folder folder_name = result_path.split('/').first folder_path = @path ? "#{@path}/#{folder_name}" : folder_name folder_url = "#{overview_path}/#{folder_path}/" files_and_folders << {name: folder_name, icon: rocticon('file-directory'), type: 'dir', url: folder_url, is_file: false} elsif !HIDDEN_PATHS.include?(result_path) file_url = page_route(result.escaped_url_path) files_and_folders << {name: result.filename, icon: rocticon('file'), type: 'file', url: file_url, file_path: result.escaped_url_path, is_file: true} end end # 1012: Overview should list folders first, followed by files and pages sorted alphabetically files_and_folders.uniq{|f| f[:name]}.sort_by!{|f| [f[:type], f[:name]]} end end def has_results [email protected]? end def no_results @results.empty? end def latest_changes true end end end end
30.378049
162
0.541148
bfbc8200b33a8890f8b94a4937f48f43f7f0f177
225
require 'spec_helper' describe Admin::HomeController do before { activate_authlogic } describe 'includes the correct concerns' do it { expect(controller.class.ancestors.include?(Accountable)).to eq(true) } end end
25
79
0.76
4a7d02211cfc72c9b7b0e42675c9b05aaf4290a3
2,814
# frozen-string-literal: true module Leftovers module ProcessorBuilders module Transform def self.build(transform, arguments, then_processor) # rubocop:disable Metrics case transform when :original, nil then_processor when :downcase ::Leftovers::Processors::Downcase.new(then_processor) when :upcase ::Leftovers::Processors::Upcase.new(then_processor) when :capitalize ::Leftovers::Processors::Capitalize.new(then_processor) when :swapcase ::Leftovers::Processors::Swapcase.new(then_processor) when :pluralize ::Leftovers::Processors::Pluralize.new(then_processor) when :singularize ::Leftovers::Processors::Singularize.new(then_processor) when :camelize ::Leftovers::Processors::Camelize.new(then_processor) when :titleize ::Leftovers::Processors::Titleize.new(then_processor) when :demodulize ::Leftovers::Processors::Demodulize.new(then_processor) when :deconstantize ::Leftovers::Processors::Deconstantize.new(then_processor) when :parameterize ::Leftovers::Processors::Parameterize.new(then_processor) when :underscore ::Leftovers::Processors::Underscore.new(then_processor) when :transforms ::Leftovers::ProcessorBuilders::TransformSet.build(arguments, then_processor) else ::Leftovers::ProcessorBuilders::Each.each_or_self(arguments) do |argument| case transform when :split ::Leftovers::Processors::Split.new(argument, then_processor) when :delete_before ::Leftovers::Processors::DeleteBefore.new(argument, then_processor) when :delete_before_last ::Leftovers::Processors::DeleteBeforeLast.new(argument, then_processor) when :delete_after ::Leftovers::Processors::DeleteAfter.new(argument, then_processor) when :delete_after_last ::Leftovers::Processors::DeleteAfterLast.new(argument, then_processor) when :add_prefix ::Leftovers::ProcessorBuilders::AddPrefix.build(argument, then_processor) when :add_suffix ::Leftovers::ProcessorBuilders::AddSuffix.build(argument, then_processor) when :delete_prefix ::Leftovers::Processors::DeletePrefix.new(argument, then_processor) when :delete_suffix ::Leftovers::Processors::DeleteSuffix.new(argument, then_processor) # :nocov: else raise Leftovers::UnexpectedCase, "Unhandled value #{transform.to_s.inspect}" # :nocov: end end end end end end end
42
93
0.641791
fff3fd1a751a3dbc758b88b67ab34c7401dfc31f
18,376
# frozen_string_literal: true # rubocop:disable Style/AsciiComments require 'capybara/selector/filter_set' require 'capybara/selector/css' module Capybara # # ## Built-in Selectors # # * **:xpath** - Select elements by XPath expression # * Locator: An XPath expression # # * **:css** - Select elements by CSS selector # * Locator: A CSS selector # # * **:id** - Select element by id # * Locator: The id of the element to match # # * **:field** - Select field elements (input [not of type submit, image, or hidden], textarea, select) # * Locator: Matches against the id, Capybara.test_id attribute, name, or placeholder # * Filters: # * :id (String) — Matches the id attribute # * :name (String) — Matches the name attribute # * :placeholder (String) — Matches the placeholder attribute # * :type (String) — Matches the type attribute of the field or element type for 'textarea' and 'select' # * :readonly (Boolean) # * :with (String) — Matches the current value of the field # * :class (String, Array<String>) — Matches the class(es) provided # * :checked (Boolean) — Match checked fields? # * :unchecked (Boolean) — Match unchecked fields? # * :disabled (Boolean) — Match disabled field? # * :multiple (Boolean) — Match fields that accept multiple values # # * **:fieldset** - Select fieldset elements # * Locator: Matches id or contents of wrapped legend # * Filters: # * :id (String) — Matches id attribute # * :legend (String) — Matches contents of wrapped legend # * :class (String, Array<String>) — Matches the class(es) provided # # * **:link** - Find links ( <a> elements with an href attribute ) # * Locator: Matches the id or title attributes, or the string content of the link, or the alt attribute of a contained img element # * Filters: # * :id (String) — Matches the id attribute # * :title (String) — Matches the title attribute # * :alt (String) — Matches the alt attribute of a contained img element # * :class (String) — Matches the class(es) provided # * :href (String, Regexp, nil) — Matches the normalized href of the link, if nil will find <a> elements with no href attribute # # * **:button** - Find buttons ( input [of type submit, reset, image, button] or button elements ) # * Locator: Matches the id, Capybara.test_id attribute, value, or title attributes, string content of a button, or the alt attribute of an image type button or of a descendant image of a button # * Filters: # * :id (String) — Matches the id attribute # * :title (String) — Matches the title attribute # * :class (String) — Matches the class(es) provided # * :value (String) — Matches the value of an input button # * :type # # * **:link_or_button** - Find links or buttons # * Locator: See :link and :button selectors # # * **:fillable_field** - Find text fillable fields ( textarea, input [not of type submit, image, radio, checkbox, hidden, file] ) # * Locator: Matches against the id, Capybara.test_id attribute, name, or placeholder # * Filters: # * :id (String) — Matches the id attribute # * :name (String) — Matches the name attribute # * :placeholder (String) — Matches the placeholder attribute # * :with (String) — Matches the current value of the field # * :type (String) — Matches the type attribute of the field or element type for 'textarea' # * :class (String, Array<String>) — Matches the class(es) provided # * :disabled (Boolean) — Match disabled field? # * :multiple (Boolean) — Match fields that accept multiple values # # * **:radio_button** - Find radio buttons # * Locator: Match id, Capybara.test_id attribute, name, or associated label text # * Filters: # * :id (String) — Matches the id attribute # * :name (String) — Matches the name attribute # * :class (String, Array<String>) — Matches the class(es) provided # * :checked (Boolean) — Match checked fields? # * :unchecked (Boolean) — Match unchecked fields? # * :disabled (Boolean) — Match disabled field? # * :option (String) — Match the value # # * **:checkbox** - Find checkboxes # * Locator: Match id, Capybara.test_id attribute, name, or associated label text # * Filters: # * *:id (String) — Matches the id attribute # * *:name (String) — Matches the name attribute # * *:class (String, Array<String>) — Matches the class(es) provided # * *:checked (Boolean) — Match checked fields? # * *:unchecked (Boolean) — Match unchecked fields? # * *:disabled (Boolean) — Match disabled field? # * *:option (String) — Match the value # # * **:select** - Find select elements # * Locator: Match id, Capybara.test_id attribute, name, placeholder, or associated label text # * Filters: # * :id (String) — Matches the id attribute # * :name (String) — Matches the name attribute # * :placeholder (String) — Matches the placeholder attribute # * :class (String, Array<String>) — Matches the class(es) provided # * :disabled (Boolean) — Match disabled field? # * :multiple (Boolean) — Match fields that accept multiple values # * :options (Array<String>) — Exact match options # * :with_options (Array<String>) — Partial match options # * :selected (String, Array<String>) — Match the selection(s) # * :with_selected (String, Array<String>) — Partial match the selection(s) # # * **:option** - Find option elements # * Locator: Match text of option # * Filters: # * :disabled (Boolean) — Match disabled option # * :selected (Boolean) — Match selected option # # * **:datalist_input** # * Locator: # * Filters: # * :disabled # * :name # * :placeholder # # * **:datalist_option** # * Locator: # # * **:file_field** - Find file input elements # * Locator: Match id, Capybara.test_id attribute, name, or associated label text # * Filters: # * :id (String) — Matches the id attribute # * :name (String) — Matches the name attribute # * :class (String, Array<String>) — Matches the class(es) provided # * :disabled (Boolean) — Match disabled field? # * :multiple (Boolean) — Match field that accepts multiple values # # * **:label** - Find label elements # * Locator: Match id or text contents # * Filters: # * :for (Element, String) — The element or id of the element associated with the label # # * **:table** - Find table elements # * Locator: id or caption text of table # * Filters: # * :id (String) — Match id attribute of table # * :caption (String) — Match text of associated caption # * :class (String, Array<String>) — Matches the class(es) provided # # * **:frame** - Find frame/iframe elements # * Locator: Match id or name # * Filters: # * :id (String) — Match id attribute # * :name (String) — Match name attribute # * :class (String, Array<String>) — Matches the class(es) provided # # * **:element** # * Locator: Type of element ('div', 'a', etc) - if not specified defaults to '*' # * Filters: Matches on any element attribute # class Selector attr_reader :name, :format extend Forwardable class << self def all @selectors ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName end def add(name, &block) all[name.to_sym] = Capybara::Selector.new(name.to_sym, &block) end def update(name, &block) all[name.to_sym].instance_eval(&block) end def remove(name) all.delete(name.to_sym) end end def initialize(name, &block) @name = name @filter_set = FilterSet.add(name) {} @match = nil @label = nil @failure_message = nil @description = nil @format = nil @expression = nil @expression_filters = {} @default_visibility = nil @config = { enable_aria_label: false, test_id: nil } instance_eval(&block) end def custom_filters warn "Deprecated: Selector#custom_filters is not valid when same named expression and node filter exist - don't use" node_filters.merge(expression_filters).freeze end def node_filters @filter_set.node_filters end def expression_filters @filter_set.expression_filters end ## # # Define a selector by an xpath expression # # @overload xpath(*expression_filters, &block) # @param [Array<Symbol>] expression_filters ([]) Names of filters that can be implemented via this expression # @yield [locator, options] The block to use to generate the XPath expression # @yieldparam [String] locator The locator string passed to the query # @yieldparam [Hash] options The options hash passed to the query # @yieldreturn [#to_xpath, #to_s] An object that can produce an xpath expression # # @overload xpath() # @return [#call] The block that will be called to generate the XPath expression # def xpath(*allowed_filters, &block) if block @format, @expression = :xpath, block allowed_filters.flatten.each { |ef| expression_filters[ef] = Filters::IdentityExpressionFilter.new(ef) } end format == :xpath ? @expression : nil end ## # # Define a selector by a CSS selector # # @overload css(*expression_filters, &block) # @param [Array<Symbol>] expression_filters ([]) Names of filters that can be implemented via this CSS selector # @yield [locator, options] The block to use to generate the CSS selector # @yieldparam [String] locator The locator string passed to the query # @yieldparam [Hash] options The options hash passed to the query # @yieldreturn [#to_s] An object that can produce a CSS selector # # @overload css() # @return [#call] The block that will be called to generate the CSS selector # def css(*allowed_filters, &block) if block @format, @expression = :css, block allowed_filters.flatten.each { |ef| expression_filters[ef] = nil } end format == :css ? @expression : nil end ## # # Automatic selector detection # # @yield [locator] This block takes the passed in locator string and returns whether or not it matches the selector # @yieldparam [String], locator The locator string used to determin if it matches the selector # @yieldreturn [Boolean] Whether this selector matches the locator string # @return [#call] The block that will be used to detect selector match # def match(&block) @match = block if block @match end ## # # Set/get a descriptive label for the selector # # @overload label(label) # @param [String] label A descriptive label for this selector - used in error messages # @overload label() # @return [String] The currently set label # def label(label = nil) @label = label if label @label end ## # # Description of the selector # # @!method description(options) # @param [Hash] options The options of the query used to generate the description # @return [String] Description of the selector when used with the options passed def_delegator :@filter_set, :description def call(locator, selector_config: {}, **options) @config.merge! selector_config if format @expression.call(locator, options) else warn 'Selector has no format' end end ## # # Should this selector be used for the passed in locator # # This is used by the automatic selector selection mechanism when no selector type is passed to a selector query # # @param [String] locator The locator passed to the query # @return [Boolean] Whether or not to use this selector # def match?(locator) @match&.call(locator) end ## # # Define a node filter for use with this selector # # @!method node_filter(name, *types, options={}, &block) # @param [Symbol, Regexp] name The filter name # @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean] # @param [Hash] options ({}) Options of the filter # @option options [Array<>] :valid_values Valid values for this filter # @option options :default The default value of the filter (if any) # @option options :skip_if Value of the filter that will cause it to be skipped # @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name. # # If a Symbol is passed for the name the block should accept | node, option_value |, while if a Regexp # is passed for the name the block should accept | node, option_name, option_value |. In either case # the block should return `true` if the node passes the filer or `false` if it doesn't # @!method filter # See {Selector#node_filter} ## # # Define an expression filter for use with this selector # # @!method expression_filter(name, *types, options={}, &block) # @param [Symbol, Regexp] name The filter name # @param [Regexp] matcher (nil) A Regexp used to check whether a specific option is handled by this filter # @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean] # @param [Hash] options ({}) Options of the filter # @option options [Array<>] :valid_values Valid values for this filter # @option options :default The default value of the filter (if any) # @option options :skip_if Value of the filter that will cause it to be skipped # @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name. # # If a Symbol is passed for the name the block should accept | current_expression, option_value |, while if a Regexp # is passed for the name the block should accept | current_expression, option_name, option_value |. In either case # the block should return the modified expression def_delegators :@filter_set, :node_filter, :expression_filter, :filter def filter_set(name, filters_to_use = nil) @filter_set.import(name, filters_to_use) end def_delegator :@filter_set, :describe def describe_expression_filters(&block) if block_given? describe(:expression_filters, &block) else describe(:expression_filters) do |**options| describe_all_expression_filters(options) end end end def describe_node_filters(&block) describe(:node_filters, &block) end ## # # Set the default visibility mode that shouble be used if no visibile option is passed when using the selector. # If not specified will default to the behavior indicated by Capybara.ignore_hidden_elements # # @param [Symbol] default_visibility Only find elements with the specified visibility: # * :all - finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - only finds visible elements. def visible(default_visibility) @default_visibility = default_visibility end def default_visibility(fallback = Capybara.ignore_hidden_elements) return @default_visibility unless @default_visibility.nil? fallback end private def enable_aria_label @config[:enable_aria_label] end def test_id @config[:test_id] end def locate_field(xpath, locator, **_options) return xpath if locator.nil? locate_xpath = xpath # Need to save original xpath for the label wrap locator = locator.to_s attr_matchers = [XPath.attr(:id) == locator, XPath.attr(:name) == locator, XPath.attr(:placeholder) == locator, XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)].reduce(:|) attr_matchers |= XPath.attr(:'aria-label').is(locator) if enable_aria_label attr_matchers |= XPath.attr(test_id) == locator if test_id locate_xpath = locate_xpath[attr_matchers] locate_xpath + XPath.descendant(:label)[XPath.string.n.is(locator)].descendant(xpath) end def describe_all_expression_filters(**opts) expression_filters.map do |ef_name, ef| if ef.matcher? opts.keys.map do |k| " with #{ef_name}[#{k} => #{opts[k]}]" if ef.handles_option?(k) && !::Capybara::Queries::SelectorQuery::VALID_KEYS.include?(k) end.join elsif opts.key?(ef_name) " with #{ef_name} #{opts[ef_name]}" end end.join end def find_by_attr(attribute, value) finder_name = "find_by_#{attribute}_attr" if respond_to?(finder_name, true) send(finder_name, value) else value ? XPath.attr(attribute) == value : nil end end def find_by_class_attr(classes) Array(classes).map { |klass| XPath.attr(:class).contains_word(klass) }.reduce(:&) end end end # rubocop:enable Style/AsciiComments
41.10962
202
0.618361
f7394b3c0e58a83e2b7d9474eceabb55a6bdf30b
576
require 'minitest_helper' describe Marshal do class Klass def initialize(str) @str = str end def say_hello @str end end it 'Dump and encode base 64' do obj = Klass.new 'hello world' Marshal.encode64(obj).must_match %r(^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$) end it 'Decode base 64 and load' do serialization = Marshal.encode64(Klass.new('hello people')) obj = Marshal.decode64 serialization obj.must_be_instance_of Klass obj.say_hello.must_equal 'hello people' end end
21.333333
117
0.635417
62fd8ccf1b908c2e64ffd0e80c9eb99ce19d7a9d
5,192
module Carnival class Field attr_accessor :size, :column, :line, :name, :params def initialize(name, params={}) @params = params @name = name set_position_by_params validate end #def name # @name.to_s #end def specified_association? not get_association_and_field[:association].nil? end def association_name get_association_and_field[:association] || @name end def association_field_name if specified_association? get_association_and_field[:field] end end def name_for_translation @name.to_s.gsub('.', '_') end def css_class if @params[:css_class] return @params[:css_class] else return "" end end def date_filter? @params[:date_filter] end def default_date_filter if @params[:date_filter_default] @params[:date_filter_default] else date_filter_periods.first.first end end def date_filter_periods if @params[:date_filter_periods] @params[:date_filter_periods] else {:today => ["#{Date.today}", "#{Date.today}"], :yesterday => ["#{Date.today - 1.day}", "#{Date.today - 1.day}"], :this_week => ["#{Date.today.beginning_of_week}", "#{Date.today.end_of_week}"], :last_week => ["#{(Date.today - 1.week).beginning_of_week}", "#{(Date.today - 1.week).end_of_week}"], :this_month => ["#{Date.today.beginning_of_month}", "#{Date.today.end_of_month}"], :last_month => ["#{(Date.today - 1.month).beginning_of_month}", "#{(Date.today - 1.month).end_of_month}"], :this_year => ["#{Date.today.beginning_of_year}", "#{Date.today.end_of_year}"], :last_year => ["#{(Date.today - 1.year).beginning_of_year}", "#{(Date.today - 1.year).end_of_year}"] } end end def default_sortable? @params[:sortable] && @params[:sortable].class == Hash && @params[:sortable][:default] == true end def default_sort_direction if default_sortable? if @params[:sortable][:direction] return @params[:sortable][:direction] end end return :asc end def depends_on @params[:depends_on] end def nested_form? @params[:nested_form] end def nested_form_allow_destroy? @params[:nested_form_allow_destroy] end def nested_form_modes? (mode) associate = get_associate_nested_form_mode return true if associate.present? && mode == :associate return @params[:nested_form_modes].include?(mode) unless @params[:nested_form_modes].nil? return false end def nested_form_scope return nil if !nested_form_modes? :associate associate_mode = get_associate_nested_form_mode return nil if associate_mode.is_a? Symbol return associate_mode[:scope] if associate_mode[:scope].present? end def sortable? return true if @params[:sortable].nil? return true if @params[:sortable] return true if @params[:sortable].class == Hash return false end def sortable_params return false if !sortable? return @params[:sortable].to_json if @params[:sortable].class == Hash return true end def searchable? @params[:searchable] end def advanced_searchable? @params[:advanced_search] end def show_as_list @params[:show_as_list] end def advanced_search_operator return @params[:advanced_search][:operator] if advanced_searchable? and @params[:advanced_search][:operator].present? :like end def actions @params[:actions] end def valid_for_action?(action) return false if @params[:actions].nil? @params[:actions].include?(action) end def as @params[:as] end def widget @params[:widget].present? ? @params[:widget] : :input end def show_view @params[:show_view] end def sort_name return @params[:related_to].to_s if @params[:related_to].present? @name.to_s end private def get_association_and_field split = @name.to_s.split('.') if split.size > 1 association = split[0] field = split[1] else field = split[0] end { association: association, field: field } end def validate if nested_form_modes?(:new) and nested_form_modes?(:associate) raise ArgumentError.new("field does not support nested_forms_modes with :new and :associate options at same time") end end def set_position_by_params if @params[:position].present? @line = @params[:position][:line] @column = @params[:position][:column] @size = @params[:position][:size] end end def get_associate_nested_form_mode return nil if @params[:nested_form_modes].nil? @params[:nested_form_modes].each do |mode| if mode.is_a? Hash return mode[:associate] if mode[:associate].present? elsif mode.is_a? Symbol return mode if mode == :associate end end nil end end end
25.326829
123
0.622496
91160fc5d87b1eafb14dc91d20a92ac17a194096
3,230
require "language/go" class Terraform < Formula desc "Tool to build, change, and version infrastructure" homepage "https://www.terraform.io/" url "https://github.com/hashicorp/terraform/archive/v0.6.15.tar.gz" sha256 "5dc7cb1d29dee3de9ed9efacab7e72aa447052c96ae8269d932f6a979871a852" head "https://github.com/hashicorp/terraform.git" bottle do cellar :any_skip_relocation sha256 "634e81edcc7b8a23a45701a89a7674d0e42029052a0a6773ded8fec0fc85e34d" => :el_capitan sha256 "19f698b20da37ec5256f9446f03f78000fc4d1719540580abb4c9b6e3b535227" => :yosemite sha256 "c72e135740cbf6cbddfaf27bda8b3c9935e787ca2e6f11d03566477e50899b1b" => :mavericks end depends_on "go" => :build terraform_deps = %w[ github.com/mitchellh/gox 770c39f64e66797aa46b70ea953ff57d41658e40 github.com/mitchellh/iochan 87b45ffd0e9581375c491fef3d32130bb15c5bd7 ] terraform_deps.each_slice(2) do |x, y| go_resource x do url "https://#{x}.git", :revision => y end end go_resource "golang.org/x/tools" do url "https://go.googlesource.com/tools.git", :revision => "977844c7af2aa555048a19d28e9fe6c392e7b8e9" end def install ENV["GOPATH"] = buildpath # For the gox buildtool used by terraform, which doesn't need to # get installed permanently ENV.append_path "PATH", buildpath terrapath = buildpath/"src/github.com/hashicorp/terraform" terrapath.install Dir["*"] Language::Go.stage_deps resources, buildpath/"src" cd "src/github.com/mitchellh/gox" do system "go", "build" buildpath.install "gox" end cd "src/golang.org/x/tools/cmd/stringer" do system "go", "build" buildpath.install "stringer" end cd terrapath do # v0.6.12 - source contains tests which fail if these environment variables are set locally. ENV.delete "AWS_ACCESS_KEY" ENV.delete "AWS_SECRET_KEY" terraform_files = `go list ./...`.lines.map { |f| f.strip unless f.include? "/vendor/" }.compact system "go", "test", *terraform_files mkdir "bin" arch = MacOS.prefer_64_bit? ? "amd64" : "386" system "gox", "-arch", arch, "-os", OS::NAME, "-output", "bin/terraform-{{.Dir}}", *terraform_files bin.install "bin/terraform-terraform" => "terraform" bin.install Dir["bin/*"] zsh_completion.install "contrib/zsh-completion/_terraform" end end test do minimal = testpath/"minimal.tf" minimal.write <<-EOS.undent variable "aws_region" { default = "us-west-2" } variable "aws_amis" { default = { eu-west-1 = "ami-b1cf19c6" us-east-1 = "ami-de7ab6b6" us-west-1 = "ami-3f75767a" us-west-2 = "ami-21f78e11" } } # Specify the provider and access details provider "aws" { access_key = "this_is_a_fake_access" secret_key = "this_is_a_fake_secret" region = "${var.aws_region}" } resource "aws_instance" "web" { instance_type = "m1.small" ami = "${lookup(var.aws_amis, var.aws_region)}" count = 4 } EOS system "#{bin}/terraform", "graph", testpath end end
30.471698
104
0.654799
e2815d8aae9da18889ae54c5f66c1405874c804a
1,210
# encoding: UTF-8 require 'rails_helper' describe 'my/show.html.erb', type: :view do let(:src_sets) { [] } before do assign(:gend_images, Kaminari.paginate_array([]).page(1)) assign(:src_images, Kaminari.paginate_array([]).page(1)) assign(:src_sets, Kaminari.paginate_array(src_sets).page(1)) assign(:show_toolbar, true) def view.current_user nil end end it 'sets the content for the title' do expect(view).to receive(:content_for).with(:title) do |&block| expect(block.call).to eq('Meme Captain My Images') end render end context 'when there are src sets' do let(:src_sets) { [FactoryGirl.create(:src_set)] * 2 } it 'renders the src sets partial' do allow(view).to receive(:render).and_call_original expect(view).to receive(:render).with( partial: 'src_sets/src_sets', locals: { src_sets: src_sets, paginate: true }) render end end it 'renders the API token partial' do assign(:api_token, 'secret') allow(view).to receive(:render).and_call_original expect(view).to receive(:render).with( partial: 'api_token', locals: { current_token: 'secret' }) render end end
26.304348
66
0.657851
e2f2fa4db2f102c1ee03055f549cf94e8edf234e
441
class CompanySize < ActiveHash::Base include ExposableViaApi self.data = [ { id: ID_FOR_ALL, name: "All Company sizes" }, { id: "0-9", name: "0-9" }, { id: "10-249", name: "10-249" }, { id: "250-500", name: "250-500" }, { id: "501-1000", name: "501-1000" }, { id: "more_than_1000", name: "1000 +" }, ] def to_s name end def self.collection all end def self.ids all.map(&:id) end end
17.64
50
0.544218
116233ca4cc49996e91c0058c5951fad11935f1c
111
module Skeletor class RequiredBothPlatformsError < LoadError end require "Skeletor/version" end
9.25
46
0.738739
0132cfc010c2f4aa85eacb1601ff98779252e48d
870
# frozen_string_literal: true RSpec.describe Zen::Search::Updater do let(:subject) { Zen::Search::Updater } context ".run" do let(:users) { ZenSearchTestHelper::Mock.new.users } let(:tickets) { ZenSearchTestHelper::Mock.new.tickets } let(:user_collection) { Zen::Search::Users.new(users) } let(:ticket_collection) { Zen::Search::Tickets.new(tickets) } before(:each) do subject.run(user_collection, ticket_collection) end describe "when called" do it "is expected to update user collection with tickets" do user_collection.each do |user| expect(user.tickets.size).to eq(1) end end it "is expected to update ticket collection with assignee name" do ticket_collection.each do |ticket| expect(ticket.assignee_name).not_to be_nil end end end end end
28.064516
72
0.664368
bf48252d32f6a7ed0d0171e499961c04e0576e0d
1,208
load File.expand_path("../set_rails_env.rake", __FILE__) namespace :deploy do desc 'Runs rake db:migrate if migrations are set' task :migrate => [:set_rails_env] do on fetch(:migration_servers) do conditionally_migrate = fetch(:conditionally_migrate) info '[deploy:migrate] Checking changes in /db/migrate' if conditionally_migrate if conditionally_migrate && test("diff -q #{release_path}/db/migrate #{current_path}/db/migrate") info '[deploy:migrate] Skip `deploy:migrate` (nothing changed in db/migrate)' else info '[deploy:migrate] Run `rake db:migrate`' invoke :'deploy:migrating' end end end desc 'Runs rake db:migrate' task migrating: [:set_rails_env] do on fetch(:migration_servers) do within release_path do with rails_env: fetch(:rails_env) do execute :rake, 'db:migrate' end end end end after 'deploy:updated', 'deploy:migrate' end namespace :load do task :defaults do set :conditionally_migrate, fetch(:conditionally_migrate, false) set :migration_role, fetch(:migration_role, :db) set :migration_servers, -> { primary(fetch(:migration_role)) } end end
30.2
103
0.686258
114276df875a7b652f6c0b3dafc9edc54a631946
4,723
# frozen_string_literal: true class RemoveDuplicateLabelsFromGroup < ActiveRecord::Migration[6.0] DOWNTIME = false CREATE = 1 RENAME = 2 disable_ddl_transaction! class BackupLabel < ApplicationRecord include EachBatch self.table_name = 'backup_labels' end class Label < ApplicationRecord self.table_name = 'labels' end class Group < ApplicationRecord include EachBatch self.table_name = 'namespaces' end BATCH_SIZE = 10_000 def up # Split to smaller chunks # Loop rather than background job, every 10,000 # there are ~1,800,000 groups in total (excluding personal namespaces, which can't have labels) Group.where(type: 'Group').each_batch(of: BATCH_SIZE) do |batch| range = batch.pluck('MIN(id)', 'MAX(id)').first transaction do remove_full_duplicates(*range) end transaction do rename_partial_duplicates(*range) end end end DOWN_BATCH_SIZE = 1000 def down BackupLabel.where('project_id IS NULL AND group_id IS NOT NULL').each_batch(of: DOWN_BATCH_SIZE) do |batch| range = batch.pluck('MIN(id)', 'MAX(id)').first restore_renamed_labels(*range) restore_deleted_labels(*range) end end def remove_full_duplicates(start_id, stop_id) # Fields that are considered duplicate: # group_id title template description type color duplicate_labels = ApplicationRecord.connection.execute(<<-SQL.squish) WITH data AS #{Gitlab::Database::AsWithMaterialized.materialized_if_supported} ( SELECT labels.*, row_number() OVER (PARTITION BY labels.group_id, labels.title, labels.template, labels.description, labels.type, labels.color ORDER BY labels.id) AS row_number, #{CREATE} AS restore_action FROM labels WHERE labels.group_id BETWEEN #{start_id} AND #{stop_id} AND NOT EXISTS (SELECT * FROM board_labels WHERE board_labels.label_id = labels.id) AND NOT EXISTS (SELECT * FROM label_links WHERE label_links.label_id = labels.id) AND NOT EXISTS (SELECT * FROM label_priorities WHERE label_priorities.label_id = labels.id) AND NOT EXISTS (SELECT * FROM lists WHERE lists.label_id = labels.id) AND NOT EXISTS (SELECT * FROM resource_label_events WHERE resource_label_events.label_id = labels.id) ) SELECT * FROM data WHERE row_number > 1; SQL if duplicate_labels.any? # create backup records BackupLabel.insert_all!(duplicate_labels.map { |label| label.except("row_number") }) Label.unscoped.where(id: duplicate_labels.pluck("id")).delete_all end end def rename_partial_duplicates(start_id, stop_id) # We need to ensure that the new title (with `_duplicate#{ID}`) doesn't exceed the limit. # Truncate the original title (if needed) to 245 characters minus the length of the ID # then add `_duplicate#{ID}` soft_duplicates = ApplicationRecord.connection.execute(<<-SQL.squish) WITH data AS #{Gitlab::Database::AsWithMaterialized.materialized_if_supported} ( SELECT *, substring(title from 1 for 245 - length(id::text)) || '_duplicate' || id::text as new_title, #{RENAME} AS restore_action, row_number() OVER (PARTITION BY group_id, title ORDER BY id) AS row_number FROM labels WHERE group_id BETWEEN #{start_id} AND #{stop_id} ) SELECT * FROM data WHERE row_number > 1; SQL if soft_duplicates.any? # create backup records BackupLabel.insert_all!(soft_duplicates.map { |label| label.except("row_number") }) ApplicationRecord.connection.execute(<<-SQL.squish) UPDATE labels SET title = substring(title from 1 for 245 - length(id::text)) || '_duplicate' || id::text WHERE labels.id IN (#{soft_duplicates.map { |dup| dup["id"] }.join(", ")}); SQL end end def restore_renamed_labels(start_id, stop_id) # the backup label IDs are not incremental, they are copied directly from the Labels table ApplicationRecord.connection.execute(<<-SQL.squish) WITH backups AS #{Gitlab::Database::AsWithMaterialized.materialized_if_supported} ( SELECT id, title FROM backup_labels WHERE id BETWEEN #{start_id} AND #{stop_id} AND restore_action = #{RENAME} ) UPDATE labels SET title = backups.title FROM backups WHERE labels.id = backups.id; SQL end def restore_deleted_labels(start_id, stop_id) ActiveRecord::Base.connection.execute(<<-SQL.squish) INSERT INTO labels SELECT id, title, color, group_id, created_at, updated_at, template, description, description_html, type, cached_markdown_version FROM backup_labels WHERE backup_labels.id BETWEEN #{start_id} AND #{stop_id} AND backup_labels.project_id IS NULL AND backup_labels.group_id IS NOT NULL AND backup_labels.restore_action = #{CREATE} SQL end end
34.727941
162
0.729198
2641b9b4db6bae4b907abdcb48b8376c3b8e91a1
6,832
#!/usr/bin/env rspec @agent_file = File.join('mcollective', 'agent', 'rpcutil') require 'spec_helper' require @agent_file module MCollective module Agent describe Rpcutil do module Facts def self.[](fact) {'fact1' => 'value1', 'fact2' => 'value2', 'fact3' => 'value3'}[fact] end end before :each do @agent = MCollective::Test::LocalAgentTest.new('rpcutil', :agent_file => @agent_file).plugin end describe '#inventory' do it 'should return the node inventory' do facts = mock facts.stubs(:get_facts).returns({:key => 'value'}) Agents.stubs(:agentlist).returns(['test']) PluginManager.stubs(:[]).with('facts_plugin').returns(facts) MCollective.stubs(:version).returns('2.4.0') PluginManager.stubs(:grep).with(/_data$/).returns(['test_data']) Config.any_instance.stubs(:classesfile).returns('classes.txt') File.stubs(:exist?).with('classes.txt').returns(true) File.stubs(:readlines).with('classes.txt').returns(['class1', 'class2']) result = @agent.call(:inventory) result.should be_successful result.should have_data_items({:agents=>["test"], :facts=>{:key=>"value"}, :version=>"2.4.0", :classes=>["class1", "class2"], :main_collective=>"mcollective", :collectives=>["production", "staging"], :data_plugins=>["test_data"]}) end end describe '#get_fact' do it 'should return the value of the queried fact' do result = @agent.call(:get_fact, :fact => 'fact1') result.should be_successful result.should have_data_items({:fact => 'fact1', :value => 'value1'}) end it 'should not break if the fact is not present' do result = @agent.call(:get_fact, :fact => 'fact4') result.should be_successful result.should have_data_items({:fact => 'fact4', :value => nil }) end end describe '#get_facts' do it 'should return the value of the supplied facts' do result = @agent.call(:get_facts, :facts => 'fact1, fact3') result.should be_successful result.should have_data_items(:values => {'fact1' => 'value1', 'fact3' => 'value3'}) end it 'should not break if the facts are not present' do result = @agent.call(:get_facts, :facts => 'fact4, fact5') result.should be_successful result.should have_data_items(:values => {'fact4' => nil, 'fact5' => nil}) end end describe '#daemon_stats' do it "it should return the daemon's statistics" do stats = {:threads => 2, :agents => ['agent1', 'agent2'], :pid => 42, :times => 12345, :configfile => '/etc/mcollective/server.cfg', :version => '2.4.0', :stats => {}} config = mock Config.stubs(:instance).returns(config) MCollective.stubs(:version).returns('2.4.0') config.stubs(:configfile).returns('/etc/mcollective/server.cfg') PluginManager.stubs(:[]).returns(stats) result = @agent.call(:daemon_stats) result.should be_successful stats.delete(:stats) result.should have_data_items(stats) end end describe '#agent_inventory' do it 'should return the agent inventory' do meta = {:license => 'ASL 2', :description => 'Agent for testing', :url => 'http://www.theurl.net', :version => '1', :author => 'rspec'} agent = mock agent.stubs(:meta).returns(meta) agent.stubs(:timeout).returns(2) PluginManager.stubs(:[]).with('test_agent').returns(agent) Agents.stubs(:agentlist).returns(['test']) result = @agent.call(:agent_inventory) result.should be_successful result.should have_data_items(:agents => [meta.merge({:timeout => 2, :name => 'test', :agent => 'test'})]) end end describe '#get_config_item' do it 'should return the value of the requested config item' do Config.any_instance.stubs(:respond_to?).with(:main_collective).returns(true) result = @agent.call(:get_config_item, :item => :main_collective) result.should be_successful result.should have_data_items(:item => :main_collective, :value => "mcollective") end it 'should fail if the config item has not been defined' do result = @agent.call(:get_config_item, :item => :failure) result.should be_aborted_error end end describe '#ping' do it 'should return the current time on the host' do Time.expects(:now).returns("123456") result = @agent.call(:ping) result.should be_successful result.should have_data_items(:pong => 123456) end end describe '#collective_info' do it 'should return the main collective and list of defined collectives' do result = @agent.call(:collective_info) result.should be_successful result.should have_data_items({:main_collective => 'mcollective', :collectives => ['production', 'staging']}) end end describe '#get_data' do let(:query_data) do {:key1 => 'value1', :key2 => 'value2'} end let(:data) do mock end let(:ddl) do mock end it 'should return the data results if a query has been specified' do data.stubs(:lookup).with('query').returns(query_data) Data.stubs(:ddl).with('test_data').returns(ddl) Data.stubs(:ddl_transform_input).with(ddl, 'query').returns('query') Data.stubs(:[]).with('test_data').returns(data) result = @agent.call(:get_data, :source => 'test_data', :query => 'query') result.should be_successful result.should have_data_items(:key1 => 'value1', :key2 => 'value2') end it 'should return the data results if no query has been specified' do data.stubs(:lookup).with(nil).returns(query_data) Data.stubs(:[]).with('test_data').returns(data) result = @agent.call(:get_data, :source => 'test_data') result.should be_successful result.should have_data_items(:key1 => 'value1', :key2 => 'value2') end end end end end
38.59887
119
0.559426
010b89c4f48a23ef61c83e4e45cd91dd6e44e23a
1,596
# # Author:: Daniel DeLeo (<[email protected]>) # Copyright:: Copyright 2010-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "tiny_server" describe Chef::Knife::Exec do before(:each) do @server = TinyServer::Manager.new # (:debug => true) @server.start end after(:each) do @server.stop end before(:each) do @knife = Chef::Knife::Exec.new @api = TinyServer::API.instance @api.clear Chef::Config[:node_name] = nil Chef::Config[:client_key] = nil Chef::Config[:chef_server_url] = "http://localhost:9000" $output = StringIO.new end it "executes a script in the context of the chef-shell main context" do @node = Chef::Node.new @node.name("ohai-world") response = { "rows" => [@node], "start" => 0, "total" => 1 } @api.get(%r{^/search/node}, 200, Chef::JSONCompat.to_json(response)) code = "$output.puts nodes.all" @knife.config[:exec] = code @knife.run expect($output.string).to match(/node\[ohai-world\]/) end end
28.5
74
0.680451
6a8ad7c5f0028ba911d9e1b06ba3f34bd4f685f8
601
require 'logger' require 'semantic_logger' log_level = begin Kernel.const_get('Logger').const_get(ENV['PACT_BROKER_LOG_LEVEL'] || 'WARN') rescue NameError $stderr.puts "Ignoring PACT_BROKER_LOG_LEVEL '#{ENV['PACT_BROKER_LOG_LEVEL']}' as it is invalid. Valid values are: DEBUG INFO WARN ERROR FATAL. Using WARN." Logger::WARN end SemanticLogger.add_appender(io: $stdout) SemanticLogger.default_level = log_level $logger = SemanticLogger['pact-broker'] PADRINO_LOGGER = { ENV.fetch('RACK_ENV').to_sym => { log_level: :error, stream: :stdout, format_datetime: '%Y-%m-%dT%H:%M:%S.000%:z' } }
33.388889
158
0.740433
62ead1cf76614978c2ed1b4a10ea436b030dc875
958
# encoding: utf-8 # copyright: 2015, Vulcano Security GmbH # license: All rights reserved # author: Dominik Richter # author: Christoph Hartmann module FindFiles TYPES = { block: 'b', character: 'c', directory: 'd', pipe: 'p', file: 'f', link: 'l', socket: 's', door: 'D', }.freeze # ignores errors def find_files(path, opts = {}) find_files_or_error(path, opts) || [] end def find_files_or_error(path, opts = {}) depth = opts[:depth] type = TYPES[opts[:type].to_sym] if opts[:type] cmd = "find #{path}" cmd += " -maxdepth #{depth.to_i}" if depth.to_i > 0 cmd += " -type #{type}" unless type.nil? result = inspec.command(cmd) exit_status = result.exit_status unless exit_status == 0 warn "find_files(): exit #{exit_status} from `#{cmd}`" return nil end result.stdout.split("\n") .map(&:strip) .find_all { |x| !x.empty? } end end
21.288889
60
0.585595
3353735c95a553c524753ffc127f557dbfe12d17
5,127
# Patches for Qt must be at the very least submitted to Qt's Gerrit codereview # rather than their bug-report Jira. The latter is rarely reviewed by Qt. class Qt < Formula desc "Cross-platform application and UI framework" homepage "https://www.qt.io/" url "https://download.qt.io/official_releases/qt/5.15/5.15.2/single/qt-everywhere-src-5.15.2.tar.xz" mirror "https://mirrors.dotsrc.org/qtproject/archive/qt/5.15/5.15.2/single/qt-everywhere-src-5.15.2.tar.xz" mirror "https://mirrors.ocf.berkeley.edu/qt/archive/qt/5.15/5.15.2/single/qt-everywhere-src-5.15.2.tar.xz" sha256 "3a530d1b243b5dec00bc54937455471aaa3e56849d2593edb8ded07228202240" license all_of: ["GFDL-1.3-only", "GPL-2.0-only", "GPL-3.0-only", "LGPL-2.1-only", "LGPL-3.0-only"] head "https://code.qt.io/qt/qt5.git", branch: "dev", shallow: false # The first-party website doesn't make version information readily available, # so we check the `head` repository tags instead. livecheck do url :head regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any, arm64_big_sur: "049a78d3f84586a28d9d035bc5ff1a677b0dd9bd8c81b5775919591cde99f258" sha256 cellar: :any, big_sur: "ac22ab5828d894518e42f00e254f1e36d5be4e5f3f1c08b3cd49b57819daaf2d" sha256 cellar: :any, catalina: "51ab78a99ff3498a236d15d9bed92962ddd2499c4020356469f7ab1090cf6825" sha256 cellar: :any, mojave: "25c4a693c787860b090685ac5cbeea18128d4d6361eed5b1bfed1b16ff6e4494" end keg_only "Qt 5 has CMake issues when linked" depends_on "pkg-config" => :build depends_on xcode: :build depends_on macos: :sierra uses_from_macos "gperf" => :build uses_from_macos "bison" uses_from_macos "flex" uses_from_macos "sqlite" # Find SDK for 11.x macOS # Upstreamed, remove when Qt updates Chromium patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/92d4cf/qt/5.15.2.diff" sha256 "fa99c7ffb8a510d140c02694a11e6c321930f43797dbf2fe8f2476680db4c2b2" end # Patch for qmake on ARM # https://codereview.qt-project.org/c/qt/qtbase/+/327649 if Hardware::CPU.arm? patch do url "https://raw.githubusercontent.com/Homebrew/formula-patches/9dc732/qt/qt-split-arch.patch" sha256 "36915fde68093af9a147d76f88a4e205b789eec38c0c6f422c21ae1e576d45c0" directory "qtbase" end end def install args = %W[ -verbose -prefix #{prefix} -release -opensource -confirm-license -system-zlib -qt-libpng -qt-libjpeg -qt-freetype -qt-pcre -nomake examples -nomake tests -no-rpath -pkg-config -dbus-runtime ] if Hardware::CPU.arm? # Temporarily fixes for Apple Silicon args << "-skip" << "qtwebengine" << "-no-assimp" else # Should be reenabled unconditionnaly once it is fixed on Apple Silicon args << "-proprietary-codecs" end system "./configure", *args # Remove reference to shims directory inreplace "qtbase/mkspecs/qmodule.pri", /^PKG_CONFIG_EXECUTABLE = .*$/, "PKG_CONFIG_EXECUTABLE = #{Formula["pkg-config"].opt_bin/"pkg-config"}" system "make" ENV.deparallelize system "make", "install" # Some config scripts will only find Qt in a "Frameworks" folder frameworks.install_symlink Dir["#{lib}/*.framework"] # The pkg-config files installed suggest that headers can be found in the # `include` directory. Make this so by creating symlinks from `include` to # the Frameworks' Headers folders. Pathname.glob("#{lib}/*.framework/Headers") do |path| include.install_symlink path => path.parent.basename(".framework") end # Move `*.app` bundles into `libexec` to expose them to `brew linkapps` and # because we don't like having them in `bin`. # (Note: This move breaks invocation of Assistant via the Help menu # of both Designer and Linguist as that relies on Assistant being in `bin`.) libexec.mkpath Pathname.glob("#{bin}/*.app") { |app| mv app, libexec } end def caveats s = <<~EOS We agreed to the Qt open source license for you. If this is unacceptable you should uninstall. EOS if Hardware::CPU.arm? s += <<~EOS This version of Qt on Apple Silicon does not include QtWebEngine EOS end s end test do (testpath/"hello.pro").write <<~EOS QT += core QT -= gui TARGET = hello CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp EOS (testpath/"main.cpp").write <<~EOS #include <QCoreApplication> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "Hello World!"; return 0; } EOS # Work around "error: no member named 'signbit' in the global namespace" ENV.delete "CPATH" system bin/"qmake", testpath/"hello.pro" system "make" assert_predicate testpath/"hello", :exist? assert_predicate testpath/"main.o", :exist? system "./hello" end end
32.449367
109
0.672128
1ca222a12c85701d57cafe94dddd588241612de7
59
module Sass module Rails VERSION = "5.0.4" end end
9.833333
21
0.627119
33b810588147adab605bf15aa83602b536bb075c
1,491
class ProjectUserInvitation < ActiveRecord::Base belongs_to :user, :inverse_of => :project_user_invitations belongs_to :invited_user, :class_name => "User", :inverse_of => :project_user_invitations_received belongs_to :project, :inverse_of => :project_user_invitations validates_presence_of :user_id, :invited_user_id, :project_id validates_uniqueness_of :invited_user_id, :scope => :project_id, :message => "has already been invited" validate :user_is_not_already_a_member after_create :email_user, :create_update_for_user after_destroy :destroy_updates def email_user Emailer.project_user_invitation(self).deliver_now end def create_update_for_user action_attrs = { resource: self, notifier: self, notification: "invited" } if action = UpdateAction.first_with_attributes(action_attrs) action.append_subscribers( [invited_user.id] ) end end def destroy_updates UpdateAction.delete_and_purge( resource_type: "ProjectUserInvitation", resource_id: id) end def accepted? @accepted = ProjectUser.where(:project_id => project_id, :user_id => invited_user_id).exists? end def pending? !accepted? end def user_is_not_already_a_member return true if project_id.blank?|| invited_user_id.blank? if ProjectUser.where(:project_id => project_id, :user_id => invited_user_id).exists? errors.add(:invited_user_id, "is already a member of that project") end true end end
31.0625
105
0.746479
79185c39800dda02061c7c8cf4add50d9fabab1f
5,174
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20131120194644) do create_table "accounts", :force => true do |t| t.text "last_4_digits" t.text "company" t.text "phone" t.text "stripe_access_token" t.text "stripe_publishable_key" t.text "stripe_account_id" t.text "stripe_livemode" t.datetime "stripe_connected_at" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.datetime "last_synced" t.integer "plan_id" t.text "stripe_customer_id" t.boolean "active", :default => true end create_table "authentications", :force => true do |t| t.integer "account_id", :null => false t.string "provider", :null => false t.string "uid", :null => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "events", :force => true do |t| t.integer "account_id" t.text "event_id" t.boolean "livemode" t.text "event_type" t.text "data" t.text "object" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "events", ["account_id"], :name => "index_events_on_account_id" add_index "events", ["event_id"], :name => "index_events_on_event_id", :unique => true add_index "events", ["event_type", "created_at"], :name => "index_events_on_event_type_and_created_at" add_index "events", ["event_type"], :name => "index_events_on_event_type" create_table "plans", :force => true do |t| t.string "title" t.string "permalink" t.string "api_handle" t.decimal "price" t.integer "feature_customers" t.integer "feature_users" t.boolean "feature_email_reports", :default => false t.boolean "feature_compare_biz", :default => false t.boolean "active", :default => true t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "stats", :force => true do |t| t.integer "account_id" t.text "method_name" t.text "method_key" t.text "data" t.date "occurred_on" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "stats", ["account_id", "method_name", "method_key", "occurred_on"], :name => "index_stat_account_method_name_key_occurred" add_index "stats", ["account_id"], :name => "index_stats_on_account_id" add_index "stats", ["method_key"], :name => "index_stats_on_method_key" add_index "stats", ["method_name"], :name => "index_stats_on_method_name" create_table "users", :force => true do |t| t.string "email", :null => false t.string "crypted_password" t.string "salt" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "reset_password_token" t.datetime "reset_password_token_expires_at" t.datetime "reset_password_email_sent_at" t.string "remember_me_token" t.datetime "remember_me_token_expires_at" t.datetime "last_login_at" t.datetime "last_logout_at" t.datetime "last_activity_at" t.string "last_login_from_ip_address" t.integer "failed_logins_count", :default => 0 t.datetime "lock_expires_at" t.string "unlock_token" t.text "first_name" t.text "last_name" t.integer "account_id" t.boolean "admin", :default => false t.boolean "reports_daily", :default => false t.boolean "reports_weekly", :default => false t.boolean "reports_monthly", :default => false t.boolean "change_password", :default => false end add_index "users", ["account_id"], :name => "index_users_on_account_id" add_index "users", ["last_logout_at", "last_activity_at"], :name => "index_accounts_on_last_logout_at_and_last_activity_at" add_index "users", ["remember_me_token"], :name => "index_accounts_on_remember_me_token" add_index "users", ["reset_password_token"], :name => "index_accounts_on_reset_password_token" end
43.116667
135
0.633166
18a2ae2ff6738bcf1c0954f389161ee08baf81ae
1,119
require 'digest/md5' require 'digest/sha1' require 'digest/sha2' require 'rickshaw/version' require 'core_ext/string/to_md5' require 'core_ext/string/to_sha1' require 'core_ext/string/to_sha256' require 'core_ext/string/to_sha512' require 'core_ext/string/to_base64' require 'core_ext/string/byte_packing' module Rickshaw module MD5 def self.hash(file_path) hash = Digest::MD5.new Rickshaw::Helper.hash_file(hash, file_path) end end module SHA1 def self.hash(file_path) hash = Digest::SHA1.new Rickshaw::Helper.hash_file(hash, file_path) end end module SHA256 def self.hash(file_path) hash = Digest::SHA256.new Rickshaw::Helper.hash_file(hash, file_path) end end module SHA512 def self.hash(file_path) hash = Digest::SHA512.new Rickshaw::Helper.hash_file(hash, file_path) end end module Helper def self.hash_file(hash, file_path) open(file_path, 'r') do |io| until io.eof? buffer = io.read(1024) hash.update(buffer) end end hash.hexdigest end end end
20.722222
49
0.67471
f84965233d2f39a81a51c3b8e144cdd1946301ab
147
require 'test/unit' class TabsHelperTest < Test::Unit::TestCase # Replace this with your real tests. def test_this_plugin flunk end end
16.333333
43
0.734694
08b1ccc7c1a0b3b4eda0c5a31f52b6c6f6bff825
1,980
require "test_helper" class DashboardTest < ActionDispatch::IntegrationTest setup do @user = create(:user, remember_token_expires_at: Gemcutter::REMEMBER_FOR.from_now) cookies[:remember_token] = @user.remember_token create(:rubygem, name: "arrakis", number: "1.0.0") end test "request with array of api keys does not pass autorization" do cookies[:remember_token] = nil rubygem = create(:rubygem, name: "sandworm", number: "1.0.0") create(:subscription, rubygem: rubygem, user: @user) get "/dashboard.atom?api_key=#{@user.api_key}", as: :json assert page.has_content? "sandworm" get "/dashboard.atom?api_key[]=#{@user.api_key}&api_key[]=key1", as: :json refute page.has_content? "sandworm" end test "gems I have pushed show on my dashboard" do rubygem = create(:rubygem, name: "sandworm", number: "1.0.0") create(:ownership, rubygem: rubygem, user: @user) get dashboard_path assert page.has_content? "sandworm" refute page.has_content?("arrakis") end test "gems I have subscribed to show on my dashboard" do rubygem = create(:rubygem, name: "sandworm", number: "1.0.0") create(:subscription, rubygem: rubygem, user: @user) get dashboard_path assert page.has_content? "sandworm" refute page.has_content?("arrakis") end test "dashboard with a non valid format" do assert_raises(ActionController::RoutingError) do get dashboard_path(format: :json) end end test "dashboard with atom format" do rubygem = create(:rubygem, name: "sandworm", number: "1.0.0") create(:subscription, rubygem: rubygem, user: @user) get dashboard_path(format: :atom) assert_response :success assert_equal "application/atom+xml", response.media_type assert page.has_content? "sandworm" end test "shows announcements on dashboard" do Announcement.create!(body: "hello w.") get dashboard_path assert page.has_content?("hello w.") end end
30.461538
86
0.698485
3958f8845ddc8a1db5966eb5f5f0249fb4ce5f89
416
class Setting < ActiveRecord::Base def self.data_attributes [:hostname, :site_name, :juvia_site_key, :juvia_server_url, :juvia_include_css, :juvia_comment_order, :api_throttle_per_minute, :mail_sender, :mail_address, :mail_port, :mail_domain, :mail_authentication, :mail_user_name, :mail_password, :exception_recipients, :artifacts_per_page] end store_accessor :data, Setting.data_attributes end
46.222222
131
0.790865
08a5a597d6f9226b2e0a1d961c31c73df010e23f
897
require 'spec_helper' describe 'mysql_client_test::default on omnios-151014' do cached(:omnios_client_55) do ChefSpec::SoloRunner.new( platform: 'omnios', version: '151014', step_into: 'mysql_client' ) do |node| node.set['mysql']['version'] = '5.5' end.converge('mysql_client_test::default') end # Resource in mysql_client_test::default context 'compiling the test recipe' do it 'creates mysql_client[default]' do expect(omnios_client_55).to create_mysql_client('default') end end # mysql_service resource internal implementation context 'stepping into mysql_client[default] resource' do it 'installs package[default :create database/mysql-55/library]' do expect(omnios_client_55).to install_package('default :create database/mysql-55/library') .with(package_name: 'database/mysql-55/library') end end end
30.931034
94
0.714604
6244f2c9f6ea0f6473d0773099060f14b9266a15
1,961
require 'linked_list_functions/challenges' RSpec.describe 'linked list functions' do describe 'list_min' do it 'returns nil for the empty list' do list = LinkedList.new assert_equal nil, list_min(list) end it 'returns the first item when there is only one' do list = LinkedList.new(Node.new("a", nil)) assert_equal "a", list_min(list) end describe 'returns the item that is less than the others, when there is more than one' do example '("a" -> "b" -> "c") returns "a"' do list = LinkedList.new(Node.new("a", Node.new("b", Node.new("c", nil)))) assert_equal "a", list_min(list) end example '("a" -> "c" -> "b") returns "a"' do list = LinkedList.new Node.new("a", Node.new("c", Node.new("b", nil))) assert_equal "a", list_min(list) end example '("b" -> "a" -> "c") returns "a"' do list = LinkedList.new Node.new("b", Node.new("a", Node.new("c", nil))) assert_equal "a", list_min(list) end example '("b" -> "c" -> "a") returns "a"' do list = LinkedList.new Node.new("b", Node.new("c", Node.new("a", nil))) assert_equal "a", list_min(list) end example '("c" -> "b" -> "a") returns "a"' do list = LinkedList.new Node.new("c", Node.new("b", Node.new("a", nil))) assert_equal "a", list_min(list) end example '("c" -> "a" -> "b") returns "a"' do list = LinkedList.new Node.new("c", Node.new("a", Node.new("b", nil))) assert_equal "a", list_min(list) end example '(100 -> 45 -> 300) returns 45' do list = LinkedList.new Node.new(100, Node.new(45, Node.new(300, nil))) assert_equal 45, list_min(list) end example 'A larger example' do list = LinkedList.new Node.new(100, Node.new(45, Node.new(300, Node.new(742, Node.new(15, nil))))) assert_equal 15, list_min(list) end end end end
33.237288
106
0.569607
ed60a16140a50e49f60473655c2dd2b4a41b00e0
441
module CarrerasHelper def link_to_editar_carrera(carrera) render partial: 'link_to_editar_carrera', locals: { carrera: carrera } end def link_to_carrera_detalle(carrera_id) render partial: 'link_to_carrera_detalle', locals: { carrera_id: carrera_id } end def link_to_puntaje_carrera(carrera_id) render partial: 'link_to_puntaje_carrera', locals: { carrera_id: carrera_id } end end
20.045455
83
0.714286
26fe10bdfb52b73667b08bf1a1800657b5c54004
3,892
require "test_helper" # users interests class InterestControllerTest < FunctionalTestCase # Test list feature from left-hand column. def test_list_interests login("rolf") Interest.create(target: observations(:minimal_unknown_obs), user: rolf, state: true) Interest.create(target: names(:agaricus_campestris), user: rolf, state: true) get_with_dump(:list_interests) assert_template("list_interests") end def test_set_interest_another_user login("rolf") get(:set_interest, type: "Observation", id: observations(:minimal_unknown_obs), user: mary.id) assert_flash_error end def test_set_interest_no_object login("rolf") assert_raises(ActiveRecord::RecordNotFound) do get(:set_interest, type: "Observation", id: 100, state: 1) end end def test_set_interest_bad_type login("rolf") assert_raises(NameError) do get(:set_interest, type: "Bogus", id: 1, state: 1) end end def test_set_interest peltigera = names(:peltigera) minimal_unknown = observations(:minimal_unknown_obs) detailed_unknown = observations(:detailed_unknown_obs) # Succeed: Turn interest on in minimal_unknown. login("rolf") get(:set_interest, type: "Observation", id: minimal_unknown.id, state: 1, user: rolf.id) assert_flash_success # Make sure rolf now has one Interest: interested in minimal_unknown. rolfs_interests = Interest.where(user_id: rolf.id) assert_equal(1, rolfs_interests.length) assert_equal(minimal_unknown, rolfs_interests.first.target) assert_equal(true, rolfs_interests.first.state) # Succeed: Turn same interest off. login("rolf") get(:set_interest, type: "Observation", id: minimal_unknown.id, state: -1) assert_flash_success # Make sure rolf now has one Interest: NOT interested in minimal_unknown. rolfs_interests = Interest.where(user_id: rolf.id) assert_equal(1, rolfs_interests.length) assert_equal(minimal_unknown, rolfs_interests.first.target) assert_equal(false, rolfs_interests.first.state) # Succeed: Turn another interest off from no interest. login("rolf") get(:set_interest, type: "Name", id: peltigera.id, state: -1) assert_flash_success # Make sure rolf now has two Interests. rolfs_interests = Interest.where(user_id: rolf.id) assert_equal(2, rolfs_interests.length) assert_equal(minimal_unknown, rolfs_interests.first.target) assert_equal(false, rolfs_interests.first.state) assert_equal(peltigera, rolfs_interests.last.target) assert_equal(false, rolfs_interests.last.state) # Succeed: Delete interest in existing object that rolf hasn't expressed # interest in yet. login("rolf") get(:set_interest, type: "Observation", id: detailed_unknown.id, state: 0) assert_flash_success assert_equal(2, Interest.where(user_id: rolf.id).length) # Succeed: Delete first interest now. login("rolf") get(:set_interest, type: "Observation", id: minimal_unknown.id, state: 0) assert_flash_success # Make sure rolf now has one Interest: NOT interested in peltigera. rolfs_interests = Interest.where(user_id: rolf.id) assert_equal(1, rolfs_interests.length) assert_equal(peltigera, rolfs_interests.last.target) assert_equal(false, rolfs_interests.last.state) # Succeed: Delete last interest. login("rolf") get(:set_interest, type: "Name", id: peltigera.id, state: 0) assert_flash_success assert_equal(0, Interest.where(user_id: rolf.id).length) end def test_destroy_notification login("rolf") n = notifications(:coprinus_comatus_notification) assert(n) id = n.id get(:destroy_notification, id: id) assert_raises(ActiveRecord::RecordNotFound) do Notification.find(id) end end end
33.843478
78
0.716341
285ebeafdecad93380353177cb2389ba45b2eb0d
7,711
require 'spec_helper' describe RailsExceptionHandler::Storage do render_views before(:each) do @handler = RailsExceptionHandler::Handler.new(create_env, create_exception) end it "should be able to use multiple storage strategies" do clear_test_log read_test_log.should == '' RailsExceptionHandler.configure { |config| config.storage_strategies = [:active_record, :mongoid, :rails_log] } @handler.handle_exception read_test_log.should match /undefined method `foo' for nil:NilClass/ RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 if defined?(Mongoid) end describe "active_record storage" do it "should store an error message in the database when storage_strategies includes :active_record" do RailsExceptionHandler.configure { |config| config.storage_strategies = [:active_record] } @handler.handle_exception RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 1 msg = RailsExceptionHandler::ActiveRecord::ErrorMessage.first msg.app_name.should == 'ExceptionHandlerTestApp' msg.class_name.should == 'NoMethodError' msg.message.should include "undefined method `foo' for nil:NilClass" msg.trace.should match /spec\/test_macros\.rb:28/ msg.params.should match /\"foo\"=>\"bar\"/ msg.user_agent.should == 'Mozilla/4.0 (compatible; MSIE 8.0)' msg.target_url.should == 'http://example.org/home?foo=bar' msg.referer_url.should == 'http://google.com/' msg.created_at.should be > 5.seconds.ago msg.created_at.should be < Time.now end it "should not store an error message in the database when storage_strategies does not include :active_record" do RailsExceptionHandler.configure { |config| config.storage_strategies = [] } RailsExceptionHandler::ActiveRecord::ErrorMessage.count.should == 0 end end describe "mongoid storage" do it "should store an error message in the database when storage_strategies includes :mongoid" do RailsExceptionHandler.configure { |config| config.storage_strategies = [:mongoid] } @handler.handle_exception if defined?(Mongoid) RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 1 msg = RailsExceptionHandler::Mongoid::ErrorMessage.first msg.app_name.should == 'ExceptionHandlerTestApp' msg.class_name.should == 'NoMethodError' msg.message.should include "undefined method `foo' for nil:NilClass" msg.trace.should match /spec\/test_macros\.rb:28/ msg.params.should match /\"foo\"=>\"bar\"/ msg.user_agent.should == 'Mozilla/4.0 (compatible; MSIE 8.0)' msg.target_url.should == 'http://example.org/home?foo=bar' msg.referer_url.should == 'http://google.com/' msg.created_at.should be > 5.seconds.ago msg.created_at.should be < Time.now end end it "should not store an error message in the database when storage_strategies does not include :mongoid" do RailsExceptionHandler.configure { |config| config.storage_strategies = [] } RailsExceptionHandler::Mongoid::ErrorMessage.count.should == 0 if defined?(Mongoid) end end describe 'rails_log storage' do it "it should log an error to the rails log when storage_strategies includes :rails_log" do clear_test_log read_test_log.should == '' RailsExceptionHandler.configure { |config| config.storage_strategies = [:rails_log] } @handler.handle_exception read_test_log.should match /undefined method `foo' for nil:NilClass/ read_test_log.should match /spec\/test_macros\.rb:28/ read_test_log.should match /PARAMS:\s+\{\"foo\"=>\"bar\"\}/ read_test_log.should match /USER_AGENT:\s+Mozilla\/4.0 \(compatible; MSIE 8\.0\)/ read_test_log.should match /TARGET_URL: http:\/\/example\.org\/home\?foo=bar/ read_test_log.should match /REFERER_URL: http:\/\/google\.com\// end it "should not log an error to the rails log when storage_strategies does not include :rails_log" do clear_test_log read_test_log.should == '' RailsExceptionHandler.configure { |config| config.storage_strategies = [] } @handler.handle_exception if Rails::VERSION::MAJOR > 4 read_test_log.should match /Rendering html template within layouts\/application/ elsif Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR > 0 read_test_log.should match /Rendered text template within layouts\/fallback/ elsif Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR == 0 read_test_log.should match /Rendered text template within layouts\/application/ else read_test_log.should == '' end end end describe 'remote_url storage' do it "should send the error_message as an HTTP POST request when :remote_url is included" do Time.stub(:now => Time.now) # Otherwise the timestamps will be different, and comparison fail @handler.handle_exception parser = @handler.instance_variable_get(:@parsed_error) RailsExceptionHandler.configure { |config| config.storage_strategies = [:remote_url => {:target => 'http://example.com/error_messages'}] } uri = URI.parse('http://example.com/error_messages') params = RailsExceptionHandler::Storage.send(:flatten_hash, { :error_message => parser.external_info }) Net::HTTP.should_receive(:post_form).with(uri, params) @handler.handle_exception end it "should not send the error_message as an HTTP POST request when :remote_url is not included" do RailsExceptionHandler.configure { |config| config.storage_strategies = [] } Net::HTTP.should_not_receive(:post_form) @handler.handle_exception end end describe 'email storage' do it "should send the error_message as an email :email is included" do RailsExceptionHandler.configure { |config| config.storage_strategies = [:email => {:recipients => "[email protected]"}] } @handler.handle_exception ActionMailer::Base.deliveries.length.should == 1 email = ActionMailer::Base.deliveries.first email.to.should == ['[email protected]'] text_body = email.body.parts.first.to_s text_body.should include('TARGET_URL') text_body.should include('http://example.org/home?foo=bar') text_body.should include("undefined method `foo") html_body = email.body.parts.last.to_s html_body.should include('TARGET_URL') html_body.should include('http://example.org/home?foo=bar') html_body.should include("undefined method `foo") end it "should not send the error_message as an email when :email is not included" do RailsExceptionHandler.configure { |config| config.storage_strategies = [] } @handler.handle_exception ActionMailer::Base.deliveries.length.should == 0 end it "should not send to blank recipients" do [nil, "", [] ].each do |value| RailsExceptionHandler.configure { |config| config.storage_strategies = [:email => {:recipients => value}] } @handler.handle_exception ActionMailer::Base.deliveries.length.should == 0 end end it "should allow multiple receivers" do RailsExceptionHandler.configure { |config| config.storage_strategies = [:email => {:recipients => "[email protected],[email protected]"}] } @handler.handle_exception ActionMailer::Base.deliveries.length.should == 1 email = ActionMailer::Base.deliveries.first email.to.should == ['[email protected]','[email protected]'] end end end
48.19375
144
0.700817