_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q12000 | Axlsx.SerializedAttributes.serialized_attributes | train | def serialized_attributes(str = '', additional_attributes = {})
attributes = declared_attributes.merge! additional_attributes
attributes.each do |key, value|
str << "#{Axlsx.camel(key, false)}=\"#{Axlsx.camel(Axlsx.booleanize(value), false)}\" "
end
str
end | ruby | {
"resource": ""
} |
q12001 | Axlsx.SerializedAttributes.declared_attributes | train | def declared_attributes
instance_values.select do |key, value|
value != nil && self.class.xml_attributes.include?(key.to_sym)
end
end | ruby | {
"resource": ""
} |
q12002 | Axlsx.SerializedAttributes.serialized_element_attributes | train | def serialized_element_attributes(str='', additional_attributes=[], &block)
attrs = self.class.xml_element_attributes + additional_attributes
values = instance_values
attrs.each do |attribute_name|
value = values[attribute_name.to_s]
next if value.nil?
value = yield value if block_given?
element_name = Axlsx.camel(attribute_name, false)
str << "<#{element_name}>#{value}</#{element_name}>"
end
str
end | ruby | {
"resource": ""
} |
q12003 | Axlsx.DLbls.to_xml_string | train | def to_xml_string(str = '')
validate_attributes_for_chart_type
str << '<c:dLbls>'
%w(d_lbl_pos show_legend_key show_val show_cat_name show_ser_name show_percent show_bubble_size show_leader_lines).each do |key|
next unless instance_values.keys.include?(key) && instance_values[key] != nil
str << "<c:#{Axlsx::camel(key, false)} val='#{instance_values[key]}' />"
end
str << '</c:dLbls>'
end | ruby | {
"resource": ""
} |
q12004 | Axlsx.LineChart.node_name | train | def node_name
path = self.class.to_s
if i = path.rindex('::')
path = path[(i+2)..-1]
end
path[0] = path[0].chr.downcase
path
end | ruby | {
"resource": ""
} |
q12005 | Axlsx.App.to_xml_string | train | def to_xml_string(str = '')
str << '<?xml version="1.0" encoding="UTF-8"?>'
str << ('<Properties xmlns="' << APP_NS << '" xmlns:vt="' << APP_NS_VT << '">')
instance_values.each do |key, value|
node_name = Axlsx.camel(key)
str << "<#{node_name}>#{value}</#{node_name}>"
end
str << '</Properties>'
end | ruby | {
"resource": ""
} |
q12006 | Axlsx.Cell.merge | train | def merge(target)
start, stop = if target.is_a?(String)
[self.r, target]
elsif(target.is_a?(Cell))
Axlsx.sort_cells([self, target]).map { |c| c.r }
end
self.row.worksheet.merge_cells "#{start}:#{stop}" unless stop.nil?
end | ruby | {
"resource": ""
} |
q12007 | Axlsx.Cell.autowidth | train | def autowidth
return if is_formula? || value.nil?
if contains_rich_text?
string_width('', font_size) + value.autowidth
elsif styles.cellXfs[style].alignment && styles.cellXfs[style].alignment.wrap_text
max_width = 0
value.to_s.split(/\r?\n/).each do |line|
width = string_width(line, font_size)
max_width = width if width > max_width
end
max_width
else
string_width(value, font_size)
end
end | ruby | {
"resource": ""
} |
q12008 | Axlsx.Cell.cell_type_from_value | train | def cell_type_from_value(v)
if v.is_a?(Date)
:date
elsif v.is_a?(Time)
:time
elsif v.is_a?(TrueClass) || v.is_a?(FalseClass)
:boolean
elsif v.to_s =~ Axlsx::NUMERIC_REGEX
:integer
elsif v.to_s =~ Axlsx::FLOAT_REGEX
:float
elsif v.to_s =~ Axlsx::ISO_8601_REGEX
:iso_8601
elsif v.is_a? RichText
:richtext
else
:string
end
end | ruby | {
"resource": ""
} |
q12009 | Axlsx.Cell.cast_value | train | def cast_value(v)
return v if v.is_a?(RichText) || v.nil?
case type
when :date
self.style = STYLE_DATE if self.style == 0
v
when :time
self.style = STYLE_DATE if self.style == 0
if !v.is_a?(Time) && v.respond_to?(:to_time)
v.to_time
else
v
end
when :float
v.to_f
when :integer
v.to_i
when :boolean
v ? 1 : 0
when :iso_8601
#consumer is responsible for ensuring the iso_8601 format when specifying this type
v
else
v.to_s
end
end | ruby | {
"resource": ""
} |
q12010 | Axlsx.Filters.apply | train | def apply(cell)
return false unless cell
filter_items.each do |filter|
return false if cell.value == filter.val
end
true
end | ruby | {
"resource": ""
} |
q12011 | Axlsx.Filters.to_xml_string | train | def to_xml_string(str = '')
str << "<filters #{serialized_attributes}>"
filter_items.each { |filter| filter.to_xml_string(str) }
date_group_items.each { |date_group_item| date_group_item.to_xml_string(str) }
str << '</filters>'
end | ruby | {
"resource": ""
} |
q12012 | Axlsx.Filters.date_group_items= | train | def date_group_items=(options)
options.each do |date_group|
raise ArgumentError, "date_group_items should be an array of hashes specifying the options for each date_group_item" unless date_group.is_a?(Hash)
date_group_items << DateGroupItem.new(date_group)
end
end | ruby | {
"resource": ""
} |
q12013 | Axlsx.SheetProtection.create_password_hash | train | def create_password_hash(password)
encoded_password = encode_password(password)
password_as_hex = [encoded_password].pack("v")
password_as_string = password_as_hex.unpack("H*").first.upcase
password_as_string[2..3] + password_as_string[0..1]
end | ruby | {
"resource": ""
} |
q12014 | Axlsx.NumData.data= | train | def data=(values=[])
@tag_name = values.first.is_a?(Cell) ? :numCache : :numLit
values.each do |value|
value = value.is_formula? ? 0 : value.value if value.is_a?(Cell)
@pt << NumVal.new(:v => value)
end
end | ruby | {
"resource": ""
} |
q12015 | Axlsx.Table.name= | train | def name=(v)
DataTypeValidator.validate :table_name, [String], v
if v.is_a?(String)
@name = v
end
end | ruby | {
"resource": ""
} |
q12016 | Axlsx.ConditionalFormattingRule.to_xml_string | train | def to_xml_string(str = '')
str << '<cfRule '
serialized_attributes str
str << '>'
str << ('<formula>' << [*self.formula].join('</formula><formula>') << '</formula>') if @formula
@color_scale.to_xml_string(str) if @color_scale && @type == :colorScale
@data_bar.to_xml_string(str) if @data_bar && @type == :dataBar
@icon_set.to_xml_string(str) if @icon_set && @type == :iconSet
str << '</cfRule>'
end | ruby | {
"resource": ""
} |
q12017 | Axlsx.WorksheetHyperlink.ref= | train | def ref=(cell_reference)
cell_reference = cell_reference.r if cell_reference.is_a?(Cell)
Axlsx::validate_string cell_reference
@ref = cell_reference
end | ruby | {
"resource": ""
} |
q12018 | Axlsx.Core.to_xml_string | train | def to_xml_string(str = '')
str << '<?xml version="1.0" encoding="UTF-8"?>'
str << ('<cp:coreProperties xmlns:cp="' << CORE_NS << '" xmlns:dc="' << CORE_NS_DC << '" ')
str << ('xmlns:dcmitype="' << CORE_NS_DCMIT << '" xmlns:dcterms="' << CORE_NS_DCT << '" ')
str << ('xmlns:xsi="' << CORE_NS_XSI << '">')
str << ('<dc:creator>' << self.creator << '</dc:creator>')
str << ('<dcterms:created xsi:type="dcterms:W3CDTF">' << (created || Time.now).strftime('%Y-%m-%dT%H:%M:%S') << 'Z</dcterms:created>')
str << '<cp:revision>0</cp:revision>'
str << '</cp:coreProperties>'
end | ruby | {
"resource": ""
} |
q12019 | Axlsx.MergedCells.add | train | def add(cells)
self << if cells.is_a?(String)
cells
elsif cells.is_a?(Array)
Axlsx::cell_range(cells, false)
elsif cells.is_a?(Row)
Axlsx::cell_range(cells, false)
end
end | ruby | {
"resource": ""
} |
q12020 | Geocoder::Lookup.BanDataGouvFr.search_geocode_ban_fr_params | train | def search_geocode_ban_fr_params(query)
params = {
q: query.sanitized_text
}
unless (limit = query.options[:limit]).nil? || !limit_param_is_valid?(limit)
params[:limit] = limit.to_i
end
unless (autocomplete = query.options[:autocomplete]).nil? || !autocomplete_param_is_valid?(autocomplete)
params[:autocomplete] = autocomplete.to_s
end
unless (type = query.options[:type]).nil? || !type_param_is_valid?(type)
params[:type] = type.downcase
end
unless (postcode = query.options[:postcode]).nil? || !code_param_is_valid?(postcode)
params[:postcode] = postcode.to_s
end
unless (citycode = query.options[:citycode]).nil? || !code_param_is_valid?(citycode)
params[:citycode] = citycode.to_s
end
params
end | ruby | {
"resource": ""
} |
q12021 | Geocoder::Lookup.BanDataGouvFr.reverse_geocode_ban_fr_params | train | def reverse_geocode_ban_fr_params(query)
lat_lon = query.coordinates
params = {
lat: lat_lon.first,
lon: lat_lon.last
}
unless (type = query.options[:type]).nil? || !type_param_is_valid?(type)
params[:type] = type.downcase
end
params
end | ruby | {
"resource": ""
} |
q12022 | Geocoder.Lookup.classify_name | train | def classify_name(filename)
filename.to_s.split("_").map{ |i| i[0...1].upcase + i[1..-1] }.join
end | ruby | {
"resource": ""
} |
q12023 | Geocoder::Lookup.Maxmind.configured_service! | train | def configured_service!
if s = configuration[:service] and services.keys.include?(s)
return s
else
raise(
Geocoder::ConfigurationError,
"When using MaxMind you MUST specify a service name: " +
"Geocoder.configure(:maxmind => {:service => ...}), " +
"where '...' is one of: #{services.keys.inspect}"
)
end
end | ruby | {
"resource": ""
} |
q12024 | Geocoder.Cache.[] | train | def [](url)
interpret case
when store.respond_to?(:[])
store[key_for(url)]
when store.respond_to?(:get)
store.get key_for(url)
when store.respond_to?(:read)
store.read key_for(url)
end
end | ruby | {
"resource": ""
} |
q12025 | Geocoder.Cache.[]= | train | def []=(url, value)
case
when store.respond_to?(:[]=)
store[key_for(url)] = value
when store.respond_to?(:set)
store.set key_for(url), value
when store.respond_to?(:write)
store.write key_for(url), value
end
end | ruby | {
"resource": ""
} |
q12026 | SimpleForm.FormBuilder.full_error | train | def full_error(attribute_name, options = {})
options = options.dup
options[:error_prefix] ||= if object.class.respond_to?(:human_attribute_name)
object.class.human_attribute_name(attribute_name.to_s)
else
attribute_name.to_s.humanize
end
error(attribute_name, options)
end | ruby | {
"resource": ""
} |
q12027 | SimpleForm.FormBuilder.lookup_model_names | train | def lookup_model_names #:nodoc:
@lookup_model_names ||= begin
child_index = options[:child_index]
names = object_name.to_s.scan(/(?!\d)\w+/).flatten
names.delete(child_index) if child_index
names.each { |name| name.gsub!('_attributes', '') }
names.freeze
end
end | ruby | {
"resource": ""
} |
q12028 | SimpleForm.FormBuilder.lookup_action | train | def lookup_action #:nodoc:
@lookup_action ||= begin
action = template.controller && template.controller.action_name
return unless action
action = action.to_s
ACTIONS[action] || action
end
end | ruby | {
"resource": ""
} |
q12029 | SimpleForm.FormBuilder.find_input | train | def find_input(attribute_name, options = {}, &block)
column = find_attribute_column(attribute_name)
input_type = default_input_type(attribute_name, column, options)
if block_given?
SimpleForm::Inputs::BlockInput.new(self, attribute_name, column, input_type, options, &block)
else
find_mapping(input_type).new(self, attribute_name, column, input_type, options)
end
end | ruby | {
"resource": ""
} |
q12030 | OneGadget.Helper.valid_elf_file? | train | def valid_elf_file?(path)
# A light-weight way to check if is a valid ELF file
# Checks at least one phdr should present.
File.open(path) { |f| ELFTools::ELFFile.new(f).each_segments.first }
true
rescue ELFTools::ELFError
false
end | ruby | {
"resource": ""
} |
q12031 | OneGadget.Helper.build_id_of | train | def build_id_of(path)
File.open(path) { |f| ELFTools::ELFFile.new(f).build_id }
end | ruby | {
"resource": ""
} |
q12032 | OneGadget.Helper.colorize | train | def colorize(str, sev: :normal_s)
return str unless color_enabled?
cc = COLOR_CODE
color = cc.key?(sev) ? cc[sev] : ''
"#{color}#{str.sub(cc[:esc_m], color)}#{cc[:esc_m]}"
end | ruby | {
"resource": ""
} |
q12033 | OneGadget.Helper.url_request | train | def url_request(url)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = ::OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
raise ArgumentError, "Fail to get response of #{url}" unless %w[200 302].include?(response.code)
response.code == '302' ? response['location'] : response.body
rescue NoMethodError, SocketError, ArgumentError => e
OneGadget::Logger.error(e.message)
nil
end | ruby | {
"resource": ""
} |
q12034 | OneGadget.Helper.architecture | train | def architecture(file)
return :invalid unless File.exist?(file)
f = File.open(file)
str = ELFTools::ELFFile.new(f).machine
{
'Advanced Micro Devices X86-64' => :amd64,
'Intel 80386' => :i386,
'ARM' => :arm,
'AArch64' => :aarch64,
'MIPS R3000' => :mips
}[str] || :unknown
rescue ELFTools::ELFError # not a valid ELF
:invalid
ensure
f&.close
end | ruby | {
"resource": ""
} |
q12035 | OneGadget.Helper.find_objdump | train | def find_objdump(arch)
[
which('objdump'),
which(arch_specific_objdump(arch))
].find { |bin| objdump_arch_supported?(bin, arch) }
end | ruby | {
"resource": ""
} |
q12036 | OneGadget.ABI.stack_register? | train | def stack_register?(reg)
%w[esp ebp rsp rbp sp x29].include?(reg)
end | ruby | {
"resource": ""
} |
q12037 | OneGadget.Logger.ask_update | train | def ask_update(msg: '')
name = 'one_gadget'
cmd = OneGadget::Helper.colorize("gem update #{name} && gem cleanup #{name}")
OneGadget::Logger.info(msg + "\n" + "Update with: $ #{cmd}" + "\n")
end | ruby | {
"resource": ""
} |
q12038 | OneGadget.CLI.work | train | def work(argv)
@options = DEFAULT_OPTIONS.dup
parser.parse!(argv)
return show("OneGadget Version #{OneGadget::VERSION}") if @options[:version]
return info_build_id(@options[:info]) if @options[:info]
libc_file = argv.pop
build_id = @options[:build_id]
level = @options[:level]
return error('Either FILE or BuildID can be passed') if libc_file && @options[:build_id]
return show(parser.help) && false unless build_id || libc_file
gadgets = if build_id
OneGadget.gadgets(build_id: build_id, details: true, level: level)
else # libc_file
OneGadget.gadgets(file: libc_file, details: true, force_file: @options[:force_file], level: level)
end
handle_gadgets(gadgets, libc_file)
end | ruby | {
"resource": ""
} |
q12039 | OneGadget.CLI.handle_gadgets | train | def handle_gadgets(gadgets, libc_file)
return false if gadgets.empty? # error occurs when fetching gadgets
return handle_script(gadgets, @options[:script]) if @options[:script]
return handle_near(libc_file, gadgets, @options[:near]) if @options[:near]
display_gadgets(gadgets, @options[:raw])
end | ruby | {
"resource": ""
} |
q12040 | OneGadget.CLI.info_build_id | train | def info_build_id(id)
result = OneGadget::Gadget.builds_info(id)
return false if result.nil? # invalid form or BuildID not found
OneGadget::Logger.info("Information of #{id}:\n#{result.join("\n")}")
true
end | ruby | {
"resource": ""
} |
q12041 | OneGadget.CLI.parser | train | def parser
@parser ||= OptionParser.new do |opts|
opts.banner = USAGE
opts.on('-b', '--build-id BuildID', 'BuildID[sha1] of libc.') do |b|
@options[:build_id] = b
end
opts.on('-f', '--[no-]force-file', 'Force search gadgets in file instead of build id first.') do |f|
@options[:force_file] = f
end
opts.on('-l', '--level OUTPUT_LEVEL', Integer, 'The output level.',
'OneGadget automatically selects gadgets with higher successful probability.',
'Increase this level to ask OneGadget show more gadgets it found.',
'Default: 0') do |l|
@options[:level] = l
end
opts.on('-n', '--near FUNCTIONS/FILE', 'Order gadgets by their distance to the given functions'\
' or to the GOT functions of the given file.') do |n|
@options[:near] = n
end
opts.on('-r', '--[no-]raw', 'Output gadgets offset only, split with one space.') do |v|
@options[:raw] = v
end
opts.on('-s', '--script exploit-script', 'Run exploit script with all possible gadgets.',
'The script will be run as \'exploit-script $offset\'.') do |s|
@options[:script] = s
end
opts.on('--info BuildID', 'Show version information given BuildID.') do |b|
@options[:info] = b
end
opts.on('--version', 'Current gem version.') do |v|
@options[:version] = v
end
end
end | ruby | {
"resource": ""
} |
q12042 | OneGadget.CLI.display_gadgets | train | def display_gadgets(gadgets, raw)
if raw
show(gadgets.map(&:offset).join(' '))
else
show(gadgets.map(&:inspect).join("\n"))
end
end | ruby | {
"resource": ""
} |
q12043 | HTTParty.ClassMethods.logger | train | def logger(logger, level = :info, format = :apache)
default_options[:logger] = logger
default_options[:log_level] = level
default_options[:log_format] = format
end | ruby | {
"resource": ""
} |
q12044 | HTTParty.ClassMethods.http_proxy | train | def http_proxy(addr = nil, port = nil, user = nil, pass = nil)
default_options[:http_proxyaddr] = addr
default_options[:http_proxyport] = port
default_options[:http_proxyuser] = user
default_options[:http_proxypass] = pass
end | ruby | {
"resource": ""
} |
q12045 | HTTParty.ClassMethods.default_params | train | def default_params(h = {})
raise ArgumentError, 'Default params must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_options[:default_params] ||= {}
default_options[:default_params].merge!(h)
end | ruby | {
"resource": ""
} |
q12046 | HTTParty.ClassMethods.headers | train | def headers(h = nil)
if h
raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_options[:headers] ||= {}
default_options[:headers].merge!(h.to_hash)
else
default_options[:headers] || {}
end
end | ruby | {
"resource": ""
} |
q12047 | HTTParty.ClassMethods.connection_adapter | train | def connection_adapter(custom_adapter = nil, options = nil)
if custom_adapter.nil?
default_options[:connection_adapter]
else
default_options[:connection_adapter] = custom_adapter
default_options[:connection_adapter_options] = options
end
end | ruby | {
"resource": ""
} |
q12048 | HTTParty.ClassMethods.get | train | def get(path, options = {}, &block)
perform_request Net::HTTP::Get, path, options, &block
end | ruby | {
"resource": ""
} |
q12049 | HTTParty.ClassMethods.post | train | def post(path, options = {}, &block)
perform_request Net::HTTP::Post, path, options, &block
end | ruby | {
"resource": ""
} |
q12050 | HTTParty.ClassMethods.patch | train | def patch(path, options = {}, &block)
perform_request Net::HTTP::Patch, path, options, &block
end | ruby | {
"resource": ""
} |
q12051 | HTTParty.ClassMethods.put | train | def put(path, options = {}, &block)
perform_request Net::HTTP::Put, path, options, &block
end | ruby | {
"resource": ""
} |
q12052 | HTTParty.ClassMethods.delete | train | def delete(path, options = {}, &block)
perform_request Net::HTTP::Delete, path, options, &block
end | ruby | {
"resource": ""
} |
q12053 | HTTParty.ClassMethods.move | train | def move(path, options = {}, &block)
perform_request Net::HTTP::Move, path, options, &block
end | ruby | {
"resource": ""
} |
q12054 | HTTParty.ClassMethods.copy | train | def copy(path, options = {}, &block)
perform_request Net::HTTP::Copy, path, options, &block
end | ruby | {
"resource": ""
} |
q12055 | HTTParty.ClassMethods.head | train | def head(path, options = {}, &block)
ensure_method_maintained_across_redirects options
perform_request Net::HTTP::Head, path, options, &block
end | ruby | {
"resource": ""
} |
q12056 | HTTParty.ClassMethods.options | train | def options(path, options = {}, &block)
perform_request Net::HTTP::Options, path, options, &block
end | ruby | {
"resource": ""
} |
q12057 | HTTParty.ClassMethods.mkcol | train | def mkcol(path, options = {}, &block)
perform_request Net::HTTP::Mkcol, path, options, &block
end | ruby | {
"resource": ""
} |
q12058 | Twitter.Utils.flat_pmap | train | def flat_pmap(enumerable)
return to_enum(:flat_pmap, enumerable) unless block_given?
pmap(enumerable, &Proc.new).flatten(1)
end | ruby | {
"resource": ""
} |
q12059 | Twitter.Utils.pmap | train | def pmap(enumerable)
return to_enum(:pmap, enumerable) unless block_given?
if enumerable.count == 1
enumerable.collect { |object| yield(object) }
else
enumerable.collect { |object| Thread.new { yield(object) } }.collect(&:value)
end
end | ruby | {
"resource": ""
} |
q12060 | Twitter.SearchResults.query_string_to_hash | train | def query_string_to_hash(query_string)
query = CGI.parse(URI.parse(query_string).query)
Hash[query.collect { |key, value| [key.to_sym, value.first] }]
end | ruby | {
"resource": ""
} |
q12061 | Twitter.Creatable.created_at | train | def created_at
time = @attrs[:created_at]
return if time.nil?
time = Time.parse(time) unless time.is_a?(Time)
time.utc
end | ruby | {
"resource": ""
} |
q12062 | Doorkeeper.AccessTokenMixin.as_json | train | def as_json(_options = {})
{
resource_owner_id: resource_owner_id,
scope: scopes,
expires_in: expires_in_seconds,
application: { uid: application.try(:uid) },
created_at: created_at.to_i,
}
end | ruby | {
"resource": ""
} |
q12063 | Doorkeeper.ApplicationMixin.secret_matches? | train | def secret_matches?(input)
# return false if either is nil, since secure_compare depends on strings
# but Application secrets MAY be nil depending on confidentiality.
return false if input.nil? || secret.nil?
# When matching the secret by comparer function, all is well.
return true if secret_strategy.secret_matches?(input, secret)
# When fallback lookup is enabled, ensure applications
# with plain secrets can still be found
if fallback_secret_strategy
fallback_secret_strategy.secret_matches?(input, secret)
else
false
end
end | ruby | {
"resource": ""
} |
q12064 | Doorkeeper.Config.validate_reuse_access_token_value | train | def validate_reuse_access_token_value
strategy = token_secret_strategy
return if !reuse_access_token || strategy.allows_restoring_secrets?
::Rails.logger.warn(
"You have configured both reuse_access_token " \
"AND strategy strategy '#{strategy}' that cannot restore tokens. " \
"This combination is unsupported. reuse_access_token will be disabled"
)
@reuse_access_token = false
end | ruby | {
"resource": ""
} |
q12065 | Mail.SMTP.ssl_context | train | def ssl_context
openssl_verify_mode = settings[:openssl_verify_mode]
if openssl_verify_mode.kind_of?(String)
openssl_verify_mode = OpenSSL::SSL.const_get("VERIFY_#{openssl_verify_mode.upcase}")
end
context = Net::SMTP.default_ssl_context
context.verify_mode = openssl_verify_mode if openssl_verify_mode
context.ca_path = settings[:ca_path] if settings[:ca_path]
context.ca_file = settings[:ca_file] if settings[:ca_file]
context
end | ruby | {
"resource": ""
} |
q12066 | Mail.AttachmentsList.[] | train | def [](index_value)
if index_value.is_a?(Integer)
self.fetch(index_value)
else
self.select { |a| a.filename == index_value }.first
end
end | ruby | {
"resource": ""
} |
q12067 | Mail.POP3.find | train | def find(options = nil, &block)
options = validate_options(options)
start do |pop3|
mails = pop3.mails
pop3.reset # Clears all "deleted" marks. This prevents non-explicit/accidental deletions due to server settings.
mails.sort! { |m1, m2| m2.number <=> m1.number } if options[:what] == :last
mails = mails.first(options[:count]) if options[:count].is_a? Integer
if options[:what].to_sym == :last && options[:order].to_sym == :desc ||
options[:what].to_sym == :first && options[:order].to_sym == :asc ||
mails.reverse!
end
if block_given?
mails.each do |mail|
new_message = Mail.new(mail.pop)
new_message.mark_for_delete = true if options[:delete_after_find]
yield new_message
mail.delete if options[:delete_after_find] && new_message.is_marked_for_delete? # Delete if still marked for delete
end
else
emails = []
mails.each do |mail|
emails << Mail.new(mail.pop)
mail.delete if options[:delete_after_find]
end
emails.size == 1 && options[:count] == 1 ? emails.first : emails
end
end
end | ruby | {
"resource": ""
} |
q12068 | Mail.POP3.delete_all | train | def delete_all
start do |pop3|
unless pop3.mails.empty?
pop3.delete_all
pop3.finish
end
end
end | ruby | {
"resource": ""
} |
q12069 | Mail.CommonAddressField.addresses | train | def addresses
list = element.addresses.map { |a| a.address }
Mail::AddressContainer.new(self, list)
end | ruby | {
"resource": ""
} |
q12070 | Mail.CommonAddressField.formatted | train | def formatted
list = element.addresses.map { |a| a.format }
Mail::AddressContainer.new(self, list)
end | ruby | {
"resource": ""
} |
q12071 | Mail.CommonAddressField.display_names | train | def display_names
list = element.addresses.map { |a| a.display_name }
Mail::AddressContainer.new(self, list)
end | ruby | {
"resource": ""
} |
q12072 | Mail.CommonAddressField.decoded_group_addresses | train | def decoded_group_addresses
groups.map { |k,v| v.map { |a| a.decoded } }.flatten
end | ruby | {
"resource": ""
} |
q12073 | Mail.CommonAddressField.encoded_group_addresses | train | def encoded_group_addresses
groups.map { |k,v| v.map { |a| a.encoded } }.flatten
end | ruby | {
"resource": ""
} |
q12074 | Mail.SMTPConnection.deliver! | train | def deliver!(mail)
envelope = Mail::SmtpEnvelope.new(mail)
response = smtp.sendmail(dot_stuff(envelope.message), envelope.from, envelope.to)
settings[:return_response] ? response : self
end | ruby | {
"resource": ""
} |
q12075 | Mail.ContentTypeField.sanitize | train | def sanitize(val)
# TODO: check if there are cases where whitespace is not a separator
val = val.
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
gsub(/[; ]+/, '; '). #use '; ' as a separator (or EOL)
gsub(/;\s*$/,'') #remove trailing to keep examples below
if val =~ /(boundary=(\S*))/i
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
else
val.downcase!
end
case
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
# Microsoft helper:
# Handles 'type/subtype;ISO-8559-1'
"#{$1}/#{$2}; charset=#{Utilities.quote_atom($3)}"
when val.chomp =~ /^text;?$/i
# Handles 'text;' and 'text'
"text/plain;"
when val.chomp =~ /^(\w+);\s(.*)$/i
# Handles 'text; <parameters>'
"text/plain; #{$2}"
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
# Handles text/html; charset="charset="GB2312""
"#{$1}; charset=#{Utilities.quote_atom($2)}"
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
type = $1
# Handles misquoted param values
# e.g: application/octet-stream; name=archiveshelp1[1].htm
# and: audio/x-midi;\r\n\sname=Part .exe
params = $2.to_s.split(/\s+/)
params = params.map { |i| i.to_s.chomp.strip }
params = params.map { |i| i.split(/\s*\=\s*/, 2) }
params = params.map { |i| "#{i[0]}=#{Utilities.dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
"#{type}; #{params}"
when val =~ /^\s*$/
'text/plain'
else
val
end
end | ruby | {
"resource": ""
} |
q12076 | Mail.Utilities.quote_phrase | train | def quote_phrase( str )
if str.respond_to?(:force_encoding)
original_encoding = str.encoding
ascii_str = str.to_s.dup.force_encoding('ASCII-8BIT')
if Constants::PHRASE_UNSAFE === ascii_str
dquote(ascii_str).force_encoding(original_encoding)
else
str
end
else
Constants::PHRASE_UNSAFE === str ? dquote(str) : str
end
end | ruby | {
"resource": ""
} |
q12077 | Mail.Utilities.quote_token | train | def quote_token( str )
if str.respond_to?(:force_encoding)
original_encoding = str.encoding
ascii_str = str.to_s.dup.force_encoding('ASCII-8BIT')
if token_safe?( ascii_str )
str
else
dquote(ascii_str).force_encoding(original_encoding)
end
else
token_safe?( str ) ? str : dquote(str)
end
end | ruby | {
"resource": ""
} |
q12078 | Mail.Utilities.capitalize_field | train | def capitalize_field( str )
str.to_s.split("-").map { |v| v.capitalize }.join("-")
end | ruby | {
"resource": ""
} |
q12079 | Mail.Utilities.constantize | train | def constantize( str )
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
end | ruby | {
"resource": ""
} |
q12080 | Mail.Utilities.blank? | train | def blank?(value)
if value.kind_of?(NilClass)
true
elsif value.kind_of?(String)
value !~ /\S/
else
value.respond_to?(:empty?) ? value.empty? : !value
end
end | ruby | {
"resource": ""
} |
q12081 | Mail.IMAP.find | train | def find(options=nil, &block)
options = validate_options(options)
start do |imap|
options[:read_only] ? imap.examine(options[:mailbox]) : imap.select(options[:mailbox])
uids = imap.uid_search(options[:keys], options[:search_charset])
uids.reverse! if options[:what].to_sym == :last
uids = uids.first(options[:count]) if options[:count].is_a?(Integer)
uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
(options[:what].to_sym != :last && options[:order].to_sym == :desc)
if block_given?
uids.each do |uid|
uid = options[:uid].to_i unless options[:uid].nil?
fetchdata = imap.uid_fetch(uid, ['RFC822', 'FLAGS'])[0]
new_message = Mail.new(fetchdata.attr['RFC822'])
new_message.mark_for_delete = true if options[:delete_after_find]
if block.arity == 4
yield new_message, imap, uid, fetchdata.attr['FLAGS']
elsif block.arity == 3
yield new_message, imap, uid
else
yield new_message
end
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find] && new_message.is_marked_for_delete?
break unless options[:uid].nil?
end
imap.expunge if options[:delete_after_find]
else
emails = []
uids.each do |uid|
uid = options[:uid].to_i unless options[:uid].nil?
fetchdata = imap.uid_fetch(uid, ['RFC822'])[0]
emails << Mail.new(fetchdata.attr['RFC822'])
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find]
break unless options[:uid].nil?
end
imap.expunge if options[:delete_after_find]
emails.size == 1 && options[:count] == 1 ? emails.first : emails
end
end
end | ruby | {
"resource": ""
} |
q12082 | Mail.IMAP.delete_all | train | def delete_all(mailbox='INBOX')
mailbox ||= 'INBOX'
mailbox = Net::IMAP.encode_utf7(mailbox)
start do |imap|
imap.select(mailbox)
imap.uid_search(['ALL']).each do |uid|
imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED])
end
imap.expunge
end
end | ruby | {
"resource": ""
} |
q12083 | Mail.IMAP.start | train | def start(config=Mail::Configuration.instance, &block)
raise ArgumentError.new("Mail::Retrievable#imap_start takes a block") unless block_given?
if settings[:enable_starttls] && settings[:enable_ssl]
raise ArgumentError, ":enable_starttls and :enable_ssl are mutually exclusive. Set :enable_ssl if you're on an IMAPS connection. Set :enable_starttls if you're on an IMAP connection and using STARTTLS for secure TLS upgrade."
end
imap = Net::IMAP.new(settings[:address], settings[:port], settings[:enable_ssl], nil, false)
imap.starttls if settings[:enable_starttls]
if settings[:authentication].nil?
imap.login(settings[:user_name], settings[:password])
else
# Note that Net::IMAP#authenticate('LOGIN', ...) is not equal with Net::IMAP#login(...)!
# (see also http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/imap/rdoc/classes/Net/IMAP.html#M000718)
imap.authenticate(settings[:authentication], settings[:user_name], settings[:password])
end
yield imap
ensure
if defined?(imap) && imap && !imap.disconnected?
imap.disconnect
end
end | ruby | {
"resource": ""
} |
q12084 | Mail.Header.fields= | train | def fields=(unfolded_fields)
@fields = Mail::FieldList.new
if unfolded_fields.size > self.class.maximum_amount
Kernel.warn "WARNING: More than #{self.class.maximum_amount} header fields; only using the first #{self.class.maximum_amount} and ignoring the rest"
unfolded_fields = unfolded_fields.slice(0...self.class.maximum_amount)
end
unfolded_fields.each do |field|
if field = Field.parse(field, charset)
@fields.add_field field
end
end
end | ruby | {
"resource": ""
} |
q12085 | Mail.Header.[]= | train | def []=(name, value)
name = name.to_s
if name.include?(Constants::COLON)
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
end
name = Utilities.dasherize(name)
# Assign nil to delete the field
if value.nil?
fields.delete_field name
else
fields.add_field Field.new(name.to_s, value, charset)
# Update charset if specified in Content-Type
if name == 'content-type'
params = self[:content_type].parameters rescue nil
@charset = params[:charset] if params && params[:charset]
end
end
end | ruby | {
"resource": ""
} |
q12086 | Mail.Message.default | train | def default( sym, val = nil )
if val
header[sym] = val
elsif field = header[sym]
field.default
end
end | ruby | {
"resource": ""
} |
q12087 | Mail.Message.[]= | train | def []=(name, value)
if name.to_s == 'body'
self.body = value
elsif name.to_s =~ /content[-_]type/i
header[name] = value
elsif name.to_s == 'charset'
self.charset = value
else
header[name] = value
end
end | ruby | {
"resource": ""
} |
q12088 | Mail.Message.method_missing | train | def method_missing(name, *args, &block)
#:nodoc:
# Only take the structured fields, as we could take _anything_ really
# as it could become an optional field... "but therin lies the dark side"
field_name = Utilities.underscoreize(name).chomp("=")
if Mail::Field::KNOWN_FIELDS.include?(field_name)
if args.empty?
header[field_name]
else
header[field_name] = args.first
end
else
super # otherwise pass it on
end
#:startdoc:
end | ruby | {
"resource": ""
} |
q12089 | Mail.Message.add_charset | train | def add_charset
if !body.empty?
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
# has not specified an encoding explicitly.
if @defaulted_charset && !body.raw_source.ascii_only? && !self.attachment?
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
warn(warning)
end
header[:content_type].parameters['charset'] = @charset
end
end | ruby | {
"resource": ""
} |
q12090 | Mail.Message.add_part | train | def add_part(part)
if !body.multipart? && !Utilities.blank?(self.body.decoded)
@text_part = Mail::Part.new('Content-Type: text/plain;')
@text_part.body = body.decoded
self.body << @text_part
add_multipart_alternate_header
end
add_boundary
self.body << part
end | ruby | {
"resource": ""
} |
q12091 | Mail.Message.part | train | def part(params = {})
new_part = Part.new(params)
yield new_part if block_given?
add_part(new_part)
end | ruby | {
"resource": ""
} |
q12092 | Mail.Message.add_file | train | def add_file(values)
convert_to_multipart unless self.multipart? || Utilities.blank?(self.body.decoded)
add_multipart_mixed_header
if values.is_a?(String)
basename = File.basename(values)
filedata = File.open(values, 'rb') { |f| f.read }
else
basename = values[:filename]
filedata = values
end
self.attachments[basename] = filedata
end | ruby | {
"resource": ""
} |
q12093 | Mail.Message.ready_to_send! | train | def ready_to_send!
identify_and_set_transfer_encoding
parts.each do |part|
part.transport_encoding = transport_encoding
part.ready_to_send!
end
add_required_fields
end | ruby | {
"resource": ""
} |
q12094 | Mail.Message.encoded | train | def encoded
ready_to_send!
buffer = header.encoded
buffer << "\r\n"
buffer << body.encoded(content_transfer_encoding)
buffer
end | ruby | {
"resource": ""
} |
q12095 | Mail.Message.body_lazy | train | def body_lazy(value)
process_body_raw if @body_raw && value
case
when value == nil || value.length<=0
@body = Mail::Body.new('')
@body_raw = nil
add_encoding_to_body
when @body && @body.multipart?
self.text_part = value
else
@body_raw = value
end
end | ruby | {
"resource": ""
} |
q12096 | Mail.Address.comments | train | def comments
parse unless @parsed
comments = get_comments
if comments.nil? || comments.none?
nil
else
comments.map { |c| c.squeeze(Constants::SPACE) }
end
end | ruby | {
"resource": ""
} |
q12097 | Mail.Retriever.all | train | def all(options = nil, &block)
options = options ? Hash[options] : {}
options[:count] = :all
find(options, &block)
end | ruby | {
"resource": ""
} |
q12098 | Mail.Retriever.find_and_delete | train | def find_and_delete(options = nil, &block)
options = options ? Hash[options] : {}
options[:delete_after_find] ||= true
find(options, &block)
end | ruby | {
"resource": ""
} |
q12099 | Mail.FieldList.insert_field | train | def insert_field(field)
lo, hi = 0, size
while lo < hi
mid = (lo + hi).div(2)
if field < self[mid]
hi = mid
else
lo = mid + 1
end
end
insert lo, field
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.