_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q16200
Azure::ARM.VnetConfig.divide_network
train
def divide_network(address_prefix) network_address = IPAddress(address_prefix) prefix = nil case network_address.count when 4097..65536 prefix = "20" when 256..4096 prefix = "24" end ## if the given network is small then do not divide it else divide using ## the prefix value calculated above ## prefix.nil? ? address_prefix : network_address.network.address.concat("/" + prefix) end
ruby
{ "resource": "" }
q16201
Azure::ARM.VnetConfig.new_subnet_address_prefix
train
def new_subnet_address_prefix(vnet_address_prefix, subnets) if subnets.empty? ## no subnets exist in the given address space of the virtual network, so divide the network into smaller subnets (based on the network size) and allocate space for the new subnet to be added ## divide_network(vnet_address_prefix) else ## subnets exist in vnet, calculate new address_prefix for the new subnet based on the space taken by these existing subnets under the given address space of the virtual network ## vnet_network_address = IPAddress(vnet_address_prefix) subnets = sort_subnets_by_cidr_prefix(subnets) available_networks_pool = Array.new used_networks_pool = Array.new subnets.each do |subnet| ## in case the larger network is not divided into smaller subnets but ## divided into only 1 largest subnet of the complete network size ## if vnet_network_address.prefix == subnet_cidr_prefix(subnet) break end ## add all the possible subnets (calculated using the current subnet's ## cidr prefix value) into the available_networks_pool ## available_networks_pool.push( vnet_network_address.subnet(subnet_cidr_prefix(subnet)) ).flatten!.uniq! { |nwrk| [ nwrk.network.address, nwrk.prefix ].join(":") } ## add current subnet into the used_networks_pool ## used_networks_pool.push( IPAddress(subnet_address_prefix(subnet)) ) ## sort both the network pools before trimming the available_networks_pool ## available_networks_pool, used_networks_pool = sort_pools( available_networks_pool, used_networks_pool) ## trim the available_networks_pool based on the networks already ## allocated to the existing subnets ## used_networks_pool.each do |subnet_network| available_networks_pool.delete_if do |available_network| in_use_network?(subnet_network, available_network) end end ## sort both the network pools after trimming the available_networks_pool ## available_networks_pool, used_networks_pool = sort_pools( available_networks_pool, used_networks_pool) end ## space available in the vnet_address_prefix network for the new subnet ## if !available_networks_pool.empty? && available_networks_pool.first.network? available_networks_pool.first.network.address.concat("/" + available_networks_pool.first.prefix.to_s) else ## space not available in the vnet_address_prefix network for the new subnet ## nil end end end
ruby
{ "resource": "" }
q16202
Azure::ARM.VnetConfig.add_subnet
train
def add_subnet(subnet_name, vnet_config, subnets) new_subnet_prefix = nil vnet_address_prefix_count = 0 vnet_address_space = vnet_config[:addressPrefixes] ## search for space in all the address prefixes of the virtual network ## while new_subnet_prefix.nil? && vnet_address_space.length > vnet_address_prefix_count new_subnet_prefix = new_subnet_address_prefix( vnet_address_space[vnet_address_prefix_count], subnets_list_for_specific_address_space( vnet_address_space[vnet_address_prefix_count], subnets ) ) vnet_address_prefix_count += 1 end if new_subnet_prefix ## found space for new subnet ## vnet_config[:subnets].push( subnet(subnet_name, new_subnet_prefix) ) else ## no space available in the virtual network for the new subnet ## raise "Unable to add subnet #{subnet_name} into the virtual network #{vnet_config[:virtualNetworkName]}, no address space available !!!" end vnet_config end
ruby
{ "resource": "" }
q16203
Azure::ARM.VnetConfig.create_vnet_config
train
def create_vnet_config(resource_group_name, vnet_name, vnet_subnet_name) raise ArgumentError, "GatewaySubnet cannot be used as the name for --azure-vnet-subnet-name option. GatewaySubnet can only be used for virtual network gateways." if vnet_subnet_name == "GatewaySubnet" vnet_config = {} subnets = nil flag = true ## check whether user passed or default named virtual network exist or not ## vnet = get_vnet(resource_group_name, vnet_name) vnet_config[:virtualNetworkName] = vnet_name if vnet ## handle resources in the existing virtual network ## vnet_config[:addressPrefixes] = vnet_address_spaces(vnet) vnet_config[:subnets] = Array.new subnets = subnets_list(resource_group_name, vnet_name) if subnets subnets.each do |subnet| flag = false if subnet.name == vnet_subnet_name ## given subnet already exist in the virtual network ## ## preserve the existing subnet resources ## vnet_config[:subnets].push( subnet(subnet.name, subnet_address_prefix(subnet)) ) end end else ## create config for new vnet ## vnet_config[:addressPrefixes] = [ "10.0.0.0/16" ] vnet_config[:subnets] = Array.new vnet_config[:subnets].push( subnet(vnet_subnet_name, "10.0.0.0/24") ) flag = false end ## given subnet does not exist, so create new one in the virtual network ## vnet_config = add_subnet(vnet_subnet_name, vnet_config, subnets) if flag vnet_config end
ruby
{ "resource": "" }
q16204
Azure.Hosts.fetch_from_cloud
train
def fetch_from_cloud(name) ret_val = @connection.query_azure("hostedservices/#{name}") error_code, error_message = error_from_response_xml(ret_val) if ret_val if ret_val.nil? || error_code.length > 0 Chef::Log.warn("Unable to find hosted(cloud) service:" + error_code + " : " + error_message) if ret_val nil else Host.new(@connection).parse(ret_val) end end
ruby
{ "resource": "" }
q16205
PublicSuffix.List.each
train
def each(&block) Enumerator.new do |y| @rules.each do |key, node| y << entry_to_rule(node, key) end end.each(&block) end
ruby
{ "resource": "" }
q16206
PublicSuffix.List.find
train
def find(name, default: default_rule, **options) rule = select(name, **options).inject do |l, r| return r if r.class == Rule::Exception l.length > r.length ? l : r end rule || default end
ruby
{ "resource": "" }
q16207
PublicSuffix.List.select
train
def select(name, ignore_private: false) name = name.to_s parts = name.split(DOT).reverse! index = 0 query = parts[index] rules = [] loop do match = @rules[query] rules << entry_to_rule(match, query) if !match.nil? && (ignore_private == false || match.private == false) index += 1 break if index >= parts.size query = parts[index] + DOT + query end rules end
ruby
{ "resource": "" }
q16208
Minicron.Monitor.start!
train
def start! # Activate the monitor @active = true # Connect to the database Minicron.establish_db_connection( Minicron.config['server']['database'], Minicron.config['verbose'] ) # Set the start time of the monitir @start_time = Time.now.utc # Start a thread for the monitor @thread = Thread.new do # While the monitor is active run it in a loop ~every minute while @active # Get all the schedules schedules = Minicron::Hub::Model::Schedule.all # Loop every schedule we know about schedules.each do |schedule| begin # TODO: is it possible to monitor on boot schedules some other way? monitor(schedule) unless schedule.special == '@reboot' rescue Exception => e if Minicron.config['debug'] puts e.message puts e.backtrace end end end sleep 59 end end end
ruby
{ "resource": "" }
q16209
Minicron.Monitor.monitor
train
def monitor(schedule) # Parse the cron expression cron = CronParser.new(schedule.formatted) # Find the time the cron was last expected to run with a 30 second pre buffer # and a 30 second post buffer (in addition to the 60 already in place) incase # jobs run early/late to allow for clock sync differences between client/hub expected_at = cron.last(Time.now.utc) - 30 expected_by = expected_at + 30 + 60 + 30 # pre buffer + minute wait + post buffer # We only need to check jobs that are expected after the monitor start time # and jobs that have passed their expected by time and the time the schedule # was last updated isn't before when it was expected, i.e we aren't checking for something # that should have happened earlier in the day. if expected_at > @start_time && Time.now.utc > expected_by && expected_by > schedule.updated_at # Check if this execution was created inside a minute window # starting when it was expected to run check = Minicron::Hub::Model::Execution.exists?( created_at: expected_at..expected_by, job_id: schedule.job_id ) # If the check failed unless check Minicron::Alert.send_all( user_id: schedule.user_id, kind: 'miss', schedule_id: schedule.id, expected_at: expected_at, job_id: schedule.job_id ) end end end
ruby
{ "resource": "" }
q16210
Minicron.Cron.build_crontab
train
def build_crontab(host) # You have been warned.. crontab = "#\n" crontab += "# This file was automatically generated by minicron at #{Time.now.utc}, DO NOT EDIT manually!\n" crontab += "#\n\n" # Set the path to something sensible by default, eventually this should be configurable crontab += "# ENV variables\n" crontab += "PATH=#{PATH}\n" crontab += "MAILTO=\"\"\n" crontab += "\n" # Add an entry to the crontab for each job schedule unless host.nil? host.jobs.each do |job| crontab += "# ID: #{job.id}\n" crontab += "# Name: #{job.name}\n" crontab += "# Status: #{job.status}\n" if !job.schedules.empty? job.schedules.each do |schedule| crontab += "\t" crontab += '# ' unless job.enabled # comment out schedule if job isn't enabled crontab += "#{build_minicron_command(schedule.formatted, job.command)}\n" end else crontab += "\t# No schedules exist for this job\n" end crontab += "\n" end end crontab end
ruby
{ "resource": "" }
q16211
MetaInspector.URL.with_default_scheme
train
def with_default_scheme(url) parsed(url) && parsed(url).scheme.nil? ? 'http://' + url : url end
ruby
{ "resource": "" }
q16212
MetaInspector.URL.normalized
train
def normalized(url) Addressable::URI.parse(url).normalize.to_s rescue Addressable::URI::InvalidURIError => e raise MetaInspector::ParserError.new(e) end
ruby
{ "resource": "" }
q16213
MetaInspector.Document.to_hash
train
def to_hash { 'url' => url, 'scheme' => scheme, 'host' => host, 'root_url' => root_url, 'title' => title, 'best_title' => best_title, 'author' => author, 'best_author' => best_author, 'description' => description, 'best_description' => best_description, 'links' => links.to_hash, 'images' => images.to_a, 'charset' => charset, 'feed' => feed, 'content_type' => content_type, 'meta_tags' => meta_tags, 'favicon' => images.favicon, 'response' => { 'status' => response.status, 'headers' => response.headers } } end
ruby
{ "resource": "" }
q16214
GLI.Command.has_option?
train
def has_option?(option) #:nodoc: option = option.gsub(/^\-+/,'') ((flags.values.map { |_| [_.name,_.aliases] }) + (switches.values.map { |_| [_.name,_.aliases] })).flatten.map(&:to_s).include?(option) end
ruby
{ "resource": "" }
q16215
GLI.Command.name_for_help
train
def name_for_help name_array = [name.to_s] command_parent = parent while(command_parent.is_a?(GLI::Command)) do name_array.unshift(command_parent.name.to_s) command_parent = command_parent.parent end name_array end
ruby
{ "resource": "" }
q16216
GLI.App.commands_from
train
def commands_from(path) if Pathname.new(path).absolute? and File.exist?(path) load_commands(path) else $LOAD_PATH.each do |load_path| commands_path = File.join(load_path,path) load_commands(commands_path) end end end
ruby
{ "resource": "" }
q16217
GLI.App.config_file
train
def config_file(filename) if filename =~ /^\// @config_file = filename else @config_file = File.join(File.expand_path(ENV['HOME']),filename) end commands[:initconfig] = InitConfig.new(@config_file,commands,flags,switches) @commands_declaration_order << commands[:initconfig] @config_file end
ruby
{ "resource": "" }
q16218
GLI.AppSupport.reset
train
def reset # :nodoc: switches.clear flags.clear @commands = nil @commands_declaration_order = [] @flags_declaration_order = [] @switches_declaration_order = [] @version = nil @config_file = nil @use_openstruct = false @prog_desc = nil @error_block = false @pre_block = false @post_block = false @default_command = :help @autocomplete = false @around_block = nil @subcommand_option_handling_strategy = :legacy @argument_handling_strategy = :loose clear_nexts end
ruby
{ "resource": "" }
q16219
GLI.AppSupport.run
train
def run(args) #:nodoc: args = args.dup if @preserve_argv the_command = nil begin override_defaults_based_on_config(parse_config) add_help_switch_if_needed(self) gli_option_parser = GLIOptionParser.new(commands, flags, switches, accepts, :default_command => @default_command, :autocomplete => autocomplete, :subcommand_option_handling_strategy => subcommand_option_handling_strategy, :argument_handling_strategy => argument_handling_strategy) parsing_result = gli_option_parser.parse_options(args) parsing_result.convert_to_openstruct! if @use_openstruct the_command = parsing_result.command if proceed?(parsing_result) call_command(parsing_result) 0 else raise PreconditionFailed, "preconditions failed" end rescue Exception => ex if the_command.nil? && ex.respond_to?(:command_in_context) the_command = ex.command_in_context end handle_exception(ex,the_command) end end
ruby
{ "resource": "" }
q16220
GLI.AppSupport.override_defaults_based_on_config
train
def override_defaults_based_on_config(config) override_default(flags,config) override_default(switches,config) override_command_defaults(commands,config) end
ruby
{ "resource": "" }
q16221
GLI.AppSupport.proceed?
train
def proceed?(parsing_result) #:nodoc: if parsing_result.command && parsing_result.command.skips_pre true else pre_block.call(*parsing_result) end end
ruby
{ "resource": "" }
q16222
GLI.AppSupport.regular_error_handling?
train
def regular_error_handling?(ex) #:nodoc: if @error_block return true if (ex.respond_to?(:exit_code) && ex.exit_code == 0) @error_block.call(ex) else true end end
ruby
{ "resource": "" }
q16223
GLI.DSL.flag
train
def flag(*names) options = extract_options(names) names = [names].flatten verify_unused(names) flag = Flag.new(names,options) flags[flag.name] = flag clear_nexts flags_declaration_order << flag flag end
ruby
{ "resource": "" }
q16224
GLI.DSL.verify_unused
train
def verify_unused(names) # :nodoc: names.each do |name| verify_unused_in_option(name,flags,"flag") verify_unused_in_option(name,switches,"switch") end end
ruby
{ "resource": "" }
q16225
GLI.GLIOptionParser.parse_options
train
def parse_options(args) # :nodoc: option_parser_class = self.class.const_get("#{options[:subcommand_option_handling_strategy].to_s.capitalize}CommandOptionParser") OptionParsingResult.new.tap { |parsing_result| parsing_result.arguments = args parsing_result = @global_option_parser.parse!(parsing_result) option_parser_class.new(@accepts).parse!(parsing_result, options[:argument_handling_strategy]) } end
ruby
{ "resource": "" }
q16226
GLI.GLIOptionBlockParser.parse!
train
def parse!(args) do_parse(args) rescue OptionParser::InvalidOption => ex @exception_handler.call("Unknown option #{ex.args.join(' ')}",@extra_error_context) rescue OptionParser::InvalidArgument => ex @exception_handler.call("#{ex.reason}: #{ex.args.join(' ')}",@extra_error_context) end
ruby
{ "resource": "" }
q16227
GLI.CommandLineToken.parse_names
train
def parse_names(names) # Allow strings; convert to symbols names = [names].flatten.map { |name| name.to_sym } names_hash = {} names.each do |name| raise ArgumentError.new("#{name} has spaces; they are not allowed") if name.to_s =~ /\s/ names_hash[self.class.name_as_string(name)] = true end name = names.shift aliases = names.length > 0 ? names : nil [name,aliases,names_hash] end
ruby
{ "resource": "" }
q16228
GLI.Flag.all_forms
train
def all_forms(joiner=', ') forms = all_forms_a string = forms.join(joiner) if forms[-1] =~ /^\-\-/ string += '=' else string += ' ' end string += @argument_name return string end
ruby
{ "resource": "" }
q16229
Hamlbars.Template.evaluate
train
def evaluate(scope, locals, &block) if @engine.respond_to?(:precompiled_method_return_value, true) super(scope, locals, &block) else @engine.render(scope, locals, &block) end end
ruby
{ "resource": "" }
q16230
Webshot.Screenshot.capture
train
def capture(url, path, opts = {}) begin # Default settings width = opts.fetch(:width, 120) height = opts.fetch(:height, 90) gravity = opts.fetch(:gravity, "north") quality = opts.fetch(:quality, 85) full = opts.fetch(:full, true) selector = opts.fetch(:selector, nil) allowed_status_codes = opts.fetch(:allowed_status_codes, []) # Reset session before visiting url Capybara.reset_sessions! unless @session_started @session_started = false # Open page visit url # Timeout sleep opts[:timeout] if opts[:timeout] # Check response code status_code = page.driver.status_code.to_i unless valid_status_code?(status_code, allowed_status_codes) fail WebshotError, "Could not fetch page: #{url.inspect}, error code: #{page.driver.status_code}" end tmp = Tempfile.new(["webshot", ".png"]) tmp.close begin screenshot_opts = { full: full } screenshot_opts = screenshot_opts.merge({ selector: selector }) if selector # Save screenshot to file page.driver.save_screenshot(tmp.path, screenshot_opts) # Resize screenshot thumb = MiniMagick::Image.open(tmp.path) if block_given? # Customize MiniMagick options yield thumb else thumb.combine_options do |c| c.thumbnail "#{width}x" c.background "white" c.extent "#{width}x#{height}" c.gravity gravity c.quality quality end end # Save thumbnail thumb.write path thumb ensure tmp.unlink end rescue Capybara::Poltergeist::StatusFailError, Capybara::Poltergeist::BrowserError, Capybara::Poltergeist::DeadClient, Capybara::Poltergeist::TimeoutError, Errno::EPIPE => e # TODO: Handle Errno::EPIPE and Errno::ECONNRESET raise WebshotError.new("Capybara error: #{e.message.inspect}") end end
ruby
{ "resource": "" }
q16231
ActiveStorageDragAndDrop.FormBuilder.drag_and_drop_file_field
train
def drag_and_drop_file_field(method, content_or_options = nil, options = {}, &block) if block_given? options = content_or_options if content_or_options.is_a? Hash drag_and_drop_file_field_string(method, capture(&block), options) else drag_and_drop_file_field_string(method, content_or_options, options) end end
ruby
{ "resource": "" }
q16232
ActiveStorageDragAndDrop.FormBuilder.unpersisted_attachment_fields
train
def unpersisted_attachment_fields(method, multiple) unpersisted_attachments(method).map.with_index do |attachment, idx| hidden_field method, mutiple: multiple ? :multiple : false, value: attachment.signed_id, name: "#{object_name}[#{method}]#{'[]' if multiple}", data: { direct_upload_id: idx, uploaded_file: { name: attachment.filename, size: attachment.byte_size }, icon_container_id: "asdndz-#{object_name}_#{method}__icon-container" } end end
ruby
{ "resource": "" }
q16233
ActiveStorageDragAndDrop.FormBuilder.default_file_field_options
train
def default_file_field_options(method) { multiple: @object.send(method).is_a?(ActiveStorage::Attached::Many), direct_upload: true, style: 'display:none;', data: { dnd: true, dnd_zone_id: "asdndz-#{object_name}_#{method}", icon_container_id: "asdndz-#{object_name}_#{method}__icon-container" } } end
ruby
{ "resource": "" }
q16234
ActiveStorageDragAndDrop.FormBuilder.file_field_options
train
def file_field_options(method, custom_options) default_file_field_options(method).merge(custom_options) do |_key, default, custom| default.is_a?(Hash) && custom.is_a?(Hash) ? default.merge(custom) : custom end end
ruby
{ "resource": "" }
q16235
StateMachines.State.value
train
def value(eval = true) if @value.is_a?(Proc) && eval if cache_value? @value = @value.call machine.states.update(self) @value else @value.call end else @value end end
ruby
{ "resource": "" }
q16236
StateMachines.State.context_methods
train
def context_methods @context.instance_methods.inject({}) do |methods, name| methods.merge(name.to_sym => @context.instance_method(name)) end end
ruby
{ "resource": "" }
q16237
StateMachines.State.call
train
def call(object, method, *args, &block) options = args.last.is_a?(Hash) ? args.pop : {} options = {:method_name => method}.merge(options) state = machine.states.match!(object) if state == self && object.respond_to?(method) object.send(method, *args, &block) elsif method_missing = options[:method_missing] # Dispatch to the superclass since the object either isn't in this state # or this state doesn't handle the method begin method_missing.call rescue NoMethodError => ex if ex.name.to_s == options[:method_name].to_s && ex.args == args # No valid context for this method raise InvalidContext.new(object, "State #{state.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{options[:method_name]}") else raise end end end end
ruby
{ "resource": "" }
q16238
StateMachines.State.add_predicate
train
def add_predicate # Checks whether the current value matches this state machine.define_helper(:instance, "#{qualified_name}?") do |machine, object| machine.states.matches?(object, name) end end
ruby
{ "resource": "" }
q16239
StateMachines.Machine.initial_state=
train
def initial_state=(new_initial_state) @initial_state = new_initial_state add_states([@initial_state]) unless dynamic_initial_state? # Update all states to reflect the new initial state states.each { |state| state.initial = (state.name == @initial_state) } # Output a warning if there are conflicting initial states for the machine's # attribute initial_state = states.detect { |state| state.initial } if !owner_class_attribute_default.nil? && (dynamic_initial_state? || !owner_class_attribute_default_matches?(initial_state)) warn( "Both #{owner_class.name} and its #{name.inspect} machine have defined "\ "a different default for \"#{attribute}\". Use only one or the other for "\ "defining defaults to avoid unexpected behaviors." ) end end
ruby
{ "resource": "" }
q16240
StateMachines.Machine.initialize_state
train
def initialize_state(object, options = {}) state = initial_state(object) if state && (options[:force] || initialize_state?(object)) value = state.value if hash = options[:to] hash[attribute.to_s] = value else write(object, :state, value) end end end
ruby
{ "resource": "" }
q16241
StateMachines.Machine.define_helper
train
def define_helper(scope, method, *args, &block) helper_module = @helper_modules.fetch(scope) if block_given? if !self.class.ignore_method_conflicts && conflicting_ancestor = owner_class_ancestor_has_method?(scope, method) ancestor_name = conflicting_ancestor.name && !conflicting_ancestor.name.empty? ? conflicting_ancestor.name : conflicting_ancestor.to_s warn "#{scope == :class ? 'Class' : 'Instance'} method \"#{method}\" is already defined in #{ancestor_name}, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true." else name = self.name helper_module.class_eval do define_method(method) do |*block_args| block.call((scope == :instance ? self.class : self).state_machine(name), self, *block_args) end end end else helper_module.class_eval(method, *args) end end
ruby
{ "resource": "" }
q16242
StateMachines.Machine.state
train
def state(*names, &block) options = names.last.is_a?(Hash) ? names.pop : {} options.assert_valid_keys(:value, :cache, :if, :human_name) # Store the context so that it can be used for / matched against any state # that gets added @states.context(names, &block) if block_given? if names.first.is_a?(Matcher) # Add any states referenced in the matcher. When matchers are used, # states are not allowed to be configured. raise ArgumentError, "Cannot configure states when using matchers (using #{options.inspect})" if options.any? states = add_states(names.first.values) else states = add_states(names) # Update the configuration for the state(s) states.each do |state| if options.include?(:value) state.value = options[:value] self.states.update(state) end state.human_name = options[:human_name] if options.include?(:human_name) state.cache = options[:cache] if options.include?(:cache) state.matcher = options[:if] if options.include?(:if) end end states.length == 1 ? states.first : states end
ruby
{ "resource": "" }
q16243
StateMachines.Machine.read
train
def read(object, attribute, ivar = false) attribute = self.attribute(attribute) if ivar object.instance_variable_defined?("@#{attribute}") ? object.instance_variable_get("@#{attribute}") : nil else object.send(attribute) end end
ruby
{ "resource": "" }
q16244
StateMachines.Machine.write
train
def write(object, attribute, value, ivar = false) attribute = self.attribute(attribute) ivar ? object.instance_variable_set("@#{attribute}", value) : object.send("#{attribute}=", value) end
ruby
{ "resource": "" }
q16245
StateMachines.Machine.event
train
def event(*names, &block) options = names.last.is_a?(Hash) ? names.pop : {} options.assert_valid_keys(:human_name) # Store the context so that it can be used for / matched against any event # that gets added @events.context(names, &block) if block_given? if names.first.is_a?(Matcher) # Add any events referenced in the matcher. When matchers are used, # events are not allowed to be configured. raise ArgumentError, "Cannot configure events when using matchers (using #{options.inspect})" if options.any? events = add_events(names.first.values) else events = add_events(names) # Update the configuration for the event(s) events.each do |event| event.human_name = options[:human_name] if options.include?(:human_name) # Add any states that may have been referenced within the event add_states(event.known_states) end end events.length == 1 ? events.first : events end
ruby
{ "resource": "" }
q16246
StateMachines.Machine.transition
train
def transition(options) raise ArgumentError, 'Must specify :on event' unless options[:on] branches = [] options = options.dup event(*Array(options.delete(:on))) { branches << transition(options) } branches.length == 1 ? branches.first : branches end
ruby
{ "resource": "" }
q16247
StateMachines.Machine.generate_message
train
def generate_message(name, values = []) message = (@messages[name] || self.class.default_messages[name]) # Check whether there are actually any values to interpolate to avoid # any warnings if message.scan(/%./).any? { |match| match != '%%' } message % values.map { |value| value.last } else message end end
ruby
{ "resource": "" }
q16248
StateMachines.Machine.action_hook?
train
def action_hook?(self_only = false) @action_hook_defined || !self_only && owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self && machine.action_hook?(true) } end
ruby
{ "resource": "" }
q16249
StateMachines.Machine.sibling_machines
train
def sibling_machines owner_class.state_machines.inject([]) do |machines, (name, machine)| if machine.attribute == attribute && machine != self machines << (owner_class.state_machine(name) {}) end machines end end
ruby
{ "resource": "" }
q16250
StateMachines.Machine.initialize_state?
train
def initialize_state?(object) value = read(object, :state) (value.nil? || value.respond_to?(:empty?) && value.empty?) && !states[value, :value] end
ruby
{ "resource": "" }
q16251
StateMachines.Machine.define_path_helpers
train
def define_path_helpers # Gets the paths of transitions available to the current object define_helper(:instance, attribute(:paths)) do |machine, object, *args| machine.paths_for(object, *args) end end
ruby
{ "resource": "" }
q16252
StateMachines.Machine.define_action_helpers?
train
def define_action_helpers? action && !owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self } end
ruby
{ "resource": "" }
q16253
StateMachines.Machine.owner_class_ancestor_has_method?
train
def owner_class_ancestor_has_method?(scope, method) return false unless owner_class_has_method?(scope, method) superclasses = owner_class.ancestors.select { |ancestor| ancestor.is_a?(Class) }[1..-1] if scope == :class current = owner_class.singleton_class superclass = superclasses.first else current = owner_class superclass = owner_class.superclass end # Generate the list of modules that *only* occur in the owner class, but # were included *prior* to the helper modules, in addition to the # superclasses ancestors = current.ancestors - superclass.ancestors + superclasses ancestors = ancestors[ancestors.index(@helper_modules[scope])..-1].reverse # Search for for the first ancestor that defined this method ancestors.detect do |ancestor| ancestor = ancestor.singleton_class if scope == :class && ancestor.is_a?(Class) ancestor.method_defined?(method) || ancestor.private_method_defined?(method) end end
ruby
{ "resource": "" }
q16254
StateMachines.Machine.define_name_helpers
train
def define_name_helpers # Gets the humanized version of a state define_helper(:class, "human_#{attribute(:name)}") do |machine, klass, state| machine.states.fetch(state).human_name(klass) end # Gets the humanized version of an event define_helper(:class, "human_#{attribute(:event_name)}") do |machine, klass, event| machine.events.fetch(event).human_name(klass) end # Gets the state name for the current value define_helper(:instance, attribute(:name)) do |machine, object| machine.states.match!(object).name end # Gets the human state name for the current value define_helper(:instance, "human_#{attribute(:name)}") do |machine, object| machine.states.match!(object).human_name(object.class) end end
ruby
{ "resource": "" }
q16255
StateMachines.Machine.run_scope
train
def run_scope(scope, machine, klass, states) values = states.flatten.map { |state| machine.states.fetch(state).value } scope.call(klass, values) end
ruby
{ "resource": "" }
q16256
StateMachines.Machine.add_sibling_machine_configs
train
def add_sibling_machine_configs # Add existing states sibling_machines.each do |machine| machine.states.each { |state| states << state unless states[state.name] } end end
ruby
{ "resource": "" }
q16257
StateMachines.Machine.add_callback
train
def add_callback(type, options, &block) callbacks[type == :around ? :before : type] << callback = Callback.new(type, options, &block) add_states(callback.known_states) callback end
ruby
{ "resource": "" }
q16258
StateMachines.Machine.add_states
train
def add_states(new_states) new_states.map do |new_state| # Check for other states that use a different class type for their name. # This typically prevents string / symbol misuse. if new_state && conflict = states.detect { |state| state.name && state.name.class != new_state.class } raise ArgumentError, "#{new_state.inspect} state defined as #{new_state.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all states must be consistent" end unless state = states[new_state] states << state = State.new(self, new_state) # Copy states over to sibling machines sibling_machines.each { |machine| machine.states << state } end state end end
ruby
{ "resource": "" }
q16259
StateMachines.Machine.add_events
train
def add_events(new_events) new_events.map do |new_event| # Check for other states that use a different class type for their name. # This typically prevents string / symbol misuse. if conflict = events.detect { |event| event.name.class != new_event.class } raise ArgumentError, "#{new_event.inspect} event defined as #{new_event.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all events must be consistent" end unless event = events[new_event] events << event = Event.new(self, new_event) end event end end
ruby
{ "resource": "" }
q16260
StateMachines.StateCollection.match
train
def match(object) value = machine.read(object, :state) self[value, :value] || detect { |state| state.matches?(value) } end
ruby
{ "resource": "" }
q16261
StateMachines.Branch.build_matcher
train
def build_matcher(options, whitelist_option, blacklist_option) options.assert_exclusive_keys(whitelist_option, blacklist_option) if options.include?(whitelist_option) value = options[whitelist_option] value.is_a?(Matcher) ? value : WhitelistMatcher.new(options[whitelist_option]) elsif options.include?(blacklist_option) value = options[blacklist_option] raise ArgumentError, ":#{blacklist_option} option cannot use matchers; use :#{whitelist_option} instead" if value.is_a?(Matcher) BlacklistMatcher.new(value) else AllMatcher.instance end end
ruby
{ "resource": "" }
q16262
StateMachines.Branch.match_states
train
def match_states(query) state_requirements.detect do |state_requirement| [:from, :to].all? {|option| matches_requirement?(query, option, state_requirement[option])} end end
ruby
{ "resource": "" }
q16263
StateMachines.Branch.matches_requirement?
train
def matches_requirement?(query, option, requirement) !query.include?(option) || requirement.matches?(query[option], query) end
ruby
{ "resource": "" }
q16264
StateMachines.Branch.matches_conditions?
train
def matches_conditions?(object, query) query[:guard] == false || Array(if_condition).all? {|condition| evaluate_method(object, condition)} && !Array(unless_condition).any? {|condition| evaluate_method(object, condition)} end
ruby
{ "resource": "" }
q16265
StateMachines.PathCollection.initial_paths
train
def initial_paths machine.events.transitions_for(object, :from => from_name, :guard => @guard).map do |transition| path = Path.new(object, machine, :target => to_name, :guard => @guard) path << transition path end end
ruby
{ "resource": "" }
q16266
StateMachines.PathCollection.walk
train
def walk(path) self << path if path.complete? path.walk {|next_path| walk(next_path)} unless to_name && path.complete? && !@deep end
ruby
{ "resource": "" }
q16267
StateMachines.Path.recently_walked?
train
def recently_walked?(transition) transitions = self if @target && @target != to_name && target_transition = detect {|t| t.to_name == @target} transitions = transitions[index(target_transition) + 1..-1] end transitions.include?(transition) end
ruby
{ "resource": "" }
q16268
StateMachines.Path.transitions
train
def transitions @transitions ||= empty? ? [] : machine.events.transitions_for(object, :from => to_name, :guard => @guard).select {|transition| can_walk_to?(transition)} end
ruby
{ "resource": "" }
q16269
StateMachines.StateContext.method_missing
train
def method_missing(*args, &block) # Get the configuration if args.last.is_a?(Hash) options = args.last else args << options = {} end # Get any existing condition that may need to be merged if_condition = options.delete(:if) unless_condition = options.delete(:unless) # Provide scope access to configuration in case the block is evaluated # within the object instance proxy = self proxy_condition = @condition # Replace the configuration condition with the one configured for this # proxy, merging together any existing conditions options[:if] = lambda do |*condition_args| # Block may be executed within the context of the actual object, so # it'll either be the first argument or the executing context object = condition_args.first || self proxy.evaluate_method(object, proxy_condition) && Array(if_condition).all? {|condition| proxy.evaluate_method(object, condition)} && !Array(unless_condition).any? {|condition| proxy.evaluate_method(object, condition)} end # Evaluate the method on the owner class with the condition proxied # through machine.owner_class.send(*args, &block) end
ruby
{ "resource": "" }
q16270
StateMachines.EventCollection.valid_for
train
def valid_for(object, requirements = {}) match(requirements).select { |event| event.can_fire?(object, requirements) } end
ruby
{ "resource": "" }
q16271
StateMachines.EventCollection.transitions_for
train
def transitions_for(object, requirements = {}) match(requirements).map { |event| event.transition_for(object, requirements) }.compact end
ruby
{ "resource": "" }
q16272
StateMachines.EventCollection.attribute_transition_for
train
def attribute_transition_for(object, invalidate = false) return unless machine.action # TODO, simplify machine.read(object, :event_transition) || if event_name = machine.read(object, :event) if event = self[event_name.to_sym, :name] event.transition_for(object) || begin # No valid transition: invalidate machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]]) if invalidate false end else # Event is unknown: invalidate machine.invalidate(object, :event, :invalid) if invalidate false end end end
ruby
{ "resource": "" }
q16273
StateMachines.Event.transition_for
train
def transition_for(object, requirements = {}) requirements.assert_valid_keys(:from, :to, :guard) requirements[:from] = machine.states.match!(object).name unless custom_from_state = requirements.include?(:from) branches.each do |branch| if match = branch.match(object, requirements) # Branch allows for the transition to occur from = requirements[:from] to = if match[:to].is_a?(LoopbackMatcher) from else values = requirements.include?(:to) ? [requirements[:to]].flatten : [from] | machine.states.map { |state| state.name } match[:to].filter(values).first end return Transition.new(object, machine, name, from, to, !custom_from_state) end end # No transition matched nil end
ruby
{ "resource": "" }
q16274
StateMachines.Event.fire
train
def fire(object, *args) machine.reset(object) if transition = transition_for(object) transition.perform(*args) else on_failure(object, *args) false end end
ruby
{ "resource": "" }
q16275
StateMachines.Event.on_failure
train
def on_failure(object, *args) state = machine.states.match!(object) machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]]) transition = Transition.new(object, machine, name, state.name, state.name) transition.args = args if args.any? transition.run_callbacks(:before => false) end
ruby
{ "resource": "" }
q16276
StateMachines.Event.add_actions
train
def add_actions # Checks whether the event can be fired on the current object machine.define_helper(:instance, "can_#{qualified_name}?") do |machine, object, *args| machine.event(name).can_fire?(object, *args) end # Gets the next transition that would be performed if the event were # fired now machine.define_helper(:instance, "#{qualified_name}_transition") do |machine, object, *args| machine.event(name).transition_for(object, *args) end # Fires the event machine.define_helper(:instance, qualified_name) do |machine, object, *args| machine.event(name).fire(object, *args) end # Fires the event, raising an exception if it fails machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args| object.send(qualified_name, *args) || raise(StateMachines::InvalidTransition.new(object, machine, name)) end end
ruby
{ "resource": "" }
q16277
StateMachines.MachineCollection.transitions
train
def transitions(object, action, options = {}) transitions = map do |name, machine| machine.events.attribute_transition_for(object, true) if machine.action == action end AttributeTransitionCollection.new(transitions.compact, {use_transactions: resolve_use_transactions}.merge(options)) end
ruby
{ "resource": "" }
q16278
StateMachines.NodeCollection.<<
train
def <<(node) @nodes << node @index_names.each { |name| add_to_index(name, value(node, name), node) } @contexts.each { |context| eval_context(context, node) } self end
ruby
{ "resource": "" }
q16279
StateMachines.NodeCollection.update_index
train
def update_index(name, node) index = self.index(name) old_key = index.key(node) new_key = value(node, name) # Only replace the key if it's changed if old_key != new_key remove_from_index(name, old_key) add_to_index(name, new_key, node) end end
ruby
{ "resource": "" }
q16280
StateMachines.NodeCollection.eval_context
train
def eval_context(context, node) node.context(&context[:block]) if context[:nodes].matches?(node.name) end
ruby
{ "resource": "" }
q16281
StateMachines.Transition.pause
train
def pause raise ArgumentError, 'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.' unless self.class.pause_supported? unless @resume_block require 'continuation' unless defined?(callcc) callcc do |block| @paused_block = block throw :halt, true end end end
ruby
{ "resource": "" }
q16282
StateMachines.Transition.resume
train
def resume if @paused_block halted, error = callcc do |block| @resume_block = block @paused_block.call end @resume_block = @paused_block = nil raise error if error !halted else true end end
ruby
{ "resource": "" }
q16283
StateMachines.Transition.before
train
def before(complete = true, index = 0, &block) unless @before_run while callback = machine.callbacks[:before][index] index += 1 if callback.type == :around # Around callback: need to handle recursively. Execution only gets # paused if: # * The block fails and the callback doesn't run on failures OR # * The block succeeds, but after callbacks are disabled (in which # case a continuation is stored for later execution) return if catch(:cancel) do callback.call(object, context, self) do before(complete, index, &block) pause if @success && !complete throw :cancel, true unless @success end end else # Normal before callback callback.call(object, context, self) end end @before_run = true end action = {:success => true}.merge(block_given? ? yield : {}) @result, @success = action[:result], action[:success] end
ruby
{ "resource": "" }
q16284
StateMachines.Transition.after
train
def after unless @after_run # First resume previously paused callbacks if resume catch(:halt) do type = @success ? :after : :failure machine.callbacks[type].each {|callback| callback.call(object, context, self)} end end @after_run = true end end
ruby
{ "resource": "" }
q16285
StateMachines.TransitionCollection.run_callbacks
train
def run_callbacks(index = 0, &block) if transition = self[index] throw :halt unless transition.run_callbacks(:after => !skip_after) do run_callbacks(index + 1, &block) {:result => results[transition.action], :success => success?} end else persist run_actions(&block) end end
ruby
{ "resource": "" }
q16286
StateMachines.TransitionCollection.run_actions
train
def run_actions catch_exceptions do @success = if block_given? result = yield actions.each {|action| results[action] = result} !!result else actions.compact.each {|action| !skip_actions && results[action] = object.send(action)} results.values.all? end end end
ruby
{ "resource": "" }
q16287
StateMachines.AttributeTransitionCollection.rollback
train
def rollback super each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?} end
ruby
{ "resource": "" }
q16288
StateMachines.Callback.call
train
def call(object, context = {}, *args, &block) if @branch.matches?(object, context) run_methods(object, context, 0, *args, &block) true else false end end
ruby
{ "resource": "" }
q16289
Yajl.HttpStream.get
train
def get(uri, opts = {}, &block) initialize_socket(uri, opts) HttpStream::get(uri, opts, &block) rescue IOError => e raise e unless @intentional_termination end
ruby
{ "resource": "" }
q16290
Yajl.HttpStream.post
train
def post(uri, body, opts = {}, &block) initialize_socket(uri, opts) HttpStream::post(uri, body, opts, &block) rescue IOError => e raise e unless @intentional_termination end
ruby
{ "resource": "" }
q16291
Yajl.HttpStream.initialize_socket
train
def initialize_socket(uri, opts = {}) return if opts[:socket] @socket = TCPSocket.new(uri.host, uri.port) opts.merge!({:socket => @socket}) @intentional_termination = false end
ruby
{ "resource": "" }
q16292
Xray.Middleware.append_js!
train
def append_js!(html, after_script_name, script_name) html.sub!(script_matcher(after_script_name)) do "#{$~}\n" + helper.javascript_include_tag(script_name) end end
ruby
{ "resource": "" }
q16293
HasScope.ClassMethods.has_scope
train
def has_scope(*scopes, &block) options = scopes.extract_options! options.symbolize_keys! options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank, :in) if options.key?(:in) options[:as] = options[:in] options[:using] = scopes end if options.key?(:using) if options.key?(:type) && options[:type] != :hash raise "You cannot use :using with another :type different than :hash" else options[:type] = :hash end options[:using] = Array(options[:using]) end options[:only] = Array(options[:only]) options[:except] = Array(options[:except]) self.scopes_configuration = scopes_configuration.dup scopes.each do |scope| scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block } scopes_configuration[scope] = self.scopes_configuration[scope].merge(options) end end
ruby
{ "resource": "" }
q16294
Ox.Element.attr_match
train
def attr_match(cond) cond.each_pair { |k,v| return false unless v == @attributes[k.to_sym] || v == @attributes[k.to_s] } true end
ruby
{ "resource": "" }
q16295
Ox.Element.each
train
def each(cond=nil) if cond.nil? nodes.each { |n| yield(n) } else cond = cond.to_s if cond.is_a?(Symbol) if cond.is_a?(String) nodes.each { |n| yield(n) if n.is_a?(Element) && cond == n.name } elsif cond.is_a?(Hash) nodes.each { |n| yield(n) if n.is_a?(Element) && n.attr_match(cond) } end end end
ruby
{ "resource": "" }
q16296
Ox.Element.remove_children
train
def remove_children(*children) return self if children.compact.empty? recursive_children_removal(children.compact.map { |c| c.object_id }) self end
ruby
{ "resource": "" }
q16297
Ox.Element.recursive_children_removal
train
def recursive_children_removal(found) return if found.empty? nodes.tap do |ns| # found.delete(n.object_id) stops looking for an already found object_id ns.delete_if { |n| found.include?(n.object_id) ? found.delete(n.object_id) : false } nodes.each do |n| n.send(:recursive_children_removal, found) if n.is_a?(Ox::Element) end end end
ruby
{ "resource": "" }
q16298
Xcake.Visitor.visit
train
def visit(item) item_name = item_name(item) method = "visit_#{item_name}" send(method, item) if respond_to? method end
ruby
{ "resource": "" }
q16299
Xcake.Visitor.leave
train
def leave(item) item_name = item_name(item) method = "leave_#{item_name}" send(method, item) if respond_to? method end
ruby
{ "resource": "" }