_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q10900
Puppet::Util::Windows.Service.exists?
train
def exists?(service_name) open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |_| true end rescue Puppet::Util::Windows::Error => e return false if e.code == ERROR_SERVICE_DOES_NOT_EXIST raise e end
ruby
{ "resource": "" }
q10901
Puppet::Util::Windows.Service.start
train
def start(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Starting the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_STOP_PENDING, SERVICE_STOPPED, SERVICE_START_PENDING ...
ruby
{ "resource": "" }
q10902
Puppet::Util::Windows.Service.stop
train
def stop(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Stopping the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = SERVICE_STATES.keys - [SERVICE_STOPPED] transition_service_state(service_name, valid_i...
ruby
{ "resource": "" }
q10903
Puppet::Util::Windows.Service.resume
train
def resume(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Resuming the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_PAUSE_PENDING, SERVICE_PAUSED, SERVICE_CONTINUE_PENDING ...
ruby
{ "resource": "" }
q10904
Puppet::Util::Windows.Service.service_state
train
def service_state(service_name) state = nil open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |service| query_status(service) do |status| state = SERVICE_STATES[status[:dwCurrentState]] end end if state.nil? raise Puppet::Error.new(_("Unkno...
ruby
{ "resource": "" }
q10905
Puppet::Util::Windows.Service.service_start_type
train
def service_start_type(service_name) start_type = nil open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service| query_config(service) do |config| start_type = SERVICE_START_TYPES[config[:dwStartType]] end end if start_type.nil? raise Pupp...
ruby
{ "resource": "" }
q10906
Puppet::Util::Windows.Service.set_startup_mode
train
def set_startup_mode(service_name, startup_type) startup_code = SERVICE_START_TYPES.key(startup_type) if startup_code.nil? raise Puppet::Error.new(_("Unknown start type %{start_type}") % {startup_type: startup_type.to_s}) end open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_...
ruby
{ "resource": "" }
q10907
Puppet::Util::Windows.Service.services
train
def services services = {} open_scm(SC_MANAGER_ENUMERATE_SERVICE) do |scm| size_required = 0 services_returned = 0 FFI::MemoryPointer.new(:dword) do |bytes_pointer| FFI::MemoryPointer.new(:dword) do |svcs_ret_ptr| FFI::MemoryPointer.new(:dword) do |resume_ptr| ...
ruby
{ "resource": "" }
q10908
Generators.PuppetGenerator.gen_sub_directories
train
def gen_sub_directories super File.makedirs(MODULE_DIR) File.makedirs(NODE_DIR) File.makedirs(PLUGIN_DIR) rescue $stderr.puts $ERROR_INFO.message exit 1 end
ruby
{ "resource": "" }
q10909
Generators.PuppetGenerator.gen_top_index
train
def gen_top_index(collection, title, template, filename) template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template) res = [] collection.sort.each do |f| if f.document_self res << { "classlist" => CGI.escapeHTML("#{MODULE_DIR}/fr_#{f.index_name}.html"), "module" => CGI.escapeHTM...
ruby
{ "resource": "" }
q10910
Generators.PuppetGenerator.gen_class_index
train
def gen_class_index gen_an_index(@classes, 'All Classes', RDoc::Page::CLASS_INDEX, "fr_class_index.html") @allfiles.each do |file| unless file['file'].context.file_relative_name =~ /\.rb$/ gen_composite_index( file, RDoc::Page::COMBO_INDEX, "#{MODU...
ruby
{ "resource": "" }
q10911
Generators.PuppetGenerator.main_url
train
def main_url main_page = @options.main_page ref = nil if main_page ref = AllReferences[main_page] if ref ref = ref.path else $stderr.puts "Could not find main page #{main_page}" end end unless ref for file in @files if ...
ruby
{ "resource": "" }
q10912
Generators.HTMLPuppetNode.http_url
train
def http_url(full_name, prefix) path = full_name.dup path.gsub!(/<<\s*(\w*)/) { "from-#$1" } if path['<<'] File.join(prefix, path.split("::").collect { |p| Digest::MD5.hexdigest(p) }) + ".html" end
ruby
{ "resource": "" }
q10913
Puppet::Util::ProviderFeatures.ProviderFeature.methods_available?
train
def methods_available?(obj) methods.each do |m| if obj.is_a?(Class) return false unless obj.public_method_defined?(m) else return false unless obj.respond_to?(m) end end true end
ruby
{ "resource": "" }
q10914
Puppet::ModuleTool.Metadata.update
train
def update(data) process_name(data) if data['name'] process_version(data) if data['version'] process_source(data) if data['source'] process_data_provider(data) if data['data_provider'] merge_dependencies(data) if data['dependencies'] @data.merge!(data) return self end
ruby
{ "resource": "" }
q10915
Puppet::ModuleTool.Metadata.add_dependency
train
def add_dependency(name, version_requirement=nil, repository=nil) validate_name(name) validate_version_range(version_requirement) if version_requirement if dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement } raise ArgumentError, ...
ruby
{ "resource": "" }
q10916
Puppet::ModuleTool.Metadata.process_name
train
def process_name(data) validate_name(data['name']) author, @module_name = data['name'].split(/[-\/]/, 2) data['author'] ||= author if @data['author'] == DEFAULTS['author'] end
ruby
{ "resource": "" }
q10917
Puppet::ModuleTool.Metadata.process_source
train
def process_source(data) if data['source'] =~ %r[://] source_uri = URI.parse(data['source']) else source_uri = URI.parse("http://#{data['source']}") end if source_uri.host =~ /^(www\.)?github\.com$/ source_uri.scheme = 'https' source_uri.path.sub!(/\.git$/, '') ...
ruby
{ "resource": "" }
q10918
Puppet::ModuleTool.Metadata.merge_dependencies
train
def merge_dependencies(data) data['dependencies'].each do |dep| add_dependency(dep['name'], dep['version_requirement'], dep['repository']) end # Clear dependencies so @data dependencies are not overwritten data.delete 'dependencies' end
ruby
{ "resource": "" }
q10919
Puppet::ModuleTool.Metadata.validate_name
train
def validate_name(name) return if name =~ /\A[a-z0-9]+[-\/][a-z][a-z0-9_]*\Z/i namespace, modname = name.split(/[-\/]/, 2) modname = :namespace_missing if namespace == '' err = case modname when nil, '', :namespace_missing _("the field must be a namespaced module name") whe...
ruby
{ "resource": "" }
q10920
Puppet::ModuleTool.Metadata.validate_version
train
def validate_version(version) return if SemanticPuppet::Version.valid?(version) err = _("version string cannot be parsed as a valid Semantic Version") raise ArgumentError, _("Invalid 'version' field in metadata.json: %{err}") % { err: err } end
ruby
{ "resource": "" }
q10921
Puppet::ModuleTool.Metadata.validate_data_provider
train
def validate_data_provider(value) if value.is_a?(String) unless value =~ /^[a-zA-Z][a-zA-Z0-9_]*$/ if value =~ /^[a-zA-Z]/ raise ArgumentError, _("field 'data_provider' contains non-alphanumeric characters") else raise ArgumentError, _("field 'data_provider' mus...
ruby
{ "resource": "" }
q10922
Puppet::ModuleTool.Metadata.validate_version_range
train
def validate_version_range(version_range) SemanticPuppet::VersionRange.parse(version_range) rescue ArgumentError => e raise ArgumentError, _("Invalid 'version_range' field in metadata.json: %{err}") % { err: e } end
ruby
{ "resource": "" }
q10923
Puppet.Network::DefaultAuthProvider.insert_default_acl
train
def insert_default_acl self.class.default_acl.each do |acl| unless rights[acl[:acl]] Puppet.info _("Inserting default '%{acl}' (auth %{auth}) ACL") % { acl: acl[:acl], auth: acl[:authenticated] } mk_acl(acl) end end # queue an empty (ie deny all) right for every oth...
ruby
{ "resource": "" }
q10924
Puppet::Util::Windows::ADSI.User.op_userflags
train
def op_userflags(*flags, &block) # Avoid an unnecessary set + commit operation. return if flags.empty? unrecognized_flags = flags.reject { |flag| ADS_USERFLAGS.keys.include?(flag) } unless unrecognized_flags.empty? raise ArgumentError, _("Unrecognized ADS UserFlags: %{unrecognized_flags...
ruby
{ "resource": "" }
q10925
Puppet::Network.Resolver.each_srv_record
train
def each_srv_record(domain, service_name = :puppet, &block) if (domain.nil? or domain.empty?) Puppet.debug "Domain not known; skipping SRV lookup" return end Puppet.debug "Searching for SRV records for domain: #{domain}" case service_name when :puppet then service = '_x...
ruby
{ "resource": "" }
q10926
Puppet::Network.Resolver.find_weighted_server
train
def find_weighted_server(records) return nil if records.nil? || records.empty? return records.first if records.size == 1 # Calculate the sum of all weights in the list of resource records, # This is used to then select hosts until the weight exceeds what # random number we selected. For ...
ruby
{ "resource": "" }
q10927
Puppet::Network.Resolver.expired?
train
def expired?(service_name) if entry = @record_cache[service_name] return Time.now > (entry.resolution_time + entry.ttl) else return true end end
ruby
{ "resource": "" }
q10928
Puppet.Util.clear_environment
train
def clear_environment(mode = default_env) case mode when :posix ENV.clear when :windows Puppet::Util::Windows::Process.get_environment_strings.each do |key, _| Puppet::Util::Windows::Process.set_environment_variable(key, nil) end else raise _("Unable to cl...
ruby
{ "resource": "" }
q10929
Puppet.Util.which
train
def which(bin) if absolute_path?(bin) return bin if FileTest.file? bin and FileTest.executable? bin else exts = Puppet::Util.get_env('PATHEXT') exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD] Puppet::Util.get_env('PATH').split(File::PATH_SEPARATOR).each do |dir| ...
ruby
{ "resource": "" }
q10930
Puppet.Util.path_to_uri
train
def path_to_uri(path) return unless path params = { :scheme => 'file' } if Puppet::Util::Platform.windows? path = path.gsub(/\\/, '/') if unc = /^\/\/([^\/]+)(\/.+)/.match(path) params[:host] = unc[1] path = unc[2] elsif path =~ /^[a-z]:\//i path = '/' + path ...
ruby
{ "resource": "" }
q10931
Puppet.Util.uri_to_path
train
def uri_to_path(uri) return unless uri.is_a?(URI) # CGI.unescape doesn't handle space rules properly in uri paths # URI.unescape does, but returns strings in their original encoding path = URI.unescape(uri.path.encode(Encoding::UTF_8)) if Puppet::Util::Platform.windows? && uri.scheme == 'file' ...
ruby
{ "resource": "" }
q10932
Puppet.Util.exit_on_fail
train
def exit_on_fail(message, code = 1) yield # First, we need to check and see if we are catching a SystemExit error. These will be raised # when we daemonize/fork, and they do not necessarily indicate a failure case. rescue SystemExit => err raise err # Now we need to catch *any* other kind of exceptio...
ruby
{ "resource": "" }
q10933
Puppet::Pops::Evaluator.Runtime3Converter.map_args
train
def map_args(args, scope, undef_value) args.map {|a| convert(a, scope, undef_value) } end
ruby
{ "resource": "" }
q10934
Puppet.Type.delete
train
def delete(attr) attr = attr.intern if @parameters.has_key?(attr) @parameters.delete(attr) else raise Puppet::DevError.new(_("Undefined attribute '%{attribute}' in %{name}") % { attribute: attr, name: self}) end end
ruby
{ "resource": "" }
q10935
Puppet.Type.managed?
train
def managed? # Once an object is managed, it always stays managed; but an object # that is listed as unmanaged might become managed later in the process, # so we have to check that every time if @managed return @managed else @managed = false properties.each { |property| s =...
ruby
{ "resource": "" }
q10936
Puppet.Type.retrieve
train
def retrieve fail "Provider #{provider.class.name} is not functional on this host" if self.provider.is_a?(Puppet::Provider) and ! provider.class.suitable? result = Puppet::Resource.new(self.class, title) # Provide the name, so we know we'll always refer to a real thing result[:name] = self[:name] unle...
ruby
{ "resource": "" }
q10937
Puppet.Type.builddepends
train
def builddepends # Handle the requires self.class.relationship_params.collect do |klass| if param = @parameters[klass.name] param.to_edges end end.flatten.reject { |r| r.nil? } end
ruby
{ "resource": "" }
q10938
Puppet.Type.set_sensitive_parameters
train
def set_sensitive_parameters(sensitive_parameters) sensitive_parameters.each do |name| p = parameter(name) if p.is_a?(Puppet::Property) p.sensitive = true elsif p.is_a?(Puppet::Parameter) warning(_("Unable to mark '%{name}' as sensitive: %{name} is a parameter and not a property, a...
ruby
{ "resource": "" }
q10939
Puppet.Type.finish
train
def finish # Call post_compile hook on every parameter that implements it. This includes all subclasses # of parameter including, but not limited to, regular parameters, metaparameters, relationship # parameters, and properties. eachparameter do |parameter| parameter.post_compile if parameter.resp...
ruby
{ "resource": "" }
q10940
Puppet::Environments.EnvironmentCreator.for
train
def for(module_path, manifest) Puppet::Node::Environment.create(:anonymous, module_path.split(File::PATH_SEPARATOR), manifest) end
ruby
{ "resource": "" }
q10941
Puppet::Environments.Static.get_conf
train
def get_conf(name) env = get(name) if env Puppet::Settings::EnvironmentConf.static_for(env, Puppet[:environment_timeout], Puppet[:static_catalogs], Puppet[:rich_data]) else nil end end
ruby
{ "resource": "" }
q10942
Puppet::Environments.Cached.add_entry
train
def add_entry(name, cache_entry) Puppet.debug {"Caching environment '#{name}' #{cache_entry.label}"} @cache[name] = cache_entry expires = cache_entry.expires @expirations.add(expires) if @next_expiration > expires @next_expiration = expires end end
ruby
{ "resource": "" }
q10943
Puppet::Environments.Cached.clear_all_expired
train
def clear_all_expired() t = Time.now return if t < @next_expiration && ! @cache.any? {|name, _| @cache_expiration_service.expired?(name.to_sym) } to_expire = @cache.select { |name, entry| entry.expires < t || @cache_expiration_service.expired?(name.to_sym) } to_expire.each do |name, entry| ...
ruby
{ "resource": "" }
q10944
Puppet::Environments.Cached.entry
train
def entry(env) ttl = (conf = get_conf(env.name)) ? conf.environment_timeout : Puppet.settings.value(:environment_timeout) case ttl when 0 NotCachedEntry.new(env) # Entry that is always expired (avoids syscall to get time) when Float::INFINITY Entry.new(env) # Ent...
ruby
{ "resource": "" }
q10945
Puppet::Environments.Cached.evict_if_expired
train
def evict_if_expired(name) if (result = @cache[name]) && (result.expired? || @cache_expiration_service.expired?(name)) Puppet.debug {"Evicting cache entry for environment '#{name}'"} @cache_expiration_service.evicted(name) clear(name) Puppet.settings.clear_environment_settings(name...
ruby
{ "resource": "" }
q10946
Puppet::ModuleTool.Checksums.data
train
def data unless @data @data = {} @path.find do |descendant| if Puppet::ModuleTool.artifact?(descendant) Find.prune elsif descendant.file? path = descendant.relative_path_from(@path) @data[path.to_s] = checksum(descendant) end ...
ruby
{ "resource": "" }
q10947
Puppet::Rest.Route.with_base_url
train
def with_base_url(dns_resolver) if @server && @port # First try connecting to the previously selected server and port. begin return yield(base_url) rescue SystemCallError => e if Puppet[:use_srv_records] Puppet.debug "Connection to cached server and port #{@...
ruby
{ "resource": "" }
q10948
Puppet.Application.run
train
def run # I don't really like the names of these lifecycle phases. It would be nice to change them to some more meaningful # names, and make deprecated aliases. --cprice 2012-03-16 exit_on_fail(_("Could not get application-specific default settings")) do initialize_app_defaults end Puppet...
ruby
{ "resource": "" }
q10949
Puppet.Application.log_runtime_environment
train
def log_runtime_environment(extra_info=nil) runtime_info = { 'puppet_version' => Puppet.version, 'ruby_version' => RUBY_VERSION, 'run_mode' => self.class.run_mode.name, } runtime_info['default_encoding'] = Encoding.default_external runtime_info.merge!(extra_info) unless extra_i...
ruby
{ "resource": "" }
q10950
Puppet::Functions.DispatcherBuilder.required_repeated_param
train
def required_repeated_param(type, name) internal_param(type, name, true) raise ArgumentError, _('A required repeated parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max = :default end
ruby
{ "resource": "" }
q10951
Puppet::Functions.DispatcherBuilder.block_param
train
def block_param(*type_and_name) case type_and_name.size when 0 type = @all_callables name = :block when 1 type = @all_callables name = type_and_name[0] when 2 type, name = type_and_name type = Puppet::Pops::Types::TypeParser.singleton.parse(type, l...
ruby
{ "resource": "" }
q10952
Puppet::Functions.LocalTypeAliasesBuilder.type
train
def type(assignment_string) # Get location to use in case of error - this produces ruby filename and where call to 'type' occurred # but strips off the rest of the internal "where" as it is not meaningful to user. # rb_location = caller[0] begin result = parser.parse_string("type ...
ruby
{ "resource": "" }
q10953
Puppet::Pops.MergeStrategy.lookup
train
def lookup(lookup_variants, lookup_invocation) case lookup_variants.size when 0 throw :no_such_key when 1 merge_single(yield(lookup_variants[0])) else lookup_invocation.with(:merge, self) do result = lookup_variants.reduce(NOT_FOUND) do |memo, lookup_variant| ...
ruby
{ "resource": "" }
q10954
Puppet::Network::HTTP::Compression.Active.uncompress_body
train
def uncompress_body(response) case response['content-encoding'] when 'gzip' # ZLib::GzipReader has an associated encoding, by default Encoding.default_external return Zlib::GzipReader.new(StringIO.new(response.body), :encoding => Encoding::BINARY).read when 'deflate' return Zli...
ruby
{ "resource": "" }
q10955
Puppet::Network.Rights.newright
train
def newright(name, line=nil, file=nil) add_right( Right.new(name, line, file) ) end
ruby
{ "resource": "" }
q10956
Puppet.Network::AuthStore.allowed?
train
def allowed?(name, ip) if name or ip # This is probably unnecessary, and can cause some weirdness in # cases where we're operating over localhost but don't have a real # IP defined. raise Puppet::DevError, _("Name and IP must be passed to 'allowed?'") unless name and ip # e...
ruby
{ "resource": "" }
q10957
Puppet::MetaType.Manager.type
train
def type(name) # Avoid loading if name obviously is not a type name if name.to_s.include?(':') return nil end @types ||= {} # We are overwhelmingly symbols here, which usually match, so it is worth # having this special-case to return quickly. Like, 25K symbols vs. 300 # strings in ...
ruby
{ "resource": "" }
q10958
Puppet::Pops.Loaders.[]
train
def [](loader_name) loader = @loaders_by_name[loader_name] if loader.nil? # Unable to find the module private loader. Try resolving the module loader = private_loader_for_module(loader_name[0..-9]) if loader_name.end_with?(' private') raise Puppet::ParseError, _("Unable to find loader named '%...
ruby
{ "resource": "" }
q10959
Puppet::Pops.Loaders.find_loader
train
def find_loader(module_name) if module_name.nil? || EMPTY_STRING == module_name # Use the public environment loader public_environment_loader else # TODO : Later check if definition is private, and then add it to private_loader_for_module # loader = public_loader_for_module(module_...
ruby
{ "resource": "" }
q10960
Puppet::Pops.Loaders.load_main_manifest
train
def load_main_manifest parser = Parser::EvaluatingParser.singleton parsed_code = Puppet[:code] program = if parsed_code != "" parser.parse_string(parsed_code, 'unknown-source-location') else file = @environment.manifest # if the manifest file is a reference to a directory, parse and c...
ruby
{ "resource": "" }
q10961
Puppet::Pops.Loaders.instantiate_definitions
train
def instantiate_definitions(program, loader) program.definitions.each { |d| instantiate_definition(d, loader) } nil end
ruby
{ "resource": "" }
q10962
Puppet::Pops.Loaders.instantiate_definition
train
def instantiate_definition(definition, loader) case definition when Model::PlanDefinition instantiate_PlanDefinition(definition, loader) when Model::FunctionDefinition instantiate_FunctionDefinition(definition, loader) when Model::TypeAlias instantiate_TypeAlias(definition, loader) ...
ruby
{ "resource": "" }
q10963
Puppet::Util::IniConfig.Section.[]=
train
def []=(key, value) entry = find_entry(key) @dirty = true if entry.nil? @entries << [key, value] else entry[1] = value end end
ruby
{ "resource": "" }
q10964
Puppet::Util::IniConfig.Section.format
train
def format if @destroy text = "" else text = "[#{name}]\n" @entries.each do |entry| if entry.is_a?(Array) key, value = entry text << "#{key}=#{value}\n" unless value.nil? else text << entry end end end ...
ruby
{ "resource": "" }
q10965
Puppet::Util::IniConfig.PhysicalFile.read
train
def read text = @filetype.read if text.nil? raise IniParseError, _("Cannot read nonexistent file %{file}") % { file: @file.inspect } end parse(text) end
ruby
{ "resource": "" }
q10966
Puppet::Util::IniConfig.PhysicalFile.add_section
train
def add_section(name) if section_exists?(name) raise IniParseError.new(_("Section %{name} is already defined, cannot redefine") % { name: name.inspect }, @file) end section = Section.new(name, @file) @contents << section section end
ruby
{ "resource": "" }
q10967
Puppet.ExternalFileError.to_s
train
def to_s msg = super @file = nil if (@file.is_a?(String) && @file.empty?) msg += Puppet::Util::Errors.error_location_with_space(@file, @line, @pos) msg end
ruby
{ "resource": "" }
q10968
Puppet::Network::HTTP.Connection.handle_retry_after
train
def handle_retry_after(response) retry_after = response['Retry-After'] return response if retry_after.nil? retry_sleep = parse_retry_after_header(retry_after) # Recover remote hostname if Net::HTTPResponse was generated by a # method that fills in the uri attribute. # server_h...
ruby
{ "resource": "" }
q10969
Puppet::Network::HTTP.Connection.parse_retry_after_header
train
def parse_retry_after_header(header_value) retry_after = begin Integer(header_value) rescue TypeError, ArgumentError begin DateTime.rfc2822(header_value) rescue ArgumentError retur...
ruby
{ "resource": "" }
q10970
Puppet::Util::Windows.Registry.values_by_name
train
def values_by_name(key, names) vals = {} names.each do |name| FFI::Pointer.from_string_to_wide_string(name) do |subkeyname_ptr| begin _, vals[name] = read(key, subkeyname_ptr) rescue Puppet::Util::Windows::Error => e # ignore missing names, but raise other...
ruby
{ "resource": "" }
q10971
Puppet::Util::FileParsing.FileRecord.fields=
train
def fields=(fields) @fields = fields.collect do |field| r = field.intern raise ArgumentError.new(_("Cannot have fields named %{name}") % { name: r }) if INVALID_FIELDS.include?(r) r end end
ruby
{ "resource": "" }
q10972
Puppet::Util::FileParsing.FileRecord.join
train
def join(details) joinchar = self.joiner fields.collect { |field| # If the field is marked absent, use the appropriate replacement if details[field] == :absent or details[field] == [:absent] or details[field].nil? if self.optional.include?(field) self.absent ...
ruby
{ "resource": "" }
q10973
Kafka.RoundRobinAssignmentStrategy.assign
train
def assign(members:, topics:) group_assignment = {} members.each do |member_id| group_assignment[member_id] = Protocol::MemberAssignment.new end topic_partitions = topics.flat_map do |topic| begin partitions = @cluster.partitions_for(topic).map(&:partition_id) ...
ruby
{ "resource": "" }
q10974
Kafka.MessageBuffer.clear_messages
train
def clear_messages(topic:, partition:) return unless @buffer.key?(topic) && @buffer[topic].key?(partition) @size -= @buffer[topic][partition].count @bytesize -= @buffer[topic][partition].map(&:bytesize).reduce(0, :+) @buffer[topic].delete(partition) @buffer.delete(topic) if @buffer[topic...
ruby
{ "resource": "" }
q10975
Kafka.Client.deliver_message
train
def deliver_message(value, key: nil, headers: {}, topic:, partition: nil, partition_key: nil, retries: 1) create_time = Time.now message = PendingMessage.new( value: value, key: key, headers: headers, topic: topic, partition: partition, partition_key: partiti...
ruby
{ "resource": "" }
q10976
Kafka.Client.producer
train
def producer( compression_codec: nil, compression_threshold: 1, ack_timeout: 5, required_acks: :all, max_retries: 2, retry_backoff: 1, max_buffer_size: 1000, max_buffer_bytesize: 10_000_000, idempotent: false, transactional: false, transactional_id: nil,...
ruby
{ "resource": "" }
q10977
Kafka.Client.async_producer
train
def async_producer(delivery_interval: 0, delivery_threshold: 0, max_queue_size: 1000, max_retries: -1, retry_backoff: 0, **options) sync_producer = producer(**options) AsyncProducer.new( sync_producer: sync_producer, delivery_interval: delivery_interval, delivery_threshold: delivery...
ruby
{ "resource": "" }
q10978
Kafka.Client.consumer
train
def consumer( group_id:, session_timeout: 30, offset_commit_interval: 10, offset_commit_threshold: 0, heartbeat_interval: 10, offset_retention_time: nil, fetcher_max_queue_size: 100 ) cluster = initialize_cluster instrumenter = DecoratingInstrumen...
ruby
{ "resource": "" }
q10979
Kafka.Client.fetch_messages
train
def fetch_messages(topic:, partition:, offset: :latest, max_wait_time: 5, min_bytes: 1, max_bytes: 1048576, retries: 1) operation = FetchOperation.new( cluster: @cluster, logger: @logger, min_bytes: min_bytes, max_bytes: max_bytes, max_wait_time: max_wait_time, ) ...
ruby
{ "resource": "" }
q10980
Kafka.Client.each_message
train
def each_message(topic:, start_from_beginning: true, max_wait_time: 5, min_bytes: 1, max_bytes: 1048576, &block) default_offset ||= start_from_beginning ? :earliest : :latest offsets = Hash.new { default_offset } loop do operation = FetchOperation.new( cluster: @cluster, l...
ruby
{ "resource": "" }
q10981
Kafka.Client.create_topic
train
def create_topic(name, num_partitions: 1, replication_factor: 1, timeout: 30, config: {}) @cluster.create_topic( name, num_partitions: num_partitions, replication_factor: replication_factor, timeout: timeout, config: config, ) end
ruby
{ "resource": "" }
q10982
Kafka.Client.create_partitions_for
train
def create_partitions_for(name, num_partitions: 1, timeout: 30) @cluster.create_partitions_for(name, num_partitions: num_partitions, timeout: timeout) end
ruby
{ "resource": "" }
q10983
Kafka.Client.last_offsets_for
train
def last_offsets_for(*topics) @cluster.add_target_topics(topics) topics.map {|topic| partition_ids = @cluster.partitions_for(topic).collect(&:partition_id) partition_offsets = @cluster.resolve_offsets(topic, partition_ids, :latest) [topic, partition_offsets.collect { |k, v| [k, v - 1...
ruby
{ "resource": "" }
q10984
Kafka.Cluster.add_target_topics
train
def add_target_topics(topics) topics = Set.new(topics) unless topics.subset?(@target_topics) new_topics = topics - @target_topics unless new_topics.empty? @logger.info "New topics added to target list: #{new_topics.to_a.join(', ')}" @target_topics.merge(new_topics) ...
ruby
{ "resource": "" }
q10985
Kafka.Cluster.get_transaction_coordinator
train
def get_transaction_coordinator(transactional_id:) @logger.debug "Getting transaction coordinator for `#{transactional_id}`" refresh_metadata_if_necessary! if transactional_id.nil? # Get a random_broker @logger.debug "Transaction ID is not available. Choose a random broker." ...
ruby
{ "resource": "" }
q10986
Kafka.Cluster.list_topics
train
def list_topics response = random_broker.fetch_metadata(topics: nil) response.topics.select do |topic| topic.topic_error_code == 0 end.map(&:topic_name) end
ruby
{ "resource": "" }
q10987
Kafka.Cluster.fetch_cluster_info
train
def fetch_cluster_info errors = [] @seed_brokers.shuffle.each do |node| @logger.info "Fetching cluster metadata from #{node}" begin broker = @broker_pool.connect(node.hostname, node.port) cluster_info = broker.fetch_metadata(topics: @target_topics) if cluster...
ruby
{ "resource": "" }
q10988
Kafka.AsyncProducer.produce
train
def produce(value, topic:, **options) ensure_threads_running! if @queue.size >= @max_queue_size buffer_overflow topic, "Cannot produce to #{topic}, max queue size (#{@max_queue_size} messages) reached" end args = [value, **options.merge(topic: topic)] @queue << [:produc...
ruby
{ "resource": "" }
q10989
Kafka.SSLSocketWithTimeout.write
train
def write(bytes) loop do written = 0 begin # unlike plain tcp sockets, ssl sockets don't support IO.select # properly. # Instead, timeouts happen on a per write basis, and we have to # catch exceptions from write_nonblock, and gradually build up # ...
ruby
{ "resource": "" }
q10990
Kafka.Consumer.subscribe
train
def subscribe(topic_or_regex, default_offset: nil, start_from_beginning: true, max_bytes_per_partition: 1048576) default_offset ||= start_from_beginning ? :earliest : :latest if topic_or_regex.is_a?(Regexp) cluster_topics.select { |topic| topic =~ topic_or_regex }.each do |topic| subscrib...
ruby
{ "resource": "" }
q10991
Kafka.Consumer.pause
train
def pause(topic, partition, timeout: nil, max_timeout: nil, exponential_backoff: false) if max_timeout && !exponential_backoff raise ArgumentError, "`max_timeout` only makes sense when `exponential_backoff` is enabled" end pause_for(topic, partition).pause!( timeout: timeout, ...
ruby
{ "resource": "" }
q10992
Kafka.Consumer.resume
train
def resume(topic, partition) pause_for(topic, partition).resume! # During re-balancing we might have lost the paused partition. Check if partition is still in group before seek. seek_to_next(topic, partition) if @group.assigned_to?(topic, partition) end
ruby
{ "resource": "" }
q10993
Kafka.Consumer.paused?
train
def paused?(topic, partition) pause = pause_for(topic, partition) pause.paused? && !pause.expired? end
ruby
{ "resource": "" }
q10994
Kafka.OffsetManager.seek_to_default
train
def seek_to_default(topic, partition) # Remove any cached offset, in case things have changed broker-side. clear_resolved_offset(topic) offset = resolve_offset(topic, partition) seek_to(topic, partition, offset) end
ruby
{ "resource": "" }
q10995
Kafka.OffsetManager.seek_to
train
def seek_to(topic, partition, offset) @processed_offsets[topic] ||= {} @processed_offsets[topic][partition] = offset @fetcher.seek(topic, partition, offset) end
ruby
{ "resource": "" }
q10996
Kafka.OffsetManager.next_offset_for
train
def next_offset_for(topic, partition) offset = @processed_offsets.fetch(topic, {}).fetch(partition) { committed_offset_for(topic, partition) } # A negative offset means that no offset has been committed, so we need to # resolve the default offset for the topic. if offset < 0 ...
ruby
{ "resource": "" }
q10997
Kafka.OffsetManager.commit_offsets
train
def commit_offsets(recommit = false) offsets = offsets_to_commit(recommit) unless offsets.empty? @logger.debug "Committing offsets#{recommit ? ' with recommit' : ''}: #{prettify_offsets(offsets)}" @group.commit_offsets(offsets) @last_commit = Time.now @last_recommit = Time....
ruby
{ "resource": "" }
q10998
Kafka.OffsetManager.clear_offsets_excluding
train
def clear_offsets_excluding(excluded) # Clear all offsets that aren't in `excluded`. @processed_offsets.each do |topic, partitions| partitions.keep_if do |partition, _| excluded.fetch(topic, []).include?(partition) end end # Clear the cached commits from the brokers. ...
ruby
{ "resource": "" }
q10999
Kafka.Connection.send_request
train
def send_request(request) api_name = Protocol.api_name(request.api_key) # Default notification payload. notification = { broker_host: @host, api: api_name, request_size: 0, response_size: 0, } raise IdleConnection if idle? @logger.push_tags(api_name...
ruby
{ "resource": "" }