_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q16800
FiniteMachine.EventDefinition.apply
train
def apply(event_name, silent = false) define_event_transition(event_name, silent) define_event_bang(event_name, silent) end
ruby
{ "resource": "" }
q16801
FiniteMachine.EventDefinition.define_event_transition
train
def define_event_transition(event_name, silent) machine.send(:define_singleton_method, event_name) do |*data, &block| method = silent ? :transition : :trigger machine.public_send(method, event_name, *data, &block) end end
ruby
{ "resource": "" }
q16802
FiniteMachine.DSL.initial
train
def initial(value, **options) state = (value && !value.is_a?(Hash)) ? value : raise_missing_state name, @defer_initial, @silent_initial = *parse_initial(options) @initial_event = name event(name, FiniteMachine::DEFAULT_STATE => state, silent: @silent_initial) end
ruby
{ "resource": "" }
q16803
FiniteMachine.DSL.event
train
def event(name, transitions = {}, &block) detect_event_conflict!(name) if machine.auto_methods? if block_given? merger = ChoiceMerger.new(machine, name, transitions) merger.instance_eval(&block) else transition_builder = TransitionBuilder.new(machine, name, transitions) transition_builder.call(transitions) end end
ruby
{ "resource": "" }
q16804
FiniteMachine.DSL.parse_initial
train
def parse_initial(options) [options.fetch(:event) { FiniteMachine::DEFAULT_EVENT_NAME }, options.fetch(:defer) { false }, options.fetch(:silent) { true }] end
ruby
{ "resource": "" }
q16805
FiniteMachine.StateMachine.is?
train
def is?(state) if state.is_a?(Array) state.include? current else state == current end end
ruby
{ "resource": "" }
q16806
FiniteMachine.StateMachine.can?
train
def can?(*args) event_name = args.shift events_map.can_perform?(event_name, current, *args) end
ruby
{ "resource": "" }
q16807
FiniteMachine.StateMachine.valid_state?
train
def valid_state?(event_name) current_states = events_map.states_for(event_name) current_states.any? { |state| state == current || state == ANY_STATE } end
ruby
{ "resource": "" }
q16808
FiniteMachine.StateMachine.notify
train
def notify(hook_event_type, event_name, from, *data) sync_shared do hook_event = hook_event_type.build(current, event_name, from) subscribers.visit(hook_event, *data) end end
ruby
{ "resource": "" }
q16809
FiniteMachine.StateMachine.try_trigger
train
def try_trigger(event_name) if valid_state?(event_name) yield else exception = InvalidStateError catch_error(exception) || fail(exception, "inappropriate current state '#{current}'") false end end
ruby
{ "resource": "" }
q16810
FiniteMachine.StateMachine.trigger!
train
def trigger!(event_name, *data, &block) from = current # Save away current state sync_exclusive do notify HookEvent::Before, event_name, from, *data status = try_trigger(event_name) do if can?(event_name, *data) notify HookEvent::Exit, event_name, from, *data stat = transition!(event_name, *data, &block) notify HookEvent::Transition, event_name, from, *data notify HookEvent::Enter, event_name, from, *data else stat = false end stat end notify HookEvent::After, event_name, from, *data status end rescue Exception => err self.state = from # rollback transition raise err end
ruby
{ "resource": "" }
q16811
FiniteMachine.StateMachine.trigger
train
def trigger(event_name, *data, &block) trigger!(event_name, *data, &block) rescue InvalidStateError, TransitionError, CallbackError false end
ruby
{ "resource": "" }
q16812
FiniteMachine.StateMachine.transition!
train
def transition!(event_name, *data, &block) from_state = current to_state = events_map.move_to(event_name, from_state, *data) block.call(from_state, to_state) if block if log_transitions Logger.report_transition(event_name, from_state, to_state, *data) end try_trigger(event_name) { transition_to!(to_state) } end
ruby
{ "resource": "" }
q16813
FiniteMachine.StateMachine.transition_to!
train
def transition_to!(new_state) from_state = current self.state = new_state self.initial_state = new_state if from_state == DEFAULT_STATE true rescue Exception => e catch_error(e) || raise_transition_error(e) end
ruby
{ "resource": "" }
q16814
FiniteMachine.StateMachine.method_missing
train
def method_missing(method_name, *args, &block) if observer.respond_to?(method_name.to_sym) observer.public_send(method_name.to_sym, *args, &block) elsif env.aliases.include?(method_name.to_sym) env.send(:target, *args, &block) else super end end
ruby
{ "resource": "" }
q16815
FiniteMachine.StateMachine.respond_to_missing?
train
def respond_to_missing?(method_name, include_private = false) observer.respond_to?(method_name.to_sym) || env.aliases.include?(method_name.to_sym) || super end
ruby
{ "resource": "" }
q16816
FiniteMachine.Safety.detect_event_conflict!
train
def detect_event_conflict!(event_name, method_name = event_name) if method_already_implemented?(method_name) raise FiniteMachine::AlreadyDefinedError, EVENT_CONFLICT_MESSAGE % { name: event_name, type: :instance, method: method_name, source: 'FiniteMachine' } end end
ruby
{ "resource": "" }
q16817
FiniteMachine.Safety.ensure_valid_callback_name!
train
def ensure_valid_callback_name!(event_type, name) message = if wrong_event_name?(name, event_type) EVENT_CALLBACK_CONFLICT_MESSAGE % { type: "on_#{event_type}", name: name } elsif wrong_state_name?(name, event_type) STATE_CALLBACK_CONFLICT_MESSAGE % { type: "on_#{event_type}", name: name } elsif !callback_names.include?(name) CALLBACK_INVALID_MESSAGE % { name: name, callbacks: callback_names.to_a.inspect } else nil end message && raise_invalid_callback_error(message) end
ruby
{ "resource": "" }
q16818
FiniteMachine.Safety.wrong_event_name?
train
def wrong_event_name?(name, event_type) machine.states.include?(name) && !machine.events.include?(name) && event_type < HookEvent::Anyaction end
ruby
{ "resource": "" }
q16819
FiniteMachine.Safety.wrong_state_name?
train
def wrong_state_name?(name, event_type) machine.events.include?(name) && !machine.states.include?(name) && event_type < HookEvent::Anystate end
ruby
{ "resource": "" }
q16820
FiniteMachine.MessageQueue.subscribe
train
def subscribe(*args, &block) @mutex.synchronize do listener = Listener.new(*args) listener.on_delivery(&block) @listeners << listener end end
ruby
{ "resource": "" }
q16821
FiniteMachine.MessageQueue.shutdown
train
def shutdown fail EventQueueDeadError, 'event queue already dead' if @dead queue = [] @mutex.synchronize do @dead = true @not_empty.broadcast queue = @queue @queue.clear end while !queue.empty? discard_message(queue.pop) end true end
ruby
{ "resource": "" }
q16822
FiniteMachine.MessageQueue.process_events
train
def process_events until @dead @mutex.synchronize do while @queue.empty? break if @dead @not_empty.wait(@mutex) end event = @queue.pop break unless event notify_listeners(event) event.dispatch end end rescue Exception => ex Logger.error "Error while running event: #{Logger.format_error(ex)}" end
ruby
{ "resource": "" }
q16823
FiniteMachine.Subscribers.visit
train
def visit(hook_event, *data) each { |subscriber| synchronize { hook_event.notify(subscriber, *data) } } end
ruby
{ "resource": "" }
q16824
FiniteMachine.TransitionBuilder.call
train
def call(transitions) StateParser.parse(transitions) do |from, to| transition = Transition.new(@machine.env.target, @name, @attributes.merge(states: { from => to })) silent = @attributes.fetch(:silent, false) @machine.events_map.add(@name, transition) next unless @machine.auto_methods? unless @machine.respond_to?(@name) @event_definition.apply(@name, silent) end @state_definition.apply(from => to) end self end
ruby
{ "resource": "" }
q16825
FiniteMachine.Catchable.handle
train
def handle(*exceptions, &block) options = exceptions.last.is_a?(Hash) ? exceptions.pop : {} unless options.key?(:with) if block_given? options[:with] = block else raise ArgumentError, 'Need to provide error handler.' end end evaluate_exceptions(exceptions, options) end
ruby
{ "resource": "" }
q16826
FiniteMachine.Catchable.catch_error
train
def catch_error(exception) if handler = handler_for_error(exception) handler.arity.zero? ? handler.call : handler.call(exception) true end end
ruby
{ "resource": "" }
q16827
FiniteMachine.Catchable.extract_const
train
def extract_const(class_name) class_name.split('::').reduce(FiniteMachine) do |constant, part| constant.const_get(part) end end
ruby
{ "resource": "" }
q16828
FiniteMachine.Catchable.evaluate_handler
train
def evaluate_handler(handler) case handler when Symbol target.method(handler) when Proc if handler.arity.zero? proc { instance_exec(&handler) } else proc { |_exception| instance_exec(_exception, &handler) } end end end
ruby
{ "resource": "" }
q16829
FiniteMachine.Catchable.evaluate_exceptions
train
def evaluate_exceptions(exceptions, options) exceptions.each do |exception| key = if exception.is_a?(Class) && exception <= Exception exception.name elsif exception.is_a?(String) exception else raise ArgumentError, "#{exception} isn't an Exception" end error_handlers << [key, options[:with]] end end
ruby
{ "resource": "" }
q16830
LitaGithub.Org.team_id_by_slug
train
def team_id_by_slug(slug, org) octo.organization_teams(org).each do |team| return team[:id] if team[:slug] == slug.downcase end nil end
ruby
{ "resource": "" }
q16831
LitaGithub.Org.team_id
train
def team_id(team, org) /^\d+$/.match(team.to_s) ? team : team_id_by_slug(team, org) end
ruby
{ "resource": "" }
q16832
LitaGithub.General.opts_parse
train
def opts_parse(cmd) o = {} cmd.scan(LitaGithub::R::OPT_REGEX).flatten.each do |opt| k, v = symbolize_opt_key(*opt.strip.split(':')) next if o.key?(k) # if it looks like we're using the extended option (first character is a " or '): # slice off the first and last character of the string # otherwise: # do nothing v = v.slice!(1, (v.length - 2)) if %w(' ").include?(v.slice(0)) o[k] = to_i_if_numeric(v) end o end
ruby
{ "resource": "" }
q16833
LitaGithub.Repo.repo_has_team?
train
def repo_has_team?(full_name, team_id) octo.repository_teams(full_name).each { |t| return true if t[:id] == team_id } false end
ruby
{ "resource": "" }
q16834
TfIdfSimilarity.TfIdfModel.probabilistic_inverse_document_frequency
train
def probabilistic_inverse_document_frequency(term) count = @model.document_count(term).to_f log((documents.size - count) / count) end
ruby
{ "resource": "" }
q16835
TfIdfSimilarity.TfIdfModel.normalized_log_term_frequency
train
def normalized_log_term_frequency(document, term) count = document.term_count(term) if count > 0 (1 + log(count)) / (1 + log(document.average_term_count)) else 0 end end
ruby
{ "resource": "" }
q16836
TfIdfSimilarity.Document.set_term_counts_and_size
train
def set_term_counts_and_size tokenize(text).each do |word| token = Token.new(word) if token.valid? term = token.lowercase_filter.classic_filter.to_s @term_counts[term] += 1 @size += 1 end end end
ruby
{ "resource": "" }
q16837
TfIdfSimilarity.BM25Model.inverse_document_frequency
train
def inverse_document_frequency(term) df = @model.document_count(term) log((documents.size - df + 0.5) / (df + 0.5)) end
ruby
{ "resource": "" }
q16838
TfIdfSimilarity.BM25Model.term_frequency
train
def term_frequency(document, term) tf = document.term_count(term) (tf * 2.2) / (tf + 0.3 + 0.9 * documents.size / @model.average_document_size) end
ruby
{ "resource": "" }
q16839
Dry.View.call
train
def call(format: config.default_format, context: config.default_context, **input) ensure_config env = self.class.render_env(format: format, context: context) template_env = self.class.template_env(format: format, context: context) locals = locals(template_env, input) output = env.template(config.template, template_env.scope(config.scope, locals)) if layout? layout_env = self.class.layout_env(format: format, context: context) output = env.template(self.class.layout_path, layout_env.scope(config.scope, layout_locals(locals))) { output } end Rendered.new(output: output, locals: locals) end
ruby
{ "resource": "" }
q16840
DeepCover.CoveredCode.check_node_overlap!
train
def check_node_overlap! node_to_positions = {} each_node do |node| node.proper_range.each do |position| if node_to_positions[position] already = node_to_positions[position] puts "There is a proper_range overlap between #{node} and #{already}" puts "Overlapping: #{already.proper_range & node.proper_range}" binding.pry end node_to_positions[position] = node end end end
ruby
{ "resource": "" }
q16841
DeepCover.Tools::ContentTag.content_tag
train
def content_tag(tag, content, **options) attrs = options.map { |kind, value| %{ #{kind}="#{value}"} }.join "<#{tag}#{attrs}>#{content}</#{tag}>" end
ruby
{ "resource": "" }
q16842
DeepCover.IgnoreNodes.results
train
def results(analyser) r = analyser.results [0, nil].map do |val| r.select { |node, runs| runs == val } .keys .map(&:source) end end
ruby
{ "resource": "" }
q16843
DeepCover.Node.find_all
train
def find_all(lookup) case lookup when ::Module each_node.grep(lookup) when ::Symbol each_node.find_all { |n| n.type == lookup } when ::String each_node.find_all { |n| n.source == lookup } when ::Regexp each_node.find_all { |n| n.source =~ lookup } else raise ::TypeError, "Expected class or symbol, got #{lookup.class}: #{lookup.inspect}" end end
ruby
{ "resource": "" }
q16844
DeepCover.Node.[]
train
def [](lookup) if lookup.is_a?(Integer) children.fetch(lookup) else found = find_all(lookup) case found.size when 1 found.first when 0 raise "No children of type #{lookup}" else raise "Ambiguous lookup #{lookup}, found #{found}." end end end
ruby
{ "resource": "" }
q16845
DeepCover.Node.each_node
train
def each_node(&block) return to_enum :each_node unless block_given? children_nodes.each do |child| child.each_node(&block) end yield self self end
ruby
{ "resource": "" }
q16846
DeepCover.Coverage.add_missing_covered_codes
train
def add_missing_covered_codes top_level_path = DeepCover.config.paths.detect do |path| next unless path.is_a?(String) path = File.expand_path(path) File.dirname(path) == path end if top_level_path # One of the paths is a root path. # Either a mistake, or the user wanted to check everything that gets loaded. Either way, # we will probably hang from searching the files to load. (and then loading them, as there # can be lots of ruby files) We prefer to warn the user and not do anything. suggestion = "#{top_level_path}/**/*.rb" warn ["Because the `paths` configured in DeepCover include #{top_level_path.inspect}, which is a root of your fs, ", 'DeepCover will not attempt to find Ruby files that were not required. Your coverage report will not include ', 'files that were not instrumented. This is to avoid extremely long wait times. If you actually want this to ', "happen, then replace the specified `paths` with #{suggestion.inspect}.", ].join return end DeepCover.all_tracked_file_paths.each do |path| covered_code(path, tracker_hits: :zeroes) end nil end
ruby
{ "resource": "" }
q16847
top_level_module::DeepCover.Persistence.load_trackers
train
def load_trackers tracker_hits_per_path_hashes = tracker_files.map do |full_path| JSON.parse(full_path.binread).transform_keys(&:to_sym).yield_self do |version:, tracker_hits_per_path:| raise "dump version mismatch: #{version}, currently #{VERSION}" unless version == VERSION tracker_hits_per_path end end self.class.merge_tracker_hits_per_paths(*tracker_hits_per_path_hashes) end
ruby
{ "resource": "" }
q16848
DeepCover.AutoloadTracker.initialize_autoloaded_paths
train
def initialize_autoloaded_paths(mods = ObjectSpace.each_object(Module)) # &do_autoload_block mods.each do |mod| # Module's constants are shared with Object. But if you set autoloads directly on Module, they # appear on multiple classes. So just skip, Object will take care of those. next if mod == Module # This happens with JRuby next unless mod.respond_to?(:constants) if mod.frozen? if mod.constants.any? { |name| mod.autoload?(name) } self.class.warn_frozen_module(mod) end next end mod.constants.each do |name| # JRuby can talk about deprecated constants here path = Tools.silence_warnings do mod.autoload?(name) end next unless path interceptor_path = setup_interceptor_for(mod, name, path) yield mod, name, interceptor_path end end end
ruby
{ "resource": "" }
q16849
DeepCover.AutoloadTracker.remove_interceptors
train
def remove_interceptors # &do_autoload_block @autoloads_by_basename.each do |basename, entries| entries.each do |entry| mod = entry.mod_if_available next unless mod # Module's constants are shared with Object. But if you set autoloads directly on Module, they # appear on multiple classes. So just skip, Object will take care of those. next if mod == Module yield mod, entry.name, entry.target_path end end @autoloaded_paths = {} @interceptor_files_by_path = {} end
ruby
{ "resource": "" }
q16850
DeepCover.Tools::ExecuteSample.execute_sample
train
def execute_sample(to_execute, source: nil) # Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected. Tools.silence_warnings do if to_execute.is_a?(CoveredCode) to_execute.execute_code else to_execute.call end end true rescue StandardError => e # In our samples, a simple `raise` is expected and doesn't need to be rescued return false if e.is_a?(RuntimeError) && e.message.empty? source = to_execute.covered_source if to_execute.is_a?(CoveredCode) raise unless source inner_msg = Tools.indent_string("#{e.class.name}: #{e.message}", 4) source = Tools.indent_string(source, 4) msg = "Exception when executing the sample:\n#{inner_msg}\n*Code follows*\n#{source}" new_exc = ExceptionInSample.new(msg) new_exc.set_backtrace(e.backtrace) raise new_exc end
ruby
{ "resource": "" }
q16851
Mixlib.Config.from_file
train
def from_file(filename) if %w{ .yml .yaml }.include?(File.extname(filename)) from_yaml(filename) elsif File.extname(filename) == ".json" from_json(filename) elsif File.extname(filename) == ".toml" from_toml(filename) else instance_eval(IO.read(filename), filename, 1) end end
ruby
{ "resource": "" }
q16852
Mixlib.Config.reset
train
def reset self.configuration = Hash.new config_contexts.values.each { |config_context| config_context.reset } end
ruby
{ "resource": "" }
q16853
Mixlib.Config.save
train
def save(include_defaults = false) result = configuration.dup if include_defaults (configurables.keys - result.keys).each do |missing_default| # Ask any configurables to save themselves into the result array if configurables[missing_default].has_default result[missing_default] = configurables[missing_default].default end end end config_contexts.each_pair do |key, context| context_result = context.save(include_defaults) result[key] = context_result if context_result.size != 0 || include_defaults end config_context_lists.each_pair do |key, meta| meta[:values].each do |context| context_result = context.save(include_defaults) result[key] = (result[key] || []) << context_result if context_result.size != 0 || include_defaults end end config_context_hashes.each_pair do |key, meta| meta[:values].each_pair do |context_key, context| context_result = context.save(include_defaults) (result[key] ||= {})[context_key] = context_result if context_result.size != 0 || include_defaults end end result end
ruby
{ "resource": "" }
q16854
Mixlib.Config.restore
train
def restore(hash) self.configuration = hash.reject { |key, value| config_contexts.key?(key) } config_contexts.each do |key, config_context| if hash.key?(key) config_context.restore(hash[key]) else config_context.reset end end config_context_lists.each do |key, meta| meta[:values] = [] if hash.key?(key) hash[key].each do |val| context = define_context(meta[:definition_blocks]) context.restore(val) meta[:values] << context end end end config_context_hashes.each do |key, meta| meta[:values] = {} if hash.key?(key) hash[key].each do |vkey, val| context = define_context(meta[:definition_blocks]) context.restore(val) meta[:values][vkey] = context end end end end
ruby
{ "resource": "" }
q16855
Mixlib.Config.merge!
train
def merge!(hash) hash.each do |key, value| if config_contexts.key?(key) # Grab the config context and let internal_get cache it if so desired config_contexts[key].restore(value) else configuration[key] = value end end self end
ruby
{ "resource": "" }
q16856
Mixlib.Config.config_context
train
def config_context(symbol, &block) if configurables.key?(symbol) raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{symbol} with a config context" end if config_contexts.key?(symbol) context = config_contexts[symbol] else context = Class.new context.extend(::Mixlib::Config) context.config_parent = self config_contexts[symbol] = context define_attr_accessor_methods(symbol) end if block context.instance_eval(&block) end context end
ruby
{ "resource": "" }
q16857
Mixlib.Config.config_context_list
train
def config_context_list(plural_symbol, singular_symbol, &block) if configurables.key?(plural_symbol) raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context" end unless config_context_lists.key?(plural_symbol) config_context_lists[plural_symbol] = { definition_blocks: [], values: [], } define_list_attr_accessor_methods(plural_symbol, singular_symbol) end config_context_lists[plural_symbol][:definition_blocks] << block if block_given? end
ruby
{ "resource": "" }
q16858
Mixlib.Config.config_context_hash
train
def config_context_hash(plural_symbol, singular_symbol, &block) if configurables.key?(plural_symbol) raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context" end unless config_context_hashes.key?(plural_symbol) config_context_hashes[plural_symbol] = { definition_blocks: [], values: {}, } define_hash_attr_accessor_methods(plural_symbol, singular_symbol) end config_context_hashes[plural_symbol][:definition_blocks] << block if block_given? end
ruby
{ "resource": "" }
q16859
Mixlib.Config.internal_set
train
def internal_set(symbol, value) if configurables.key?(symbol) configurables[symbol].set(configuration, value) elsif config_contexts.key?(symbol) config_contexts[symbol].restore(value.to_hash) else if config_strict_mode == :warn Chef::Log.warn("Setting unsupported config value #{symbol}.") elsif config_strict_mode raise UnknownConfigOptionError, "Cannot set unsupported config value #{symbol}." end configuration[symbol] = value end end
ruby
{ "resource": "" }
q16860
NestedForm.BuilderMixin.link_to_remove
train
def link_to_remove(*args, &block) options = args.extract_options!.symbolize_keys options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ") # Extracting "milestones" from "...[milestones_attributes][...]" md = object_name.to_s.match /(\w+)_attributes\](?:\[[\w\d]+\])?$/ association = md && md[1] options["data-association"] = association args << (options.delete(:href) || "javascript:void(0)") args << options hidden_field(:_destroy) << @template.link_to(*args, &block) end
ruby
{ "resource": "" }
q16861
Lyp.DependencyResolver.resolve_tree
train
def resolve_tree permutations = permutate_simplified_tree permutations = filter_invalid_permutations(permutations) # select highest versioned dependencies (for those specified by user) user_deps = tree.dependencies.keys result = select_highest_versioned_permutation(permutations, user_deps).flatten if result.empty? && !tree.dependencies.empty? error("Failed to satisfy dependency requirements") else result end end
ruby
{ "resource": "" }
q16862
Lyp.DependencyResolver.dependencies_array
train
def dependencies_array(leaf, processed = {}) return processed[leaf] if processed[leaf] deps_array = [] processed[leaf] = deps_array leaf.each do |pack, versions| a = [] versions.each do |version, deps| perms = [] sub_perms = dependencies_array(deps, processed) if sub_perms == [] perms += [version] else sub_perms[0].each do |perm| perms << [version] + [perm].flatten end end a += perms end deps_array << a end deps_array end
ruby
{ "resource": "" }
q16863
Lyp.DependencyResolver.filter_invalid_permutations
train
def filter_invalid_permutations(permutations) valid = [] permutations.each do |perm| versions = {}; invalid = false perm.each do |ref| if ref =~ /(.+)@(.+)/ name, version = $1, $2 if versions[name] && versions[name] != version invalid = true break else versions[name] = version end end end valid << perm.uniq unless invalid end valid end
ruby
{ "resource": "" }
q16864
Lyp.DependencyResolver.select_highest_versioned_permutation
train
def select_highest_versioned_permutation(permutations, user_deps) sorted = sort_permutations(permutations, user_deps) sorted.empty? ? [] : sorted.last end
ruby
{ "resource": "" }
q16865
Lyp.DependencyResolver.sort_permutations
train
def sort_permutations(permutations, user_deps) # Cache for versions converted to Gem::Version instances versions = {} map = lambda do |m, p| if p =~ Lyp::PACKAGE_RE m[$1] = versions[p] ||= (Lyp.version($2 || '0.0') rescue nil) end m end compare = lambda do |x, y| x_versions = x.inject({}, &map) y_versions = y.inject({}, &map) # If the dependency is direct (not transitive), just compare its versions. # Otherwise, add the result of comparison to score. x_versions.inject(0) do |score, kv| package = kv[0] cmp = kv[1] <=> y_versions[package] if user_deps.include?(package) && cmp != 0 return cmp else score += cmp unless cmp.nil? end score end end permutations.sort(&compare) end
ruby
{ "resource": "" }
q16866
Lyp.DependencyResolver.find_matching_packages
train
def find_matching_packages(req) return {} unless req =~ Lyp::PACKAGE_RE req_package = $1 req_version = $2 req = nil if @opts[:forced_package_paths] && @opts[:forced_package_paths][req_package] req_version = 'forced' end req = Lyp.version_req(req_version || '>=0') rescue nil available_packages.select do |package, leaf| if (package =~ Lyp::PACKAGE_RE) && (req_package == $1) version = Lyp.version($2 || '0') rescue nil if version.nil? || req.nil? req_version.nil? || (req_version == $2) else req =~ version end else nil end end end
ruby
{ "resource": "" }
q16867
Lyp.DependencyResolver.find_package_versions
train
def find_package_versions(ref, leaf, location) return {} unless ref =~ Lyp::PACKAGE_RE ref_package = $1 version_clause = $2 matches = find_matching_packages(ref) # Raise if no match found and we're at top of the tree if matches.empty? && (leaf == tree) && !opts[:ignore_missing] msg = "Missing package dependency #{ref} in %sYou can install any missing packages by running:\n\n lyp resolve #{@user_file}" error(msg, location) end matches.each do |p, package_leaf| if package_leaf.path queue_file_for_processing(package_leaf.path, package_leaf) end end # Setup up dependency leaf leaf.add_dependency(ref_package, DependencySpec.new(ref, matches, location)) end
ruby
{ "resource": "" }
q16868
Lyp.DependencyResolver.squash_old_versions
train
def squash_old_versions specifiers = map_specifiers_to_versions compare_versions = lambda do |x, y| v_x = x =~ Lyp::PACKAGE_RE && Lyp.version($2) v_y = y =~ Lyp::PACKAGE_RE && Lyp.version($2) x <=> y end specifiers.each do |package, clauses| # Remove old versions only if the package is referenced using a single # specifier clause next unless clauses.size == 1 specs = clauses.values.first specs.each do |s| if s.versions.values.uniq.size == 1 versions = s.versions.keys.sort(&compare_versions) latest = versions.last s.versions.select! {|k, v| k == latest} end end end end
ruby
{ "resource": "" }
q16869
Lyp.DependencyResolver.map_specifiers_to_versions
train
def map_specifiers_to_versions specifiers = {} processed = {} l = lambda do |t| return if processed[t.object_id] processed[t.object_id] = true t.dependencies.each do |package, spec| specifiers[package] ||= {} specifiers[package][spec.clause] ||= [] specifiers[package][spec.clause] << spec spec.versions.each_value {|v| l[v]} end end l[@tree] specifiers end
ruby
{ "resource": "" }
q16870
Lyp.DependencyResolver.remove_unfulfilled_dependencies
train
def remove_unfulfilled_dependencies(leaf, raise_on_missing = true, processed = {}) tree.dependencies.each do |package, dependency| dependency.versions.select! do |version, leaf| if processed[version] true else processed[version] = true # Remove unfulfilled transitive dependencies remove_unfulfilled_dependencies(leaf, false, processed) valid = true leaf.dependencies.each do |k, v| valid = false if v.versions.empty? end valid end end if dependency.versions.empty? && raise_on_missing error("No valid version found for package #{package}") end end end
ruby
{ "resource": "" }
q16871
Airbrake.FilterChain.add_filter
train
def add_filter(filter) @filters = (@filters << filter).sort_by do |f| f.respond_to?(:weight) ? f.weight : DEFAULT_WEIGHT end.reverse! end
ruby
{ "resource": "" }
q16872
Airbrake.FilterChain.delete_filter
train
def delete_filter(filter_class) index = @filters.index { |f| f.class.name == filter_class.name } @filters.delete_at(index) if index end
ruby
{ "resource": "" }
q16873
Airbrake.Truncator.replace_invalid_characters
train
def replace_invalid_characters(str) encoding = str.encoding utf8_string = (encoding == Encoding::UTF_8 || encoding == Encoding::ASCII) return str if utf8_string && str.valid_encoding? temp_str = str.dup temp_str.encode!(TEMP_ENCODING, ENCODING_OPTIONS) if utf8_string temp_str.encode!('utf-8', ENCODING_OPTIONS) end
ruby
{ "resource": "" }
q16874
Airbrake.AsyncSender.send
train
def send(notice, promise) return will_not_deliver(notice) if @unsent.size >= @unsent.max @unsent << [notice, promise] promise end
ruby
{ "resource": "" }
q16875
Airbrake.Notice.[]=
train
def []=(key, value) raise_if_ignored unless WRITABLE_KEYS.include?(key) raise Airbrake::Error, ":#{key} is not recognized among #{WRITABLE_KEYS}" end unless value.respond_to?(:to_hash) raise Airbrake::Error, "Got #{value.class} value, wanted a Hash" end @payload[key] = value.to_hash end
ruby
{ "resource": "" }
q16876
Danger.DangerSwiftlint.run_swiftlint
train
def run_swiftlint(files, lint_all_files, options, additional_swiftlint_args) if lint_all_files result = swiftlint.lint(options, additional_swiftlint_args) if result == '' {} else JSON.parse(result).flatten end else files .map { |file| options.merge(path: file) } .map { |full_options| swiftlint.lint(full_options, additional_swiftlint_args) } .reject { |s| s == '' } .map { |s| JSON.parse(s).flatten } .flatten end end
ruby
{ "resource": "" }
q16877
Danger.DangerSwiftlint.find_swift_files
train
def find_swift_files(dir_selected, files = nil, excluded_paths = [], included_paths = []) # Needs to be escaped before comparsion with escaped file paths dir_selected = Shellwords.escape(dir_selected) # Assign files to lint files = if files.nil? (git.modified_files - git.deleted_files) + git.added_files else Dir.glob(files) end # Filter files to lint files. # Ensure only swift files are selected select { |file| file.end_with?('.swift') }. # Make sure we don't fail when paths have spaces map { |file| Shellwords.escape(File.expand_path(file)) }. # Remove dups uniq. # Ensure only files in the selected directory select { |file| file.start_with?(dir_selected) }. # Reject files excluded on configuration reject { |file| file_exists?(excluded_paths, file) }. # Accept files included on configuration select do |file| next true if included_paths.empty? file_exists?(included_paths, file) end end
ruby
{ "resource": "" }
q16878
Danger.DangerSwiftlint.load_config
train
def load_config(filepath) return {} if filepath.nil? || !File.exist?(filepath) config_file = File.open(filepath).read # Replace environment variables config_file = parse_environment_variables(config_file) YAML.safe_load(config_file) end
ruby
{ "resource": "" }
q16879
Danger.DangerSwiftlint.parse_environment_variables
train
def parse_environment_variables(file_contents) # Matches the file contents for environment variables defined like ${VAR_NAME}. # Replaces them with the environment variable value if it exists. file_contents.gsub(/\$\{([^{}]+)\}/) do |env_var| return env_var if ENV[Regexp.last_match[1]].nil? ENV[Regexp.last_match[1]] end end
ruby
{ "resource": "" }
q16880
Danger.DangerSwiftlint.file_exists?
train
def file_exists?(paths, file) paths.any? do |path| Find.find(path) .map { |path_file| Shellwords.escape(path_file) } .include?(file) end end
ruby
{ "resource": "" }
q16881
Danger.DangerSwiftlint.format_paths
train
def format_paths(paths, filepath) # Extract included paths paths .map { |path| File.join(File.dirname(filepath), path) } .map { |path| File.expand_path(path) } .select { |path| File.exist?(path) || Dir.exist?(path) } end
ruby
{ "resource": "" }
q16882
Danger.DangerSwiftlint.markdown_issues
train
def markdown_issues(results, heading) message = "#### #{heading}\n\n".dup message << "File | Line | Reason |\n" message << "| --- | ----- | ----- |\n" results.each do |r| filename = r['file'].split('/').last line = r['line'] reason = r['reason'] rule = r['rule_id'] # Other available properties can be found int SwiftLint/…/JSONReporter.swift message << "#{filename} | #{line} | #{reason} (#{rule})\n" end message end
ruby
{ "resource": "" }
q16883
Pusher.WebHook.check_signature
train
def check_signature(secret) digest = OpenSSL::Digest::SHA256.new expected = OpenSSL::HMAC.hexdigest(digest, secret, @body) if @signature == expected return true else Pusher.logger.warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}" return false end end
ruby
{ "resource": "" }
q16884
Pusher.Client.url=
train
def url=(url) uri = URI.parse(url) @scheme = uri.scheme @app_id = uri.path.split('/').last @key = uri.user @secret = uri.password @host = uri.host @port = uri.port end
ruby
{ "resource": "" }
q16885
Pusher.Client.trigger
train
def trigger(channels, event_name, data, params = {}) post('/events', trigger_params(channels, event_name, data, params)) end
ruby
{ "resource": "" }
q16886
Pusher.Channel.trigger
train
def trigger(event_name, data, socket_id = nil) trigger!(event_name, data, socket_id) rescue Pusher::Error => e Pusher.logger.error("#{e.message} (#{e.class})") Pusher.logger.debug(e.backtrace.join("\n")) end
ruby
{ "resource": "" }
q16887
Pusher.Channel.authentication_string
train
def authentication_string(socket_id, custom_string = nil) validate_socket_id(socket_id) unless custom_string.nil? || custom_string.kind_of?(String) raise Error, 'Custom argument must be a string' end string_to_sign = [socket_id, name, custom_string]. compact.map(&:to_s).join(':') Pusher.logger.debug "Signing #{string_to_sign}" token = @client.authentication_token digest = OpenSSL::Digest::SHA256.new signature = OpenSSL::HMAC.hexdigest(digest, token.secret, string_to_sign) return "#{token.key}:#{signature}" end
ruby
{ "resource": "" }
q16888
Pageflow.WidgetType.render
train
def render(template, entry) template.render(File.join('pageflow', name, 'widget'), entry: entry) end
ruby
{ "resource": "" }
q16889
Pageflow.AccountRoleQuery.has_at_least_role?
train
def has_at_least_role?(role) @user .memberships .where(role: Roles.at_least(role)) .where('(entity_id = :account_id AND '\ "entity_type = 'Pageflow::Account')", account_id: @account.id) .any? end
ruby
{ "resource": "" }
q16890
Pageflow.HelpEntries.register
train
def register(name, options = {}) help_entry = HelpEntry.new(name, options) @help_entries_by_name[name] = help_entry collection = find_collection(options[:parent]) collection << help_entry collection.sort_by! { |help_entry| -help_entry.priority } end
ruby
{ "resource": "" }
q16891
Twirp.Service.call
train
def call(rack_env) begin env = {} bad_route = route_request(rack_env, env) return error_response(bad_route, env) if bad_route @before.each do |hook| result = hook.call(rack_env, env) return error_response(result, env) if result.is_a? Twirp::Error end output = call_handler(env) return error_response(output, env) if output.is_a? Twirp::Error return success_response(output, env) rescue => e raise e if self.class.raise_exceptions begin @exception_raised.each{|hook| hook.call(e, env) } rescue => hook_e e = hook_e end twerr = Twirp::Error.internal_with(e) return error_response(twerr, env) end end
ruby
{ "resource": "" }
q16892
Twirp.Service.route_request
train
def route_request(rack_env, env) rack_request = Rack::Request.new(rack_env) if rack_request.request_method != "POST" return bad_route_error("HTTP request method must be POST", rack_request) end content_type = rack_request.get_header("CONTENT_TYPE") if !Encoding.valid_content_type?(content_type) return bad_route_error("Unexpected Content-Type: #{content_type.inspect}. Content-Type header must be one of #{Encoding.valid_content_types.inspect}", rack_request) end env[:content_type] = content_type path_parts = rack_request.fullpath.split("/") if path_parts.size < 3 || path_parts[-2] != self.full_name return bad_route_error("Invalid route. Expected format: POST {BaseURL}/#{self.full_name}/{Method}", rack_request) end method_name = path_parts[-1] base_env = self.class.rpcs[method_name] if !base_env return bad_route_error("Invalid rpc method #{method_name.inspect}", rack_request) end env.merge!(base_env) # :rpc_method, :input_class, :output_class input = nil begin input = Encoding.decode(rack_request.body.read, env[:input_class], content_type) rescue => e error_msg = "Invalid request body for rpc method #{method_name.inspect} with Content-Type=#{content_type}" if e.is_a?(Google::Protobuf::ParseError) error_msg += ": #{e.message.strip}" end return bad_route_error(error_msg, rack_request) end env[:input] = input env[:http_response_headers] = {} return end
ruby
{ "resource": "" }
q16893
Twirp.ServiceDSL.rpc
train
def rpc(rpc_method, input_class, output_class, opts) raise ArgumentError.new("rpc_method can not be empty") if rpc_method.to_s.empty? raise ArgumentError.new("input_class must be a Protobuf Message class") unless input_class.is_a?(Class) raise ArgumentError.new("output_class must be a Protobuf Message class") unless output_class.is_a?(Class) raise ArgumentError.new("opts[:ruby_method] is mandatory") unless opts && opts[:ruby_method] rpcdef = { rpc_method: rpc_method.to_sym, # as defined in the Proto file. input_class: input_class, # google/protobuf Message class to serialize the input (proto request). output_class: output_class, # google/protobuf Message class to serialize the output (proto response). ruby_method: opts[:ruby_method].to_sym, # method on the handler or client to handle this rpc requests. } @rpcs ||= {} @rpcs[rpc_method.to_s] = rpcdef rpc_define_method(rpcdef) if respond_to? :rpc_define_method # hook for the client to implement the methods on the class end
ruby
{ "resource": "" }
q16894
Launchy.DescendantTracker.find_child
train
def find_child( method, *args ) children.find do |child| Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}" child.send( method, *args ) end end
ruby
{ "resource": "" }
q16895
RSpec.LoggingHelper.capture_log_messages
train
def capture_log_messages( opts = {} ) from = opts.fetch(:from, 'root') to = opts.fetch(:to, '__rspec__') exclusive = opts.fetch(:exclusive, true) appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to) logger = Logging::Logger[from] if exclusive logger.appenders = appender else logger.add_appenders(appender) end before(:all) do @log_output = Logging::Appenders[to] end before(:each) do @log_output.reset end end
ruby
{ "resource": "" }
q16896
Logging.Repository.parent_name
train
def parent_name( key ) return if :root == key a = key.split PATH_DELIMITER p = :root while a.slice!(-1) and !a.empty? k = a.join PATH_DELIMITER if @h.has_key? k then p = k; break end end p end
ruby
{ "resource": "" }
q16897
Logging::Appenders.RollingFile.build_singleton_methods
train
def build_singleton_methods method = case @age when 'daily' -> { now = Time.now (now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400 } when 'weekly' -> { (Time.now - age_fn_mtime) > 604800 } when 'monthly' -> { now = Time.now (now.month != age_fn_mtime.month) || (now - age_fn_mtime) > 2678400 } when Integer, String @age = Integer(@age) -> { (Time.now - age_fn_mtime) > @age } else -> { false } end self.define_singleton_method(:sufficiently_aged?, method) end
ruby
{ "resource": "" }
q16898
Logging::Appenders.Buffering.auto_flushing=
train
def auto_flushing=( period ) @auto_flushing = case period when true; 1 when false, nil, 0; DEFAULT_BUFFER_SIZE when Integer; period when String; Integer(period) else raise ArgumentError, "unrecognized auto_flushing period: #{period.inspect}" end if @auto_flushing <= 0 raise ArgumentError, "auto_flushing period must be greater than zero: #{period.inspect}" end @auto_flushing = DEFAULT_BUFFER_SIZE if @flush_period && @auto_flushing <= 1 end
ruby
{ "resource": "" }
q16899
Logging::Appenders.Buffering._setup_async_flusher
train
def _setup_async_flusher # stop and remove any existing async flusher instance if @async_flusher @async_flusher.stop @async_flusher = nil Thread.pass end # create a new async flusher if we have a valid flush period if @flush_period || async? @auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1 @async_flusher = AsyncFlusher.new(self, @flush_period) @async_flusher.start Thread.pass end nil end
ruby
{ "resource": "" }