_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q17500
Gibberish.RSA.decrypt
train
def decrypt(data, opts={}) data = data.to_s raise "No private key set!" unless @key.private? unless opts[:binary] data = Base64.decode64(data) end @key.private_decrypt(data) end
ruby
{ "resource": "" }
q17501
ActsAsApi.Base.acts_as_api
train
def acts_as_api class_eval do include ActsAsApi::Base::InstanceMethods extend ActsAsApi::Base::ClassMethods end if block_given? yield ActsAsApi::Config end end
ruby
{ "resource": "" }
q17502
ActsAsApi.ApiTemplate.add
train
def add(val, options = {}) item_key = (options[:as] || val).to_sym self[item_key] = val @options[item_key] = options end
ruby
{ "resource": "" }
q17503
ActsAsApi.ApiTemplate.allowed_to_render?
train
def allowed_to_render?(fieldset, field, model, options) return true unless fieldset.is_a? ActsAsApi::ApiTemplate fieldset_options = fieldset.options_for(field) if fieldset_options[:unless] !(condition_fulfilled?(model, fieldset_options[:unless], options)) elsif fieldset_options[:if] condition_fulfilled?(model, fieldset_options[:if], options) else true end end
ruby
{ "resource": "" }
q17504
ActsAsApi.ApiTemplate.to_response_hash
train
def to_response_hash(model, fieldset = self, options = {}) api_output = {} fieldset.each do |field, value| next unless allowed_to_render?(fieldset, field, model, options) out = process_value(model, value, options) if out.respond_to?(:as_api_response) sub_template = api_template_for(fieldset, field) out = out.as_api_response(sub_template, options) end api_output[field] = out end api_output end
ruby
{ "resource": "" }
q17505
ActsAsApi.Rendering.render_for_api
train
def render_for_api(api_template_or_options, render_options) if api_template_or_options.is_a?(Hash) api_template = [] api_template << api_template_or_options.delete(:prefix) api_template << api_template_or_options.delete(:template) api_template << api_template_or_options.delete(:postfix) api_template = api_template.reject(&:blank?).join('_') else api_template = api_template_or_options end # extract the api format and model api_format_options = {} ActsAsApi::Config.accepted_api_formats.each do |item| if render_options.key?(item) api_format_options[item] = render_options[item] render_options.delete item end end meta_hash = render_options[:meta] if render_options.key?(:meta) api_format = api_format_options.keys.first api_model = api_format_options.values.first # set the params to render output_params = render_options api_root_name = nil if !output_params[:root].nil? api_root_name = output_params[:root].to_s elsif api_model.class.respond_to?(:model_name) api_root_name = api_model.class.model_name elsif api_model.respond_to?(:collection_name) api_root_name = api_model.collection_name elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.class.respond_to?(:model_name) api_root_name = api_model.first.class.model_name elsif api_model.is_a?(Array) && !api_model.empty? && api_model.first.respond_to?(:model_name) api_root_name = api_model.first.model_name elsif api_model.respond_to?(:model_name) api_root_name = api_model.model_name else api_root_name = ActsAsApi::Config.default_root.to_s end api_root_name = api_root_name.to_s.underscore.tr('/', '_') if api_model.is_a?(Array) || (defined?(ActiveRecord) && api_model.is_a?(ActiveRecord::Relation)) api_root_name = api_root_name.pluralize end api_root_name = api_root_name.dasherize if ActsAsApi::Config.dasherize_for.include? api_format.to_sym output_params[:root] = api_root_name api_response = api_model.as_api_response(api_template) if api_response.is_a?(Array) && api_format.to_sym == :json && ActsAsApi::Config.include_root_in_json_collections api_response = api_response.collect { |f| { api_root_name.singularize => f } } end if meta_hash || ActsAsApi::Config.add_root_node_for.include?(api_format) api_response = { api_root_name.to_sym => api_response } end api_response = meta_hash.merge api_response if meta_hash if ActsAsApi::Config.allow_jsonp_callback && params[:callback] output_params[:callback] = params[:callback] api_format = :acts_as_api_jsonp if ActsAsApi::Config.add_http_status_to_jsonp_response end # create the Hash as response output_params[api_format] = api_response render output_params end
ruby
{ "resource": "" }
q17506
ActsAsApi.Collection.as_api_response
train
def as_api_response(api_template, options = {}) collect do |item| if item.respond_to?(:as_api_response) item.as_api_response(api_template, options) else item end end end
ruby
{ "resource": "" }
q17507
RablRails.Compiler.condition
train
def condition(proc) return unless block_given? @template.add_node Nodes::Condition.new(proc, sub_compile(nil, true) { yield }) end
ruby
{ "resource": "" }
q17508
Jammit.CommandLine.ensure_configuration_file
train
def ensure_configuration_file config = @options[:config_paths] return true if File.exists?(config) && File.readable?(config) puts "Could not find the asset configuration file \"#{config}\"" exit(1) end
ruby
{ "resource": "" }
q17509
Jammit.Packager.precache_all
train
def precache_all(output_dir=nil, base_url=nil) output_dir ||= File.join(Jammit.public_root, Jammit.package_path) cacheable(:js, output_dir).each {|p| cache(p, 'js', pack_javascripts(p), output_dir) } cacheable(:css, output_dir).each do |p| cache(p, 'css', pack_stylesheets(p), output_dir) if Jammit.embed_assets cache(p, 'css', pack_stylesheets(p, :datauri), output_dir, :datauri) if Jammit.mhtml_enabled raise MissingConfiguration, "A --base-url option is required in order to generate MHTML." unless base_url mtime = latest_mtime package_for(p, :css)[:paths] asset_url = "#{base_url}#{Jammit.asset_url(p, :css, :mhtml, mtime)}" cache(p, 'css', pack_stylesheets(p, :mhtml, asset_url), output_dir, :mhtml, mtime) end end end end
ruby
{ "resource": "" }
q17510
Jammit.Packager.cache
train
def cache(package, extension, contents, output_dir, suffix=nil, mtime=nil) FileUtils.mkdir_p(output_dir) unless File.exists?(output_dir) raise OutputNotWritable, "Jammit doesn't have permission to write to \"#{output_dir}\"" unless File.writable?(output_dir) mtime ||= latest_mtime package_for(package, extension.to_sym)[:paths] files = [] files << file_name = File.join(output_dir, Jammit.filename(package, extension, suffix)) File.open(file_name, 'wb+') {|f| f.write(contents) } if Jammit.gzip_assets files << zip_name = "#{file_name}.gz" Zlib::GzipWriter.open(zip_name, Zlib::BEST_COMPRESSION) {|f| f.write(contents) } end File.utime(mtime, mtime, *files) end
ruby
{ "resource": "" }
q17511
Jammit.Packager.pack_stylesheets
train
def pack_stylesheets(package, variant=nil, asset_url=nil) compressor.compress_css(package_for(package, :css)[:paths], variant, asset_url) end
ruby
{ "resource": "" }
q17512
Jammit.Packager.package_for
train
def package_for(package, extension) pack = @packages[extension] && @packages[extension][package] pack || not_found(package, extension) end
ruby
{ "resource": "" }
q17513
Jammit.Controller.package
train
def package parse_request template_ext = Jammit.template_extension.to_sym case @extension when :js render :js => (@contents = Jammit.packager.pack_javascripts(@package)) when template_ext render :js => (@contents = Jammit.packager.pack_templates(@package)) when :css render :text => generate_stylesheets, :content_type => 'text/css' end cache_package if perform_caching && (@extension != template_ext) rescue Jammit::PackageNotFound package_not_found end
ruby
{ "resource": "" }
q17514
Jammit.Helper.include_stylesheets
train
def include_stylesheets(*packages) options = packages.extract_options! return html_safe(individual_stylesheets(packages, options)) unless should_package? disabled = (options.delete(:embed_assets) == false) || (options.delete(:embed_images) == false) return html_safe(packaged_stylesheets(packages, options)) if disabled || !Jammit.embed_assets return html_safe(embedded_image_stylesheets(packages, options)) end
ruby
{ "resource": "" }
q17515
Jammit.Helper.include_javascripts
train
def include_javascripts(*packages) options = packages.extract_options! options.merge!(:extname=>false) html_safe packages.map {|pack| should_package? ? Jammit.asset_url(pack, :js) : Jammit.packager.individual_urls(pack.to_sym, :js) }.flatten.map {|pack| "<script src=\"#{pack}\"></script>" }.join("\n") end
ruby
{ "resource": "" }
q17516
Jammit.Helper.individual_stylesheets
train
def individual_stylesheets(packages, options) tags_with_options(packages, options) {|p| Jammit.packager.individual_urls(p.to_sym, :css) } end
ruby
{ "resource": "" }
q17517
Jammit.Helper.packaged_stylesheets
train
def packaged_stylesheets(packages, options) tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css) } end
ruby
{ "resource": "" }
q17518
Jammit.Helper.embedded_image_stylesheets
train
def embedded_image_stylesheets(packages, options) datauri_tags = tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :datauri) } ie_tags = Jammit.mhtml_enabled ? tags_with_options(packages, options) {|p| Jammit.asset_url(p, :css, :mhtml) } : packaged_stylesheets(packages, options) [DATA_URI_START, datauri_tags, DATA_URI_END, MHTML_START, ie_tags, MHTML_END].join("\n") end
ruby
{ "resource": "" }
q17519
Jammit.Helper.tags_with_options
train
def tags_with_options(packages, options) packages.dup.map {|package| yield package }.flatten.map {|package| stylesheet_link_tag package, options }.join("\n") end
ruby
{ "resource": "" }
q17520
Jammit.Compressor.compile_jst
train
def compile_jst(paths) namespace = Jammit.template_namespace paths = paths.grep(Jammit.template_extension_matcher).sort base_path = find_base_path(paths) compiled = paths.map do |path| contents = read_binary_file(path) contents = contents.gsub(/\r?\n/, "\\n").gsub("'", '\\\\\'') name = template_name(path, base_path) "#{namespace}['#{name}'] = #{Jammit.template_function}('#{contents}');" end compiler = Jammit.include_jst_script ? read_binary_file(DEFAULT_JST_SCRIPT) : ''; setup_namespace = "#{namespace} = #{namespace} || {};" [JST_START, setup_namespace, compiler, compiled, JST_END].flatten.join("\n") end
ruby
{ "resource": "" }
q17521
Jammit.Compressor.find_base_path
train
def find_base_path(paths) return nil if paths.length <= 1 paths.sort! first = paths.first.split('/') last = paths.last.split('/') i = 0 while first[i] == last[i] && i <= first.length i += 1 end res = first.slice(0, i).join('/') res.empty? ? nil : res end
ruby
{ "resource": "" }
q17522
Jammit.Compressor.concatenate_and_tag_assets
train
def concatenate_and_tag_assets(paths, variant=nil) stylesheets = [paths].flatten.map do |css_path| contents = read_binary_file(css_path) contents.gsub(EMBED_DETECTOR) do |url| ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path)) is_url = URI.parse($1).absolute? is_url ? url : "url(#{construct_asset_path(ipath, cpath, variant)})" end end stylesheets.join("\n") end
ruby
{ "resource": "" }
q17523
Jammit.Compressor.absolute_path
train
def absolute_path(asset_pathname, css_pathname) (asset_pathname.absolute? ? Pathname.new(File.join(Jammit.public_root, asset_pathname)) : css_pathname.dirname + asset_pathname).cleanpath end
ruby
{ "resource": "" }
q17524
Jammit.Compressor.rails_asset_id
train
def rails_asset_id(path) asset_id = ENV["RAILS_ASSET_ID"] return asset_id if asset_id File.exists?(path) ? File.mtime(path).to_i.to_s : '' end
ruby
{ "resource": "" }
q17525
Jammit.Compressor.embeddable?
train
def embeddable?(asset_path, variant) font = EMBED_FONTS.include?(asset_path.extname) return false unless variant return false unless asset_path.to_s.match(EMBEDDABLE) && asset_path.exist? return false unless EMBED_EXTS.include?(asset_path.extname) return false unless font || encoded_contents(asset_path).length < MAX_IMAGE_SIZE return false if font && variant == :mhtml return true end
ruby
{ "resource": "" }
q17526
Jammit.Compressor.encoded_contents
train
def encoded_contents(asset_path) return @asset_contents[asset_path] if @asset_contents[asset_path] data = read_binary_file(asset_path) @asset_contents[asset_path] = Base64.encode64(data).gsub(/\n/, '') end
ruby
{ "resource": "" }
q17527
Rubotnik.Helpers.say
train
def say(text, quick_replies: [], user: @user) message_options = { recipient: { id: user.id }, message: { text: text } } if quick_replies && !quick_replies.empty? message_options[:message][:quick_replies] = UI::QuickReplies .build(*quick_replies) end send_message(message_options) end
ruby
{ "resource": "" }
q17528
MachO.FatFile.change_dylib_id
train
def change_dylib_id(new_id, options = {}) raise ArgumentError, "argument must be a String" unless new_id.is_a?(String) return unless machos.all?(&:dylib?) each_macho(options) do |macho| macho.change_dylib_id(new_id, options) end repopulate_raw_machos end
ruby
{ "resource": "" }
q17529
MachO.FatFile.change_install_name
train
def change_install_name(old_name, new_name, options = {}) each_macho(options) do |macho| macho.change_install_name(old_name, new_name, options) end repopulate_raw_machos end
ruby
{ "resource": "" }
q17530
MachO.FatFile.change_rpath
train
def change_rpath(old_path, new_path, options = {}) each_macho(options) do |macho| macho.change_rpath(old_path, new_path, options) end repopulate_raw_machos end
ruby
{ "resource": "" }
q17531
MachO.FatFile.add_rpath
train
def add_rpath(path, options = {}) each_macho(options) do |macho| macho.add_rpath(path, options) end repopulate_raw_machos end
ruby
{ "resource": "" }
q17532
MachO.FatFile.delete_rpath
train
def delete_rpath(path, options = {}) each_macho(options) do |macho| macho.delete_rpath(path, options) end repopulate_raw_machos end
ruby
{ "resource": "" }
q17533
MachO.FatFile.populate_fat_header
train
def populate_fat_header # the smallest fat Mach-O header is 8 bytes raise TruncatedFileError if @raw_data.size < 8 fh = Headers::FatHeader.new_from_bin(:big, @raw_data[0, Headers::FatHeader.bytesize]) raise MagicError, fh.magic unless Utils.magic?(fh.magic) raise MachOBinaryError unless Utils.fat_magic?(fh.magic) # Rationale: Java classfiles have the same magic as big-endian fat # Mach-Os. Classfiles encode their version at the same offset as # `nfat_arch` and the lowest version number is 43, so we error out # if a file claims to have over 30 internal architectures. It's # technically possible for a fat Mach-O to have over 30 architectures, # but this is extremely unlikely and in practice distinguishes the two # formats. raise JavaClassFileError if fh.nfat_arch > 30 fh end
ruby
{ "resource": "" }
q17534
MachO.FatFile.populate_fat_archs
train
def populate_fat_archs archs = [] fa_klass = Utils.fat_magic32?(header.magic) ? Headers::FatArch : Headers::FatArch64 fa_off = Headers::FatHeader.bytesize fa_len = fa_klass.bytesize header.nfat_arch.times do |i| archs << fa_klass.new_from_bin(:big, @raw_data[fa_off + (fa_len * i), fa_len]) end archs end
ruby
{ "resource": "" }
q17535
MachO.FatFile.populate_machos
train
def populate_machos machos = [] fat_archs.each do |arch| machos << MachOFile.new_from_bin(@raw_data[arch.offset, arch.size], **options) end machos end
ruby
{ "resource": "" }
q17536
MachO.FatFile.repopulate_raw_machos
train
def repopulate_raw_machos machos.each_with_index do |macho, i| arch = fat_archs[i] @raw_data[arch.offset, arch.size] = macho.serialize end end
ruby
{ "resource": "" }
q17537
MachO.FatFile.each_macho
train
def each_macho(options = {}) strict = options.fetch(:strict, true) errors = [] machos.each_with_index do |macho, index| begin yield macho rescue RecoverableModificationError => e e.macho_slice = index # Strict mode: Immediately re-raise. Otherwise: Retain, check later. raise e if strict errors << e end end # Non-strict mode: Raise first error if *all* Mach-O slices failed. raise errors.first if errors.size == machos.size end
ruby
{ "resource": "" }
q17538
MachO.MachOFile.insert_command
train
def insert_command(offset, lc, options = {}) context = LoadCommands::LoadCommand::SerializationContext.context_for(self) cmd_raw = lc.serialize(context) fileoff = offset + cmd_raw.bytesize raise OffsetInsertionError, offset if offset < header.class.bytesize || fileoff > low_fileoff new_sizeofcmds = sizeofcmds + cmd_raw.bytesize raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff # update Mach-O header fields to account for inserted load command update_ncmds(ncmds + 1) update_sizeofcmds(new_sizeofcmds) @raw_data.insert(offset, cmd_raw) @raw_data.slice!(header.class.bytesize + new_sizeofcmds, cmd_raw.bytesize) populate_fields if options.fetch(:repopulate, true) end
ruby
{ "resource": "" }
q17539
MachO.MachOFile.replace_command
train
def replace_command(old_lc, new_lc) context = LoadCommands::LoadCommand::SerializationContext.context_for(self) cmd_raw = new_lc.serialize(context) new_sizeofcmds = sizeofcmds + cmd_raw.bytesize - old_lc.cmdsize raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff delete_command(old_lc) insert_command(old_lc.view.offset, new_lc) end
ruby
{ "resource": "" }
q17540
MachO.MachOFile.delete_command
train
def delete_command(lc, options = {}) @raw_data.slice!(lc.view.offset, lc.cmdsize) # update Mach-O header fields to account for deleted load command update_ncmds(ncmds - 1) update_sizeofcmds(sizeofcmds - lc.cmdsize) # pad the space after the load commands to preserve offsets @raw_data.insert(header.class.bytesize + sizeofcmds - lc.cmdsize, Utils.nullpad(lc.cmdsize)) populate_fields if options.fetch(:repopulate, true) end
ruby
{ "resource": "" }
q17541
MachO.MachOFile.segment_alignment
train
def segment_alignment # special cases: 12 for x86/64/PPC/PP64, 14 for ARM/ARM64 return 12 if %i[i386 x86_64 ppc ppc64].include?(cputype) return 14 if %i[arm arm64].include?(cputype) cur_align = Sections::MAX_SECT_ALIGN segments.each do |segment| if filetype == :object # start with the smallest alignment, and work our way up align = magic32? ? 2 : 3 segment.sections.each do |section| align = section.align unless section.align <= align end else align = segment.guess_align end cur_align = align if align < cur_align end cur_align end
ruby
{ "resource": "" }
q17542
MachO.MachOFile.change_dylib_id
train
def change_dylib_id(new_id, _options = {}) raise ArgumentError, "new ID must be a String" unless new_id.is_a?(String) return unless dylib? old_lc = command(:LC_ID_DYLIB).first raise DylibIdMissingError unless old_lc new_lc = LoadCommands::LoadCommand.create(:LC_ID_DYLIB, new_id, old_lc.timestamp, old_lc.current_version, old_lc.compatibility_version) replace_command(old_lc, new_lc) end
ruby
{ "resource": "" }
q17543
MachO.MachOFile.change_install_name
train
def change_install_name(old_name, new_name, _options = {}) old_lc = dylib_load_commands.find { |d| d.name.to_s == old_name } raise DylibUnknownError, old_name if old_lc.nil? new_lc = LoadCommands::LoadCommand.create(old_lc.type, new_name, old_lc.timestamp, old_lc.current_version, old_lc.compatibility_version) replace_command(old_lc, new_lc) end
ruby
{ "resource": "" }
q17544
MachO.MachOFile.change_rpath
train
def change_rpath(old_path, new_path, _options = {}) old_lc = command(:LC_RPATH).find { |r| r.path.to_s == old_path } raise RpathUnknownError, old_path if old_lc.nil? raise RpathExistsError, new_path if rpaths.include?(new_path) new_lc = LoadCommands::LoadCommand.create(:LC_RPATH, new_path) delete_rpath(old_path) insert_command(old_lc.view.offset, new_lc) end
ruby
{ "resource": "" }
q17545
MachO.MachOFile.add_rpath
train
def add_rpath(path, _options = {}) raise RpathExistsError, path if rpaths.include?(path) rpath_cmd = LoadCommands::LoadCommand.create(:LC_RPATH, path) add_command(rpath_cmd) end
ruby
{ "resource": "" }
q17546
MachO.MachOFile.delete_rpath
train
def delete_rpath(path, _options = {}) rpath_cmds = command(:LC_RPATH).select { |r| r.path.to_s == path } raise RpathUnknownError, path if rpath_cmds.empty? # delete the commands in reverse order, offset descending. this # allows us to defer (expensive) field population until the very end rpath_cmds.reverse_each { |cmd| delete_command(cmd, :repopulate => false) } populate_fields end
ruby
{ "resource": "" }
q17547
MachO.MachOFile.populate_mach_header
train
def populate_mach_header # the smallest Mach-O header is 28 bytes raise TruncatedFileError if @raw_data.size < 28 magic = populate_and_check_magic mh_klass = Utils.magic32?(magic) ? Headers::MachHeader : Headers::MachHeader64 mh = mh_klass.new_from_bin(endianness, @raw_data[0, mh_klass.bytesize]) check_cputype(mh.cputype) check_cpusubtype(mh.cputype, mh.cpusubtype) check_filetype(mh.filetype) mh end
ruby
{ "resource": "" }
q17548
MachO.MachOFile.populate_and_check_magic
train
def populate_and_check_magic magic = @raw_data[0..3].unpack("N").first raise MagicError, magic unless Utils.magic?(magic) raise FatBinaryError if Utils.fat_magic?(magic) @endianness = Utils.little_magic?(magic) ? :little : :big magic end
ruby
{ "resource": "" }
q17549
MachO.MachOFile.populate_load_commands
train
def populate_load_commands permissive = options.fetch(:permissive, false) offset = header.class.bytesize load_commands = [] header.ncmds.times do fmt = Utils.specialize_format("L=", endianness) cmd = @raw_data.slice(offset, 4).unpack(fmt).first cmd_sym = LoadCommands::LOAD_COMMANDS[cmd] raise LoadCommandError, cmd unless cmd_sym || permissive # If we're here, then either cmd_sym represents a valid load # command *or* we're in permissive mode. klass = if (klass_str = LoadCommands::LC_STRUCTURES[cmd_sym]) LoadCommands.const_get klass_str else LoadCommands::LoadCommand end view = MachOView.new(@raw_data, endianness, offset) command = klass.new_from_bin(view) load_commands << command offset += command.cmdsize end load_commands end
ruby
{ "resource": "" }
q17550
MachO.MachOFile.update_ncmds
train
def update_ncmds(ncmds) fmt = Utils.specialize_format("L=", endianness) ncmds_raw = [ncmds].pack(fmt) @raw_data[16..19] = ncmds_raw end
ruby
{ "resource": "" }
q17551
MachO.MachOFile.update_sizeofcmds
train
def update_sizeofcmds(size) fmt = Utils.specialize_format("L=", endianness) size_raw = [size].pack(fmt) @raw_data[20..23] = size_raw end
ruby
{ "resource": "" }
q17552
SandiMeter.Analyzer.number_of_arguments
train
def number_of_arguments(method_sexp) arguments = method_sexp[2] arguments = arguments[1] if arguments.first == :paren arguments[1] == nil ? 0 : arguments[1].size end
ruby
{ "resource": "" }
q17553
Dnsimple.Client.execute
train
def execute(method, path, data = nil, options = {}) response = request(method, path, data, options) case response.code when 200..299 response when 401 raise AuthenticationFailed, response["message"] when 404 raise NotFoundError, response else raise RequestError, response end end
ruby
{ "resource": "" }
q17554
Dnsimple.Client.request
train
def request(method, path, data = nil, options = {}) request_options = request_options(options) if data request_options[:headers]["Content-Type"] = content_type(request_options[:headers]) request_options[:body] = content_data(request_options[:headers], data) end HTTParty.send(method, base_url + path, request_options) end
ruby
{ "resource": "" }
q17555
Jpmobile.RequestWithMobile.remote_addr
train
def remote_addr if respond_to?(:remote_ip) __send__(:remote_ip) # for Rails elsif respond_to?(:ip) __send__(:ip) # for Rack else if env['HTTP_X_FORWARDED_FOR'] env['HTTP_X_FORWARDED_FOR'].split(',').pop else env['REMOTE_ADDR'] end end end
ruby
{ "resource": "" }
q17556
Jpmobile::Mobile.AbstractMobile.variants
train
def variants return @_variants if @_variants @_variants = self.class.ancestors.select {|c| c.to_s =~ /^Jpmobile/ && c.to_s !~ /Emoticon/ }.map do |klass| klass = klass.to_s. gsub(/Jpmobile::/, ''). gsub(/AbstractMobile::/, ''). gsub(/Mobile::SmartPhone/, 'smart_phone'). gsub(/Mobile::Tablet/, 'tablet'). gsub(/::/, '_'). gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2'). gsub(/([a-z\d])([A-Z])/, '\1_\2'). downcase (klass =~ /abstract/) ? 'mobile' : klass end if @_variants.include?('tablet') @_variants = @_variants.reject {|v| v == 'mobile' }.map {|v| v.gsub(/mobile_/, 'tablet_') } elsif @_variants.include?('smart_phone') @_variants = @_variants.reject {|v| v == 'mobile' }.map {|v| v.gsub(/mobile_/, 'smart_phone_') } end @_variants || [] end
ruby
{ "resource": "" }
q17557
Rapidfire.Question.validate_answer
train
def validate_answer(answer) if rules[:presence] == "1" answer.validates_presence_of :answer_text end if rules[:minimum].present? || rules[:maximum].present? min_max = { minimum: rules[:minimum].to_i } min_max[:maximum] = rules[:maximum].to_i if rules[:maximum].present? answer.validates_length_of :answer_text, min_max end end
ruby
{ "resource": "" }
q17558
Category.Cache.replace_sections
train
def replace_sections(diary) return if diary.nil? or !diary.categorizable? categorized = categorize_diary(diary) categories = restore_categories deleted = [] ymd = diary.date.strftime('%Y%m%d') @plugin.__send__(:transaction, 'category') do |db| categories.each do |c| cat = get(db, c) || {} if diary.visible? and categorized[c] cat.update(categorized[c]) set(db, c, cat) else # diary is invisible or sections of this category is deleted cat.delete(ymd) if cat.empty? db.delete(c) deleted << c else set(db, c, cat) end end end if !deleted.empty? replace_categories(categories - deleted) end end end
ruby
{ "resource": "" }
q17559
Category.Cache.categorize
train
def categorize(category, years) categories = category - ['ALL'] if categories.empty? categories = restore_categories else categories &= restore_categories end categorized = {} begin categorized.clear categories.each do |c| @plugin.__send__(:transaction, 'category') do |db| categorized[c] = get(db, c) end categorized[c].keys.each do |ymd| y, m = ymd[0,4], ymd[4,2] if years[y].nil? or !years[y].include?(m) categorized[c].delete(ymd) end end categorized.delete(c) if categorized[c].empty? end rescue NoMethodError # when categorized[c] is nil recreate(years) retry end categorized end
ruby
{ "resource": "" }
q17560
Category.Cache.categorize_diary
train
def categorize_diary(diary) categorized = {} ymd = diary.date.strftime('%Y%m%d') idx = 1 diary.each_section do |s| shorten = begin body = %Q|apply_plugin(#{s.body_to_html.dump}, true)| @conf.shorten(eval(body, @binding)) rescue NameError "" end s.categories.each do |c| categorized[c] = {} if categorized[c].nil? categorized[c][ymd] = [] if categorized[c][ymd].nil? categorized[c][ymd] << [idx, s.stripped_subtitle_to_html, shorten] end idx +=1 end categorized end
ruby
{ "resource": "" }
q17561
TDiary.Dispatcher.dispatch_cgi
train
def dispatch_cgi(request, cgi) result = @target.run( request, cgi ) result.headers.reject!{|k,v| k.to_s.downcase == "status" } result.to_a end
ruby
{ "resource": "" }
q17562
TDiary.Dispatcher.fake_stdin_as_params
train
def fake_stdin_as_params stdin_spy = StringIO.new if $RACK_ENV && $RACK_ENV['rack.input'] stdin_spy.print($RACK_ENV['rack.input'].read) stdin_spy.rewind end $stdin = stdin_spy end
ruby
{ "resource": "" }
q17563
TDiary.Configuration.load_cgi_conf
train
def load_cgi_conf def_vars1 = '' def_vars2 = '' [ :tdiary_version, :html_title, :author_name, :author_mail, :index_page, :hour_offset, :description, :icon, :banner, :x_frame_options, :header, :footer, :section_anchor, :comment_anchor, :date_format, :latest_limit, :show_nyear, :theme, :css, :show_comment, :comment_limit, :comment_limit_per_day, :mail_on_comment, :mail_header, :show_referer, :no_referer2, :only_volatile2, :referer_table2, :options2, ].each do |var| def_vars1 << "#{var} = nil\n" def_vars2 << "@#{var} = #{var} unless #{var} == nil\n" end unless defined?(::TDiary::Cache) && ::TDiary::Cache.method_defined?(:store_cache) require 'tdiary/cache/file' end unless @io_class require 'tdiary/io/default' @io_class = IO::Default attr_reader :io_class end cgi_conf = @io_class.load_cgi_conf(self) b = binding eval( def_vars1, b ) begin eval( cgi_conf, b, "(TDiary::Configuration#load_cgi_conf)", 1 ) rescue SyntaxError enc = case @lang when 'en' 'UTF-8' else 'EUC-JP' end cgi_conf.force_encoding( enc ) retry end if cgi_conf eval( def_vars2, b ) end
ruby
{ "resource": "" }
q17564
TDiary.Configuration.configure_attrs
train
def configure_attrs @options = {} eval( File::open( 'tdiary.conf' ) {|f| f.read }, nil, "(tdiary.conf)", 1 ) # language setup @lang = 'ja' unless @lang begin instance_eval( File::open( "#{TDiary::PATH}/tdiary/lang/#{@lang}.rb" ){|f| f.read }, "(tdiary/lang/#{@lang}.rb)", 1 ) rescue Errno::ENOENT @lang = 'ja' retry end @data_path += '/' if @data_path && /\/$/ !~ @data_path @style = 'tDiary' unless @style @index = './' unless @index @update = 'update.rb' unless @update @hide_comment_form = false unless defined?( @hide_comment_form ) @author_name = '' unless @author_name @index_page = '' unless @index_page @hour_offset = 0 unless @hour_offset @html_title = '' unless @html_title @x_frame_options = nil unless @x_frame_options @header = '' unless @header @footer = '' unless @footer @section_anchor = '<span class="sanchor">_</span>' unless @section_anchor @comment_anchor = '<span class="canchor">_</span>' unless @comment_anchor @date_format = '%Y-%m-%d' unless @date_format @latest_limit = 10 unless @latest_limit @show_nyear = false unless @show_nyear @theme = 'default' if not @theme and not @css @theme = "local/#{@theme}" unless @theme.index('/') @css = '' unless @css @show_comment = true unless defined?( @show_comment ) @comment_limit = 3 unless @comment_limit @comment_limit_per_day = 100 unless @comment_limit_per_day @show_referer = true unless defined?( @show_referer ) @referer_limit = 10 unless @referer_limit @referer_day_only = true unless defined?( @referer_day_only ) @no_referer = [] unless @no_referer @no_referer2 = [] unless @no_referer2 @no_referer = @no_referer2 + @no_referer @only_volatile = [] unless @only_volatile @only_volatile2 = [] unless @only_volatile2 @only_volatile = @only_volatile2 + @only_volatile @referer_table = [] unless @referer_table @referer_table2 = [] unless @referer_table2 @referer_table = @referer_table2 + @referer_table @options = {} unless @options.class == Hash if @options2 then @options.update( @options2 ) else @options2 = {} end # for 1.4 compatibility @section_anchor = @paragraph_anchor unless @section_anchor end
ruby
{ "resource": "" }
q17565
Footnotes.Filter.close!
train
def close!(controller) self.each_with_rescue(@@klasses) {|klass| klass.close!(controller)} self.each_with_rescue(Footnotes.after_hooks) {|hook| hook.call(controller, self)} end
ruby
{ "resource": "" }
q17566
Footnotes.Filter.close
train
def close javascript = '' each_with_rescue(@notes) do |note| next unless note.has_fieldset? javascript << close_helper(note) end javascript end
ruby
{ "resource": "" }
q17567
Footnotes.Filter.link_helper
train
def link_helper(note) onclick = note.onclick unless href = note.link href = '#' onclick ||= "Footnotes.hideAllAndToggle('#{note.to_sym}_debug_info');return false;" if note.has_fieldset? end "<a href=\"#{href}\" onclick=\"#{onclick}\">#{note.title}</a>" end
ruby
{ "resource": "" }
q17568
PredictionIO.Connection.request
train
def request(method, request) response = AsyncResponse.new(request) @packages.push(method: method, request: request, response: response) response end
ruby
{ "resource": "" }
q17569
PredictionIO.EventClient.get_status
train
def get_status status = @http.aget(PredictionIO::AsyncRequest.new('/')).get begin status.body rescue status end end
ruby
{ "resource": "" }
q17570
EXIFR.JPEG.to_hash
train
def to_hash h = {:width => width, :height => height, :bits => bits, :comment => comment} h.merge!(exif) if exif? h end
ruby
{ "resource": "" }
q17571
EXIFR.JPEG.method_missing
train
def method_missing(method, *args) super unless args.empty? super unless methods.include?(method) @exif.send method if defined?(@exif) && @exif end
ruby
{ "resource": "" }
q17572
EXIFR.TIFF.method_missing
train
def method_missing(method, *args) super unless args.empty? if @ifds.first.respond_to?(method) @ifds.first.send(method) elsif TAGS.include?(method) @ifds.first.to_hash[method] else super end end
ruby
{ "resource": "" }
q17573
EXIFR.TIFF.gps
train
def gps return nil unless gps_latitude && gps_longitude altitude = gps_altitude.is_a?(Array) ? gps_altitude.first : gps_altitude GPS.new(gps_latitude.to_f * (gps_latitude_ref == 'S' ? -1 : 1), gps_longitude.to_f * (gps_longitude_ref == 'W' ? -1 : 1), altitude && (altitude.to_f * (gps_altitude_ref == "\1" ? -1 : 1)), gps_img_direction && gps_img_direction.to_f) end
ruby
{ "resource": "" }
q17574
Authority.Controller.authorize_action_for
train
def authorize_action_for(authority_resource, *options) # `action_name` comes from ActionController authority_action = self.class.authority_action_map[action_name.to_sym] if authority_action.nil? raise MissingAction.new("No authority action defined for #{action_name}") end Authority.enforce(authority_action, authority_resource, authority_user, *options) # This method is always invoked, but will only log if it's overriden authority_success(authority_user, authority_action, authority_resource) self.authorization_performed = true end
ruby
{ "resource": "" }
q17575
Authority.Controller.authority_forbidden
train
def authority_forbidden(error) Authority.logger.warn(error.message) render :file => Rails.root.join('public', '403.html'), :status => 403, :layout => false end
ruby
{ "resource": "" }
q17576
Authority.Controller.run_authorization_check
train
def run_authorization_check if instance_authority_resource.is_a?(Array) # Array includes options; pass as separate args authorize_action_for(*instance_authority_resource, *authority_arguments) else # *resource would be interpreted as resource.to_a, which is wrong and # actually triggers a query if it's a Sequel model authorize_action_for(instance_authority_resource, *authority_arguments) end end
ruby
{ "resource": "" }
q17577
Service.RegistryApi.search
train
def search(query) get('/v1/search'.freeze, { q: query }) rescue => e logger.warn "API v1 - Search failed #{e.backtrace}" { 'results' => catalog(query) } end
ruby
{ "resource": "" }
q17578
Surveyor.ActsAsResponse.as
train
def as(type_symbol) return case type_symbol.to_sym when :string, :text, :integer, :float, :datetime self.send("#{type_symbol}_value".to_sym) when :date self.datetime_value.nil? ? nil : self.datetime_value.to_date when :time self.datetime_value.nil? ? nil : self.datetime_value.to_time else # :answer_id self.answer_id end end
ruby
{ "resource": "" }
q17579
Surveyor.Parser.method_missing
train
def method_missing(missing_method, *args, &block) method_name, reference_identifier = missing_method.to_s.split("_", 2) type = full(method_name) Surveyor::Parser.raise_error( "\"#{type}\" is not a surveyor method." )if !%w(survey survey_translation survey_section question_group question dependency dependency_condition answer validation validation_condition).include?(type) Surveyor::Parser.rake_trace(reference_identifier.blank? ? "#{type} #{args.map(&:inspect).join ', '}" : "#{type}_#{reference_identifier} #{args.map(&:inspect).join ', '}", block_models.include?(type) ? 2 : 0) # check for blocks Surveyor::Parser.raise_error "A #{type.humanize.downcase} should take a block" if block_models.include?(type) && !block_given? Surveyor::Parser.raise_error "A #{type.humanize.downcase} doesn't take a block" if !block_models.include?(type) && block_given? # parse and build type.classify.constantize.new.extend("SurveyorParser#{type.classify}Methods".constantize).parse_and_build(context, args, method_name, reference_identifier) # evaluate and clear context for block models if block_models.include?(type) self.instance_eval(&block) if type == 'survey' resolve_dependency_condition_references resolve_question_correct_answers report_lost_and_duplicate_references report_missing_default_locale Surveyor::Parser.rake_trace("", -2) if context[:survey].save Surveyor::Parser.rake_trace "Survey saved." else Surveyor::Parser.raise_error "Survey not saved: #{context[:survey].errors.full_messages.join(", ")}" end else Surveyor::Parser.rake_trace("", -2) context[type.to_sym].clear(context) end end end
ruby
{ "resource": "" }
q17580
Larch.Config.validate
train
def validate ['from', 'to'].each do |s| raise Error, "'#{s}' must be a valid IMAP URI (e.g. imap://example.com)" unless fetch(s) =~ IMAP::REGEX_URI end unless Logger::LEVELS.has_key?(verbosity.to_sym) raise Error, "'verbosity' must be one of: #{Logger::LEVELS.keys.join(', ')}" end if exclude_file raise Error, "exclude file not found: #{exclude_file}" unless File.file?(exclude_file) raise Error, "exclude file cannot be read: #{exclude_file}" unless File.readable?(exclude_file) end if @cached['all'] || @cached['all-subscribed'] # A specific source folder wins over 'all' and 'all-subscribed' if @cached['from-folder'] @cached['all'] = false @cached['all-subscribed'] = false @cached['to-folder'] ||= @cached['from-folder'] elsif @cached['all'] && @cached['all-subscribed'] # 'all' wins over 'all-subscribed' @cached['all-subscribed'] = false end # 'no-recurse' is not compatible with 'all' and 'all-subscribed' raise Error, "'no-recurse' option cannot be used with 'all' or 'all-subscribed'" if @cached['no-recurse'] else @cached['from-folder'] ||= 'INBOX' @cached['to-folder'] ||= 'INBOX' end @cached['exclude'].flatten! end
ruby
{ "resource": "" }
q17581
Larch.Config.cache_config
train
def cache_config @cached = {} @lookup.reverse.each do |c| c.each {|k, v| @cached[k] = config_merge(@cached[k] || {}, v) } end end
ruby
{ "resource": "" }
q17582
Larch.IMAP.safely
train
def safely safe_connect retries = 0 begin yield rescue Errno::ECONNABORTED, Errno::ECONNRESET, Errno::ENOTCONN, Errno::EPIPE, Errno::ETIMEDOUT, IOError, Net::IMAP::ByeResponseError, OpenSSL::SSL::SSLError => e raise unless (retries += 1) <= @options[:max_retries] warning "#{e.class.name}: #{e.message} (reconnecting)" reset sleep 1 * retries safe_connect retry rescue Net::IMAP::BadResponseError, Net::IMAP::NoResponseError, Net::IMAP::ResponseParseError => e raise unless (retries += 1) <= @options[:max_retries] warning "#{e.class.name}: #{e.message} (will retry)" sleep 1 * retries retry end rescue Larch::Error => e raise rescue Net::IMAP::Error => e raise Error, "#{e.class.name}: #{e.message} (giving up)" rescue => e raise FatalError, "#{e.class.name}: #{e.message} (cannot recover)" end
ruby
{ "resource": "" }
q17583
Larch.IMAP.uri_mailbox
train
def uri_mailbox mb = @uri.path[1..-1] mb.nil? || mb.empty? ? nil : CGI.unescape(mb) end
ruby
{ "resource": "" }
q17584
Larch.IMAP.check_quirks
train
def check_quirks return unless @conn && @conn.greeting.kind_of?(Net::IMAP::UntaggedResponse) && @conn.greeting.data.kind_of?(Net::IMAP::ResponseText) if @conn.greeting.data.text =~ /^Gimap ready/ @quirks[:gmail] = true debug "looks like Gmail" elsif host =~ /^imap(?:-ssl)?\.mail\.yahoo\.com$/ @quirks[:yahoo] = true debug "looks like Yahoo! Mail" elsif host =~ /emailsrvr\.com/ @quirks[:rackspace] = true debug "looks like Rackspace Mail" end end
ruby
{ "resource": "" }
q17585
Apicasso.CrudController.set_object
train
def set_object id = params[:id] @object = resource.friendly.find(id) rescue NoMethodError @object = resource.find(id) ensure authorize! action_to_cancancan, @object end
ruby
{ "resource": "" }
q17586
Apicasso.CrudController.set_records
train
def set_records authorize! :read, resource.name.underscore.to_sym @records = request_collection.ransack(parsed_query).result @object = request_collection.new key_scope_records reorder_records if params[:sort].present? select_fields if params[:select].present? include_relations if params[:include].present? end
ruby
{ "resource": "" }
q17587
Apicasso.CrudController.index_json
train
def index_json if params[:group].present? @records.group(params[:group][:by].split(',')) .send(:calculate, params[:group][:calculate], params[:group][:field]) else collection_response end end
ruby
{ "resource": "" }
q17588
Apicasso.ApplicationController.request_metadata
train
def request_metadata { uuid: request.uuid, url: request.original_url, headers: request.env.select { |key, _v| key =~ /^HTTP_/ }, ip: request.remote_ip } end
ruby
{ "resource": "" }
q17589
Apicasso.Ability.build_permissions
train
def build_permissions(opts = {}) permission = opts[:permission].to_sym clearances = opts[:clearance] # To have full read access to the whole APIcasso just set a # true key scope operation. # Usage: # To have full read access to the system the scope would be: # => `{read: true}` if clearances == true can permission, :all else clearances.to_h.each do |klass, clearance| klass_module = klass.underscore.singularize.to_sym klass = klass.classify.constantize can permission, klass_module if clearance == true # Usage: # To have a key reading all channels and all accouts # you would have a scope: # => `{read: {channel: true, accout: true}}` can permission, klass else clear_for(permission, klass, clearance) end end end end
ruby
{ "resource": "" }
q17590
ROM::Factory.Factories.define
train
def define(spec, **opts, &block) name, parent = spec.is_a?(Hash) ? spec.flatten(1) : spec if registry.key?(name) raise ArgumentError, "#{name.inspect} factory has been already defined" end builder = if parent extend_builder(name, registry[parent], &block) else relation_name = opts.fetch(:relation) { infer_relation(name) } relation = rom.relations[relation_name] DSL.new(name, relation: relation.struct_namespace(struct_namespace), factories: self, &block).call end registry[name] = builder end
ruby
{ "resource": "" }
q17591
ROM::Factory.Factories.struct_namespace
train
def struct_namespace(namespace = Undefined) if namespace.equal?(Undefined) options[:struct_namespace] else with(struct_namespace: namespace) end end
ruby
{ "resource": "" }
q17592
Timerizer.WallClock.hour
train
def hour(system = :twenty_four_hour) hour = self.to_duration.to_units(:hour, :minute, :second).fetch(:hour) if system == :twelve_hour if hour == 0 12 elsif hour > 12 hour - 12 else hour end elsif (system == :twenty_four_hour) hour else raise ArgumentError, "system should be :twelve_hour or :twenty_four_hour" end end
ruby
{ "resource": "" }
q17593
Timerizer.Duration.after
train
def after(time) time = time.to_time prev_day = time.mday prev_month = time.month prev_year = time.year units = self.to_units(:years, :months, :days, :seconds) date_in_month = self.class.build_date( prev_year + units[:years], prev_month + units[:months], prev_day ) date = date_in_month + units[:days] Time.new( date.year, date.month, date.day, time.hour, time.min, time.sec ) + units[:seconds] end
ruby
{ "resource": "" }
q17594
Timerizer.Duration.to_unit
train
def to_unit(unit) unit_details = self.class.resolve_unit(unit) if unit_details.has_key?(:seconds) seconds = self.normalize.get(:seconds) self.class.div(seconds, unit_details.fetch(:seconds)) elsif unit_details.has_key?(:months) months = self.denormalize.get(:months) self.class.div(months, unit_details.fetch(:months)) else raise "Unit should have key :seconds or :months" end end
ruby
{ "resource": "" }
q17595
Timerizer.Duration.-
train
def -(other) case other when 0 self when Duration Duration.new( seconds: @seconds - other.get(:seconds), months: @months - other.get(:months) ) else raise ArgumentError, "Cannot subtract #{other.inspect} from Duration #{self}" end end
ruby
{ "resource": "" }
q17596
Timerizer.Duration.*
train
def *(other) case other when Integer Duration.new( seconds: @seconds * other, months: @months * other ) else raise ArgumentError, "Cannot multiply Duration #{self} by #{other.inspect}" end end
ruby
{ "resource": "" }
q17597
Timerizer.Duration.to_s
train
def to_s(format = :long, options = nil) format = case format when Symbol FORMATS.fetch(format) when Hash FORMATS.fetch(:long).merge(format) else raise ArgumentError, "Expected #{format.inspect} to be a Symbol or Hash" end format = format.merge(options || {}) count = if format[:count].nil? || format[:count] == :all UNITS.count else format[:count] end format_units = format.fetch(:units) units = self.to_units(*format_units.keys).select {|unit, n| n > 0} if units.empty? units = {seconds: 0} end separator = format[:separator] || ' ' delimiter = format[:delimiter] || ', ' units.take(count).map do |unit, n| unit_label = format_units.fetch(unit) singular, plural = case unit_label when Array unit_label else [unit_label, unit_label] end unit_name = if n == 1 singular else plural || singular end [n, unit_name].join(separator) end.join(format[:delimiter] || ', ') end
ruby
{ "resource": "" }
q17598
Timerizer.Duration.to_rounded_s
train
def to_rounded_s(format = :min_long, options = nil) format = case format when Symbol FORMATS.fetch(format) when Hash FORMATS.fetch(:long).merge(format) else raise ArgumentError, "Expected #{format.inspect} to be a Symbol or Hash" end format = format.merge(Hash(options)) places = format[:count] begin places = Integer(places) # raise if nil or `:all` supplied as value rescue TypeError places = 2 end q = RoundedTime.call(self, places) q.to_s(format, options) end
ruby
{ "resource": "" }
q17599
Elastomer::Client::RestApiSpec.ApiSpec.select_params
train
def select_params(api:, from:) rest_api = get(api) return from if rest_api.nil? rest_api.select_params(from: from) end
ruby
{ "resource": "" }