_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q18400
RocketPants.ErrorHandling.render_error
train
def render_error(exception) logger.debug "Exception raised: #{exception.class.name}: #{exception.message}" if logger # When a normalised class is present, make sure we # convert it to a useable error class. normalised_class = exception.class.ancestors.detect do |klass| klass < StandardEr...
ruby
{ "resource": "" }
q18401
RocketPants.Client.transform_response
train
def transform_response(response, options = {}) # Now unpack the response into the data types. inner = response.delete("response") objects = unpack inner, options # Unpack pagination as a special case. if response.has_key?("pagination") paginated_response objects, response els...
ruby
{ "resource": "" }
q18402
RocketPants.Client.paginated_response
train
def paginated_response(objects, container) pagination = container.delete("pagination") WillPaginate::Collection.create(pagination["current"], pagination["per_page"]) do |collection| collection.replace objects collection.total_entries = pagination["count"] end end
ruby
{ "resource": "" }
q18403
RocketPants.Client.unpack
train
def unpack(object, options = {}) transformer = options[:transformer] || options[:as] transformer ? transformer.call(object) : object end
ruby
{ "resource": "" }
q18404
RocketPants.Linking.links
train
def links(links = {}) links.each_pair do |rel, uri| link rel, uri if uri end end
ruby
{ "resource": "" }
q18405
RocketPants.Respondable.render_json
train
def render_json(json, options = {}) # Setup data from options self.status = options[:status] if options[:status] self.content_type = options[:content_type] if options[:content_type] options = options.slice(*RENDERING_OPTIONS) # Don't convert raw strings to JSON. json = encode_t...
ruby
{ "resource": "" }
q18406
RocketPants.Respondable.exposes
train
def exposes(object, options = {}) if Respondable.paginated?(object) paginated object, options elsif Respondable.collection?(object) collection object, options else if Respondable.invalid?(object) error! :invalid_resource, object.errors else resource ...
ruby
{ "resource": "" }
q18407
RocketPants.Respondable.metadata_for
train
def metadata_for(object, options, type, singular) {}.tap do |metadata| metadata[:count] = object.length unless singular metadata[:pagination] = Respondable.extract_pagination(object) if type == :paginated metadata.merge! options[:metadata] if options[:metadata] end end
ruby
{ "resource": "" }
q18408
Tugboat.Configuration.create_config_file
train
def create_config_file(access_token, ssh_key_path, ssh_user, ssh_port, region, image, size, ssh_key, private_networking, backups_enabled, ip6, timeout) # Default SSH Key path ssh_key_path = File.join('~', DEFAULT_SSH_KEY_PATH) if ssh_key_path.empty? ssh_user = 'root' if ssh_user.empty? ssh_por...
ruby
{ "resource": "" }
q18409
Creditsafe.Client.handle_error
train
def handle_error(error) case error when Savon::SOAPFault return UnknownApiError.new(error.message) when Savon::HTTPError if error.to_hash[:code] == 401 return AccountError.new("Unauthorized: invalid credentials") end return UnknownApiError.new(error.message) ...
ruby
{ "resource": "" }
q18410
CrowdFlower.Connection.method_missing
train
def method_missing(method_id, *args) if [:get, :post, :put, :delete].include?(method_id) path, options = *args options ||= {} options[:query] = (default_params.merge(options[:query] || {})) options[:headers] = (self.class.default_options[:headers].merge(options[:headers] || {})) ...
ruby
{ "resource": "" }
q18411
CrowdFlower.Judgment.all
train
def all(page = 1, limit = 100, latest = true) opts = connection.version == 2 ? {:unseen => latest} : {:latest => latest} connection.get(resource_uri, {:query => {:limit => limit, :page => page}.merge(opts)}) end
ruby
{ "resource": "" }
q18412
Solrizer.FieldMapper.solr_names_and_values
train
def solr_names_and_values(field_name, field_value, index_types) return {} if field_value.nil? # Determine the set of index types index_types = Array(index_types) index_types.uniq! index_types.dup.each do |index_type| if index_type.to_s =~ /^not_(.*)/ index_types.de...
ruby
{ "resource": "" }
q18413
Mongify.Configuration.mongodb_connection
train
def mongodb_connection(options={}, &block) return @mongodb_conncetion if @mongodb_connection and !block_given? options.stringify_keys! options['adapter'] ||= 'mongodb' @mongodb_connection = no_sql_connection(options, &block) end
ruby
{ "resource": "" }
q18414
Mongify.ProgressBar.show
train
def show return unless @out arguments = @format_arguments.map {|method| method = sprintf("fmt_%s", method) send(method) } line = sprintf(@format, *arguments) width = get_width if line.length == width - 1 @out.print(line + eol) @out.flush elsif l...
ruby
{ "resource": "" }
q18415
RackSessionAccess.Middleware.call
train
def call(env) return render(500) do |xml| xml.h2("#{@key} env is not initialized") end unless env[@key] request = ::Rack::Request.new(env) if action = dispatch_action(request) send(action, request) else @app.call(env) end end
ruby
{ "resource": "" }
q18416
RackSessionAccess.Middleware.show
train
def show(request) # force load session because it can be lazy loaded request.env[@key].delete(:rack_session_access_force_load_session) # session hash object session_hash = request.env[@key].to_hash case File.extname(request.path) when ".raw" render do |xml| xml.h2...
ruby
{ "resource": "" }
q18417
RackSessionAccess.Middleware.edit
train
def edit(request) render do |xml| xml.h2 "Update rack session" xml.p "Put marshalized and encoded with base64 ruby hash into the form" xml.form({ :action => action_path(:update), :method => 'post', :enctype => 'application/x-www-form-urlencoded' }) d...
ruby
{ "resource": "" }
q18418
RackSessionAccess.Middleware.update
train
def update(request) begin data = request.params['data'] hash = RackSessionAccess.decode(data) hash.each { |k, v| request.env[@key][k] = v } rescue => e return render(400) do |xml| xml.h2("Bad data #{data.inspect}: #{e.message} ") end end redirec...
ruby
{ "resource": "" }
q18419
RackSessionAccess.Middleware.dispatch_action
train
def dispatch_action(request) method = request_method(request) path = request.path.sub(/\.\w+$/, '') route = @routing.detect { |r| r[0] == method && r[1] == path } route[2] if route end
ruby
{ "resource": "" }
q18420
RackSessionAccess.Middleware.request_method
train
def request_method(request) return request.request_method if request.request_method != 'POST' return request.params['_method'].upcase if request.params['_method'] request.request_method end
ruby
{ "resource": "" }
q18421
StrongPassword.QwertyAdjuster.adjusted_entropy
train
def adjusted_entropy(entropy_threshhold: 0) revpassword = base_password.reverse min_entropy = [EntropyCalculator.calculate(base_password), EntropyCalculator.calculate(revpassword)].min QWERTY_STRINGS.each do |qwertystr| qpassword = mask_qwerty_strings(base_password, qwertystr) qrevpass...
ruby
{ "resource": "" }
q18422
StrongPassword.DictionaryAdjuster.adjusted_entropy
train
def adjusted_entropy(min_word_length: 4, extra_dictionary_words: [], entropy_threshhold: -1) dictionary_words = Regexp.union( ( extra_dictionary_words + COMMON_PASSWORDS ).compact.reject{ |i| i.length < min_word_length } ) min_entropy = EntropyCalculator.calculate(base_password) # Process the password...
ruby
{ "resource": "" }
q18423
Adamantium.ModuleMethods.memoize
train
def memoize(*methods) options = methods.last.kind_of?(Hash) ? methods.pop : {} method_freezer = Freezer.parse(options) || freezer methods.each { |method| memoize_method(method, method_freezer) } self end
ruby
{ "resource": "" }
q18424
Adamantium.ModuleMethods.memoize_method
train
def memoize_method(method_name, freezer) memoized_methods[method_name] = Memoizable::MethodBuilder .new(self, method_name, freezer).call end
ruby
{ "resource": "" }
q18425
TimelineSetter.Timeline.timeline_min
train
def timeline_min @js = "" @css = Kompress::CSS.new(File.open("#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css").read).css libs = Dir.glob("#{TimelineSetter::ROOT}/public/javascripts/vendor/**").select {|q| q =~ /min/ } libs.each { |lib| @js << File.open(lib,'r').read } @min_...
ruby
{ "resource": "" }
q18426
Starscope.DB.parse_db
train
def parse_db(stream) case stream.gets.to_i when DB_FORMAT @meta = Oj.load(stream.gets) @tables = Oj.load(stream.gets) return true when 3..4 # Old format, so read the directories segment then rebuild add_paths(Oj.load(stream.gets)) return false wh...
ruby
{ "resource": "" }
q18427
Mittsu.PolyhedronGeometry.prepare
train
def prepare(vector) vertex = vector.normalize.clone vertex.index = @vertices.push(vertex).length - 1 # Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle. u = azimuth(vector) / 2.0 / Math::PI + 0.5 v = inclination(vector) / Math::PI + 0.5 ...
ruby
{ "resource": "" }
q18428
Mittsu.PolyhedronGeometry.make
train
def make(v1, v2, v3) face = Face3.new(v1.index, v2.index, v3.index, [v1.clone, v2.clone, v3.clone]) @faces << face @centroid.copy(v1).add(v2).add(v3).divide_scalar(3) azi = azimuth(@centroid) @face_vertex_uvs[0] << [ correct_uv(v1.uv, v1, azi), correct_uv(v2.uv, v2, azi)...
ruby
{ "resource": "" }
q18429
Mittsu.PolyhedronGeometry.subdivide
train
def subdivide(face, detail) cols = 2.0 ** detail a = prepare(@vertices[face.a]) b = prepare(@vertices[face.b]) c = prepare(@vertices[face.c]) v = [] # Construct all of the vertices for this subdivision. for i in 0..cols do v[i] = [] aj = prepare(a.clone.lerp(c...
ruby
{ "resource": "" }
q18430
Mittsu.PolyhedronGeometry.inclination
train
def inclination(vector) Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)) end
ruby
{ "resource": "" }
q18431
Mittsu.PolyhedronGeometry.correct_uv
train
def correct_uv(uv, vector, azimuth) return Vector2.new(uv.x - 1.0, uv.y) if azimuth < 0 return Vector2.new(azimuth / 2.0 / Math::PI + 0.5, uv.y) if vector.x.zero? && vector.z.zero? uv.clone end
ruby
{ "resource": "" }
q18432
Mittsu.Texture.filter_fallback
train
def filter_fallback(filter) if filter == NearestFilter || filter == NearestMipMapNearestFilter || f == NearestMipMapLinearFilter GL_NEAREST end GL_LINEAR end
ruby
{ "resource": "" }
q18433
Mittsu.ShadowMapPlugin.update_virtual_light
train
def update_virtual_light(light, cascade) virtual_light = light.shadow_cascade_array[cascade] virtual_light.position.copy(light.position) virtual_light.target.position.copy(light.target.position) virtual_light.look_at(virtual_light.target) virtual_light.shadow_camera_visible = light.shado...
ruby
{ "resource": "" }
q18434
Mittsu.ShadowMapPlugin.update_shadow_camera
train
def update_shadow_camera(camera, light) shadow_camera = light.shadow_camera points_frustum = light.pointa_frustum points_world = light.points_world @min.set(Float::INFINITY, Float::INFINITY, Float::INFINITY) @max.set(-Float::INFINITY, -Float::INFINITY, -Float::INFINITY) 8.times do ...
ruby
{ "resource": "" }
q18435
Mittsu.ShadowMapPlugin.get_object_material
train
def get_object_material(object) if object.material.is_a?(MeshFaceMaterial) object.material.materials[0] else object.material end end
ruby
{ "resource": "" }
q18436
Wallaby.ResourcesHelper.show_title
train
def show_title(decorated) raise ::ArgumentError unless decorated.is_a? ResourceDecorator [ to_model_label(decorated.model_class), decorated.to_label ].compact.join ': ' end
ruby
{ "resource": "" }
q18437
Wallaby.SecureHelper.user_portrait
train
def user_portrait(user = current_user) email_method = security.email_method || :email email = ModuleUtils.try_to user, email_method if email.present? https = "http#{request.ssl? ? 's' : EMPTY_STRING}" email_md5 = ::Digest::MD5.hexdigest email.downcase image_source = "#{https}:/...
ruby
{ "resource": "" }
q18438
Wallaby.SecureHelper.logout_path
train
def logout_path(user = current_user, app = main_app) path = security.logout_path path ||= if defined? ::Devise scope = ::Devise::Mapping.find_scope! user "destroy_#{scope}_session_path" end ModuleUtils.try_to app, path end
ruby
{ "resource": "" }
q18439
Wallaby.SecureHelper.logout_method
train
def logout_method(user = current_user) http_method = security.logout_method http_method || if defined? ::Devise scope = ::Devise::Mapping.find_scope! user mapping = ::Devise.mappings[scope] mapping.sign_out_via end ...
ruby
{ "resource": "" }
q18440
Wallaby.ResourcesRouter.find_controller_by
train
def find_controller_by(params) model_class = find_model_class_by params Map.controller_map(model_class, params[:resources_controller]) || default_controller(params) end
ruby
{ "resource": "" }
q18441
Wallaby.ResourcesRouter.find_model_class_by
train
def find_model_class_by(params) model_class = Map.model_class_map params[:resources] return model_class unless MODEL_ACTIONS.include? params[:action].to_sym raise ModelNotFound, params[:resources] unless model_class unless Map.mode_map[model_class] raise UnprocessableEntity, I18n.t('erro...
ruby
{ "resource": "" }
q18442
Wallaby.ResourcesRouter.set_message_for
train
def set_message_for(exception, env) session = env[ActionDispatch::Request::Session::ENV_SESSION_KEY] || {} env[ActionDispatch::Flash::KEY] ||= ActionDispatch::Flash::FlashHash.from_session_value session['flash'] flash = env[ActionDispatch::Flash::KEY] flash[:alert] = exception.message end
ruby
{ "resource": "" }
q18443
Wallaby.ModelDecorator.validate_presence_of
train
def validate_presence_of(field_name, type) type || raise(::ArgumentError, I18n.t('errors.invalid.type_required', field_name: field_name)) end
ruby
{ "resource": "" }
q18444
Wallaby.StylingHelper.itooltip
train
def itooltip(title, icon_suffix = 'info-circle', html_options = {}) html_options[:title] = title (html_options[:data] ||= {}).merge! toggle: 'tooltip', placement: 'top' fa_icon icon_suffix, html_options end
ruby
{ "resource": "" }
q18445
Wallaby.StylingHelper.imodal
train
def imodal(title, body, html_options = {}) label ||= html_options.delete(:label) \ || html_options.delete(:icon) || fa_icon('clone') content_tag :span, class: 'modaler' do concat link_to(label, '#', data: { target: '#imodal', toggle: 'modal' }) concat content_tag(:span, tit...
ruby
{ "resource": "" }
q18446
Wallaby.FormBuilder.error_messages
train
def error_messages(field_name) errors = Array object.errors[field_name] return if errors.blank? content_tag :ul, class: 'errors' do errors.each do |message| concat content_tag :li, content_tag(:small, raw(message)) end end end
ruby
{ "resource": "" }
q18447
Wallaby.FormBuilder.label
train
def label(method, text = nil, options = {}, &block) text = instance_exec(&text) if text.is_a?(Proc) super end
ruby
{ "resource": "" }
q18448
Wallaby.FormBuilder.select
train
def select(method, choices = nil, options = {}, html_options = {}, &block) choices = instance_exec(&choices) if choices.is_a?(Proc) super end
ruby
{ "resource": "" }
q18449
Wallaby.FormBuilder.method_missing
train
def method_missing(method, *args, &block) return super unless @template.respond_to? method # Delegate the method so that we don't come in here the next time # when same method is called self.class.delegate method, to: :@template @template.public_send method, *args, &block end
ruby
{ "resource": "" }
q18450
Wallaby.FormHelper.remote_url
train
def remote_url(url, model_class, wildcard = 'QUERY') url || index_path(model_class, url_params: { q: wildcard, per: pagination.page_size }) end
ruby
{ "resource": "" }
q18451
Wallaby.IndexHelper.filter_link
train
def filter_link(model_class, filter_name, filters: {}, url_params: {}) is_all = filter_name == :all config = filters[filter_name] || {} label = is_all ? all_label : filter_label(filter_name, filters) url_params = if config[:default] then index_params.except(:filter).merge(url_params) ...
ruby
{ "resource": "" }
q18452
Wallaby.IndexHelper.export_link
train
def export_link(model_class, url_params: {}) url_params = index_params.except(:page, :per).merge(format: 'csv').merge(url_params) index_link(model_class, url_params: url_params) { t 'links.export', ext: 'CSV' } end
ruby
{ "resource": "" }
q18453
Wallaby.BaseHelper.model_classes
train
def model_classes(classes = Map.model_classes) nested_hash = classes.each_with_object({}) do |klass, hash| hash[klass] = Node.new(klass) end nested_hash.each do |klass, node| node.parent = parent = nested_hash[klass.superclass] parent.children << node if parent end ...
ruby
{ "resource": "" }
q18454
Wallaby.BaseHelper.model_tree
train
def model_tree(array, base_class = nil) return EMPTY_STRING.html_safe if array.blank? options = { html_options: { class: 'dropdown-item' } } content_tag :ul, class: 'dropdown-menu', 'aria-labelledby': base_class do array.sort_by(&:name).each do |node| content = index_link(node.klass,...
ruby
{ "resource": "" }
q18455
Wallaby.ModelAuthorizer.init_provider
train
def init_provider(context) providers = Map.authorizer_provider_map model_class provider_class = providers[self.class.provider_name] provider_class ||= providers.values.find { |klass| klass.available? context } provider_class.new context end
ruby
{ "resource": "" }
q18456
Wallaby.ApplicationController.error_rendering
train
def error_rendering(exception, symbol) Rails.logger.error exception @exception = exception @symbol = symbol @code = Rack::Utils::SYMBOL_TO_STATUS_CODE[symbol].to_i respond_with @exception, status: @code, template: ERROR_PATH, prefixes: _prefixes end
ruby
{ "resource": "" }
q18457
Wallaby.Authorizable.authorized?
train
def authorized?(action, subject) return false unless subject klass = subject.is_a?(Class) ? subject : subject.class authorizer_of(klass).authorized? action, subject end
ruby
{ "resource": "" }
q18458
Wallaby.SharedHelpers.controller_to_get
train
def controller_to_get(attribute_name, class_attribute_name = nil) class_attribute_name ||= attribute_name return ModuleUtils.try_to self.class, class_attribute_name if is_a? ::ActionController::Base # controller? ModuleUtils.try_to controller, attribute_name # view? end
ruby
{ "resource": "" }
q18459
Wallaby.CustomLookupContext.find_template
train
def find_template(name, prefixes = [], partial = false, keys = [], options = {}) prefixes = [] if partial && name.include?(SLASH) # reset the prefixes if `/` is detected key = [name, prefixes, partial, keys, options].map(&:inspect).join(SLASH) cached_lookup[key] ||= super end
ruby
{ "resource": "" }
q18460
Wallaby.PunditAuthorizationProvider.authorize
train
def authorize(action, subject) context.send(:authorize, subject, normalize(action)) && subject rescue ::Pundit::NotAuthorizedError Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject) raise Forbidden end
ruby
{ "resource": "" }
q18461
Wallaby.PunditAuthorizationProvider.authorized?
train
def authorized?(action, subject) policy = context.send :policy, subject ModuleUtils.try_to policy, normalize(action) end
ruby
{ "resource": "" }
q18462
Wallaby.PunditAuthorizationProvider.attributes_for
train
def attributes_for(action, subject) policy = context.send :policy, subject value = ModuleUtils.try_to(policy, "attributes_for_#{action}") || ModuleUtils.try_to(policy, 'attributes_for') Rails.logger.warn I18n.t('error.pundit.not_found.attributes_for', subject: subject) unless value value || {} ...
ruby
{ "resource": "" }
q18463
Wallaby.PunditAuthorizationProvider.permit_params
train
def permit_params(action, subject) policy = context.send :policy, subject # @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258 ModuleUtils.try_to(policy, "permitted_attributes_for_#{action}") \ || ModuleUtils.try_to(policy, 'permitted_attributes') end
ruby
{ "resource": "" }
q18464
Wallaby.Defaultable.set_defaults_for
train
def set_defaults_for(action, options) case action.try(:to_sym) when :create, :update then assign_create_and_update_defaults_with options when :destroy then assign_destroy_defaults_with options end options end
ruby
{ "resource": "" }
q18465
Wallaby.CancancanAuthorizationProvider.authorize
train
def authorize(action, subject) current_ability.authorize! action, subject rescue ::CanCan::AccessDenied Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject) raise Forbidden end
ruby
{ "resource": "" }
q18466
Wallaby.LinksHelper.index_link
train
def index_link(model_class, url_params: {}, html_options: {}, &block) return if unauthorized? :index, model_class html_options, block = LinkOptionsNormalizer.normalize( html_options, block, block: -> { to_model_label model_class } ) path = index_path model_class, url_params: url...
ruby
{ "resource": "" }
q18467
Wallaby.LinksHelper.new_link
train
def new_link(model_class, html_options: {}, &block) return if unauthorized? :new, model_class html_options, block = LinkOptionsNormalizer.normalize( html_options, block, class: 'resource__create', block: -> { t 'links.new', model: to_model_label(model_class) } ) link_to ...
ruby
{ "resource": "" }
q18468
Wallaby.LinksHelper.show_link
train
def show_link(resource, options: {}, html_options: {}, &block) # NOTE: to_s is a must # if a block is returning integer (e.g. `{ 1 }`) # `link_to` will render blank text note inside hyper link html_options, block = LinkOptionsNormalizer.normalize( html_options, block, block: -> {...
ruby
{ "resource": "" }
q18469
Wallaby.LinksHelper.edit_link
train
def edit_link(resource, options: {}, html_options: {}, &block) default = options[:readonly] && decorate(resource).to_label || nil return default if unauthorized? :edit, extract(resource) html_options, block = LinkOptionsNormalizer.normalize( html_options, block, class: 'resource__upda...
ruby
{ "resource": "" }
q18470
Wallaby.LinksHelper.delete_link
train
def delete_link(resource, options: {}, html_options: {}, &block) return if unauthorized? :destroy, extract(resource) html_options, block = LinkOptionsNormalizer.normalize( html_options, block, class: 'resource__destroy', block: -> { t 'links.delete' } ) html_options[:me...
ruby
{ "resource": "" }
q18471
Wallaby.LinksHelper.index_path
train
def index_path(model_class, url_params: {}) if url_params.is_a?(::ActionController::Parameters) \ && !url_params.permitted? url_params = {} end url_for url_params.to_h.reverse_merge( resources: to_resources_name(model_class), action: :index ) end
ruby
{ "resource": "" }
q18472
Wallaby.LinksHelper.new_path
train
def new_path(model_class, url_params: {}) url_for url_params.to_h.reverse_merge( resources: to_resources_name(model_class), action: :new ) end
ruby
{ "resource": "" }
q18473
Wallaby.LinksHelper.edit_path
train
def edit_path(resource, is_resource: false, url_params: {}) decorated = decorate resource return unless is_resource || decorated.primary_key_value url_for( url_params.to_h.reverse_merge( resources: decorated.resources_name, action: :edit, id: decorated.primary_k...
ruby
{ "resource": "" }
q18474
Wallaby.CustomPartialRenderer.render
train
def render(context, options, block) super rescue CellHandling => e CellUtils.render context, e.message, options[:locals], &block end
ruby
{ "resource": "" }
q18475
Wallaby.CustomPartialRenderer.find_partial
train
def find_partial(*) super.tap do |partial| raise CellHandling, partial.inspect if CellUtils.cell? partial.inspect end end
ruby
{ "resource": "" }
q18476
PNGlitch.Base.filter_types
train
def filter_types types = [] wrap_with_rewind(@filtered_data) do scanline_positions.each do |pos| @filtered_data.pos = pos byte = @filtered_data.read 1 types << byte.unpack('C').first end end types end
ruby
{ "resource": "" }
q18477
PNGlitch.Base.compress
train
def compress( level = Zlib::DEFAULT_COMPRESSION, window_bits = Zlib::MAX_WBITS, mem_level = Zlib::DEF_MEM_LEVEL, strategy = Zlib::DEFAULT_STRATEGY ) wrap_with_rewind(@compressed_data, @filtered_data) do z = Zlib::Deflate.new level, window_bits, mem_level, strategy until...
ruby
{ "resource": "" }
q18478
PNGlitch.Base.each_scanline
train
def each_scanline # :yield: scanline return enum_for :each_scanline unless block_given? prev_filters = self.filter_types is_refilter_needed = false filter_codecs = [] wrap_with_rewind(@filtered_data) do at = 0 scanline_positions.push(@filtered_data.size).inject do |pos, del...
ruby
{ "resource": "" }
q18479
PNGlitch.Base.width=
train
def width= w @head_data.pos = 8 while bytes = @head_data.read(8) length, type = bytes.unpack 'Na*' if type == 'IHDR' @head_data << [w].pack('N') @head_data.pos -= 4 data = @head_data.read length @head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('...
ruby
{ "resource": "" }
q18480
PNGlitch.Base.height=
train
def height= h @head_data.pos = 8 while bytes = @head_data.read(8) length, type = bytes.unpack 'Na*' if type == 'IHDR' @head_data.pos += 4 @head_data << [h].pack('N') @head_data.pos -= 8 data = @head_data.read length @head_data << [Zlib.crc32(...
ruby
{ "resource": "" }
q18481
PNGlitch.Base.save
train
def save file wrap_with_rewind(@head_data, @tail_data, @compressed_data) do open(file, 'wb') do |io| io << @head_data.read chunk_size = @idat_chunk_size || @compressed_data.size type = 'IDAT' until @compressed_data.eof? do data = @compressed_data.read(ch...
ruby
{ "resource": "" }
q18482
PNGlitch.Base.wrap_with_rewind
train
def wrap_with_rewind *io, &block io.each do |i| i.rewind end yield io.each do |i| i.rewind end end
ruby
{ "resource": "" }
q18483
PNGlitch.Base.scanline_positions
train
def scanline_positions scanline_pos = [0] amount = @filtered_data.size @interlace_pass_count = [] if self.interlaced? # Adam7 # Pass 1 v = 1 + (@width / 8.0).ceil * @sample_size (@height / 8.0).ceil.times do scanline_pos << scanline_pos.last + v ...
ruby
{ "resource": "" }
q18484
PNGlitch.Scanline.register_filter_encoder
train
def register_filter_encoder encoder = nil, &block if !encoder.nil? && encoder.is_a?(Proc) @filter_codec[:encoder] = encoder elsif block_given? @filter_codec[:encoder] = block end save end
ruby
{ "resource": "" }
q18485
PNGlitch.Scanline.register_filter_decoder
train
def register_filter_decoder decoder = nil, &block if !decoder.nil? && decoder.is_a?(Proc) @filter_codec[:decoder] = decoder elsif block_given? @filter_codec[:decoder] = block end save end
ruby
{ "resource": "" }
q18486
PNGlitch.Scanline.save
train
def save pos = @io.pos @io.pos = @start_at @io << [Filter.guess(@filter_type)].pack('C') @io << self.data.slice(0, @data_size).ljust(@data_size, "\0") @io.pos = pos @callback.call(self) unless @callback.nil? self end
ruby
{ "resource": "" }
q18487
Benchmark.Perf.variance
train
def variance(measurements) return 0 if measurements.empty? avg = average(measurements) total = measurements.reduce(0) do |sum, x| sum + (x - avg)**2 end total.to_f / measurements.size end
ruby
{ "resource": "" }
q18488
Benchmark.Perf.assert_perform_under
train
def assert_perform_under(threshold, options = {}, &work) actual, _ = ExecutionTime.run(options, &work) actual <= threshold end
ruby
{ "resource": "" }
q18489
Benchmark.Perf.assert_perform_ips
train
def assert_perform_ips(iterations, options = {}, &work) mean, stddev, _ = Iteration.run(options, &work) iterations <= (mean + 3 * stddev) end
ruby
{ "resource": "" }
q18490
HCl.App.run
train
def run request_config if @options[:reauth] if @options[:changelog] system %[ more "#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}" ] exit end begin if @command if command? @command result = send @command, *@args if not ...
ruby
{ "resource": "" }
q18491
HCl.Utility.time2float
train
def time2float time_string if time_string =~ /:/ hours, minutes = time_string.split(':') hours.to_f + (minutes.to_f / 60.0) else time_string.to_f end end
ruby
{ "resource": "" }
q18492
HCl.DayEntry.append_note
train
def append_note http, new_notes # If I don't include hours it gets reset. # This doens't appear to be the case for task and project. (self.notes << "\n#{new_notes}").lstrip! http.post "daily/update/#{id}", notes:notes, hours:hours end
ruby
{ "resource": "" }
q18493
HCl.Commands.status
train
def status result = Faraday.new("http://kccljmymlslr.statuspage.io/api/v2") do |f| f.adapter Faraday.default_adapter end.get('status.json').body json = Yajl::Parser.parse result, symbolize_keys: true status = json[:status][:description] updated_at = DateTime.parse(json[:page][:upd...
ruby
{ "resource": "" }
q18494
Goodreads.Shelves.shelves
train
def shelves(user_id, options = {}) options = options.merge(user_id: user_id, v: 2) data = request("/shelf/list.xml", options) shelves = data["shelves"] shelves = data["shelves"]["user_shelf"].map do |s| Hashie::Mash.new({ id: s["id"], name: s["n...
ruby
{ "resource": "" }
q18495
Goodreads.Shelves.shelf
train
def shelf(user_id, shelf_name, options = {}) options = options.merge(shelf: shelf_name, v: 2) data = request("/review/list/#{user_id}.xml", options) reviews = data["reviews"]["review"] books = [] unless reviews.nil? # one-book results come back as a single hash reviews = [...
ruby
{ "resource": "" }
q18496
Goodreads.Shelves.add_to_shelf
train
def add_to_shelf(book_id, shelf_name, options = {}) options = options.merge(book_id: book_id, name: shelf_name, v: 2) data = oauth_request_method(:post, "/shelf/add_to_shelf.xml", options) # when a book is on a single shelf it is a single hash shelves = data["my_review"]["shelves"]["shelf"] ...
ruby
{ "resource": "" }
q18497
Goodreads.Request.request
train
def request(path, params = {}) if oauth_configured? oauth_request(path, params) else http_request(path, params) end end
ruby
{ "resource": "" }
q18498
Goodreads.Request.http_request
train
def http_request(path, params) token = api_key || Goodreads.configuration[:api_key] fail(Goodreads::ConfigurationError, "API key required.") if token.nil? params.merge!(format: API_FORMAT, key: token) url = "#{API_URL}#{path}" resp = RestClient.get(url, params: params) do |response, req...
ruby
{ "resource": "" }
q18499
Goodreads.Request.oauth_request_method
train
def oauth_request_method(http_method, path, params = {}) fail "OAuth access token required!" unless @oauth_token headers = { "Accept" => "application/xml" } resp = if http_method == :get || http_method == :delete if params url_params = params.map { |k, v| "#{k}=#{v}" }.join("&") ...
ruby
{ "resource": "" }