_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 < StandardError and error_mapping.has_key?(klass)
end
if normalised_class
mapped = error_mapping[normalised_class]
if mapped.respond_to?(:call)
exception = mapped.call(exception)
else
exception = mapped.new exception.message
end
end
self.status = lookup_error_status(exception)
render_json({
:error => lookup_error_name(exception).to_s,
:error_description => lookup_error_message(exception)
}.merge(lookup_error_metadata(exception)))
end | 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
else
objects
end
end | 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_to_json(json) unless json.respond_to?(:to_str)
# Encode the object to json.
self.status ||= :ok
self.content_type ||= Mime::JSON
self.response_body = json
headers['Content-Length'] = Rack::Utils.bytesize(json).to_s
end | 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 object, options
end
end
end | 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_port = DEFAULT_SSH_PORT if ssh_port.empty?
region = DEFAULT_REGION if region.empty?
image = DEFAULT_IMAGE if image.empty?
size = DEFAULT_SIZE if size.empty?
default_ssh_key = DEFAULT_SSH_KEY if ssh_key.empty?
if private_networking.empty?
private_networking = DEFAULT_PRIVATE_NETWORKING
end
backups_enabled = DEFAULT_BACKUPS_ENABLED if backups_enabled.empty?
ip6 = DEFAULT_IP6 if ip6.empty?
timeout = DEFAULT_TIMEOUT if timeout.empty?
require 'yaml'
File.open(@path, File::RDWR | File::TRUNC | File::CREAT, 0o600) do |file|
data = {
'authentication' => {
'access_token' => access_token
},
'connection' => {
'timeout' => timeout
},
'ssh' => {
'ssh_user' => ssh_user,
'ssh_key_path' => ssh_key_path,
'ssh_port' => ssh_port
},
'defaults' => {
'region' => region,
'image' => image,
'size' => size,
'ssh_key' => ssh_key,
'private_networking' => private_networking,
'backups_enabled' => backups_enabled,
'ip6' => ip6
}
}
file.write data.to_yaml
end
end | 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)
when Excon::Errors::Error
return HttpError.new("Error making HTTP request: #{error.message}")
end
error
end | 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] || {}))
CrowdFlower.request_hook.call(method_id, path, options) do
self.class.send(method_id, url(path), options)
end
else
super
end
end | 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.delete index_type # not_foo
index_types.delete $1.to_sym # foo
end
end
# Map names and values
results = {}
# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
field_value = [field_value] if field_value.kind_of? Time
index_types.each do |index_type|
Array(field_value).each do |single_value|
# Get mapping for field
descriptor = indexer(index_type)
data_type = extract_type(single_value)
name, converter = descriptor.name_and_converter(field_name, type: data_type)
next unless name
# Is there a custom converter?
# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.
value = if converter
if converter.arity == 1
converter.call(single_value)
else
converter.call(single_value, field_name)
end
elsif data_type == :boolean
single_value
else
single_value.to_s
end
# Add mapped name & value, unless it's a duplicate
if descriptor.evaluate_suffix(data_type).multivalued?
values = (results[name] ||= [])
values << value unless value.nil? || values.include?(value)
else
Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
results[name] = value
end
end
end
results
end | 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 line.length >= width
@terminal_width = [@terminal_width - (line.length - width + 1), 0].max
if @terminal_width == 0 then @out.print(line + eol) else show end
else # line.length < width - 1
@terminal_width += width - line.length + 1
show
end
@previous_time = Time.now
end | 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 "Raw rack session data"
xml.pre RackSessionAccess.encode(session_hash)
end
else
render do |xml|
xml.h2 "Rack session data"
xml.ul do |ul|
session_hash.each do |k,v|
ul.li("#{k.inspect} : #{v.inspect}")
end
end
xml.p do |p|
p.a("Edit", :href => action_path(:edit))
end
end
end
end | 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'
}) do |form|
form.input(:type => 'hidden', :name =>'_method', :value => 'put')
form.textarea(:cols => 40, :rows => 10, :name => 'data') {}
form.p do |p|
p.input(:type => 'submit', :value => "Update")
end
end
end
end | 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
redirect_to action_path(:show)
end | 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)
qrevpassword = mask_qwerty_strings(revpassword, qwertystr)
if qpassword != base_password
numbits = EntropyCalculator.calculate(qpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
if qrevpassword != revpassword
numbits = EntropyCalculator.calculate(qrevpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
end
min_entropy
end | 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 passwords, while looking for possible matching words in the dictionary.
PasswordVariants.all_variants(base_password).inject( min_entropy ) do |min_entropy, variant|
[ min_entropy, EntropyCalculator.calculate( variant.sub( dictionary_words, '*' ) ) ].min
end
end | 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_html = Kompress::HTML.new(timeline_markup).html
@js << File.open("#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js", 'r').read
@timeline = tmpl("timeline-min.erb")
end | 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
when 0..2
# Old format (pre-json), so read the directories segment then rebuild
len = stream.gets.to_i
add_paths(Marshal.load(stream.read(len)))
return false
else
raise UnknownDBFormatError
end
rescue Oj::ParseError
stream.rewind
raise unless stream.gets.to_i == DB_FORMAT
# try reading as formated json, which is much slower, but it is sometimes
# useful to be able to directly read your db
objects = []
Oj.load(stream) { |obj| objects << obj }
@meta, @tables = objects
return true
end | 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
vertex.uv = Vector2.new(u, 1.0 - v)
vertex
end | 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),
correct_uv(v3.uv, v3, azi)
]
end | 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, i.to_f / cols.to_f))
bj = prepare(b.clone.lerp(c, i.to_f / cols.to_f))
rows = cols - i
for j in 0..rows do
v[i][j] = if j.zero? && i == cols
aj
else
prepare(aj.clone.lerp(bj, j.to_f / rows.to_f))
end
end
end
# Construct all of the faces
for i in 0...cols do
for j in (0...(2 * (cols - i) - 1)) do
k = j/2
if j.even?
make(
v[i][k + 1],
v[i + 1][k],
v[i][k]
)
else
make(
v[i][k + 1],
v[i + 1][k + 1],
v[i + 1][k]
)
end
end
end
end | 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.shadow_camera_visible
virtual_light.shadow_darkness = light.shadow_darkness
virtual_light.shadow_bias = light.shadow_cascade_bias[cascade]
near_z = light.shadow_cascade_near_z[cascade]
far_z = light.shadow_cascade_far_z[cascade]
points_frustum = virtual_light.points_frustum
points_frustum[0].z = near_z
points_frustum[1].z = near_z
points_frustum[2].z = near_z
points_frustum[3].z = near_z
points_frustum[4].z = far_z
points_frustum[5].z = far_z
points_frustum[6].z = far_z
points_frustum[7].z = far_z
end | 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 |i|
p = points_world[i]
p.copy(points_frustum[i])
p.unproject(camera)
p.apply_matrix4(shadow_camera.matrix_world_inverse)
@min.x = p.x if (p.x < @min.x)
@max.x = p.x if (p.x > @max.x)
@min.y = p.y if (p.y < @min.y)
@max.y = p.y if (p.y > @max.y)
@min.z = p.z if (p.z < @min.z)
@max.z = p.z if (p.z > @max.z)
end
shadow_camera.left = @min.x
shadow_camera.right = @max.x
shadow_camera.top = @max.y
shadow_camera.bottom = @min.y
# can't really fit near/far
# shadow_camera.near = @min.x
# shadow_camera.far = @max.z
shadow_camera.update_projection_matrix
end | 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}://www.gravatar.com/avatar/#{email_md5}"
image_tag image_source, class: 'user'
else
fa_icon 'user'
end
end | 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
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('errors.unprocessable_entity.model', model: model_class)
end
model_class
end | 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, title, class: 'modaler__title')
concat content_tag(:span, body, class: 'modaler__body')
end
end | 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)
else index_params.merge(filter: filter_name).merge(url_params)
end
index_link(model_class, url_params: url_params) { label }
end | 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
nested_hash.values.select { |v| v.parent.nil? }
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, options).try :<<, model_tree(node.children)
concat content_tag(:li, content)
end
end
end | 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 || {}
end | 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_params
link_to path, html_options, &block
end | 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 new_path(model_class), html_options, &block
end | 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: -> { decorate(resource).to_label.to_s }
)
default = options[:readonly] && block.call || nil
return default if unauthorized? :show, extract(resource)
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | 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__update',
block: -> { "#{t 'links.edit'} #{decorate(resource).to_label}" }
)
link_to edit_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | 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[:method] ||= :delete
html_options[:data] ||= {}
html_options[:data][:confirm] ||= t 'links.confirm.delete'
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end | 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_key_value
).delete_if { |_, v| v.blank? }
)
end | 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 @filtered_data.eof? do
buffer_size = 2 ** 16
flush = Zlib::NO_FLUSH
flush = Zlib::FINISH if @filtered_data.size - @filtered_data.pos < buffer_size
@compressed_data << z.deflate(@filtered_data.read(buffer_size), flush)
end
z.finish
z.close
truncate_io @compressed_data
end
@is_compressed_data_modified = false
self
end | 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, delimit|
scanline = Scanline.new @filtered_data, pos, (delimit - pos - 1), at
yield scanline
if fabricate_scanline(scanline, prev_filters, filter_codecs)
is_refilter_needed = true
end
at += 1
delimit
end
end
apply_filters(prev_filters, filter_codecs) if is_refilter_needed
compress
self
end | 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('N')
break
end
end
@head_data.rewind
w
end | 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(data, Zlib.crc32(type))].pack('N')
@head_data.rewind
break
end
end
@head_data.rewind
h
end | 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(chunk_size)
io << [data.size].pack('N')
io << type
io << data
io << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
end
io << @tail_data.read
end
end
self
end | 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
end
@interlace_pass_count << scanline_pos.size
# Pass 2
v = 1 + ((@width - 4) / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 3
v = 1 + (@width / 4.0).ceil * @sample_size
((@height - 4) / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 4
v = 1 + ((@width - 2) / 4.0).ceil * @sample_size
(@height / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 5
v = 1 + (@width / 2.0).ceil * @sample_size
((@height - 2) / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 6
v = 1 + ((@width - 1) / 2.0).ceil * @sample_size
(@height / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 7
v = 1 + @width * @sample_size
((@height - 1) / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
scanline_pos.pop # no need to keep last position
end
loop do
v = scanline_pos.last + (1 + @width * @sample_size)
break if v >= amount
scanline_pos << v
end
scanline_pos
end | 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 result.nil?
if result.respond_to? :join, include_all=false
puts result.join(', ')
elsif result.respond_to? :to_s, include_all=false
puts result
end
end
else
puts start(@command, *@args)
end
else
puts show
end
rescue CommandError => e
$stderr.puts e
exit 1
rescue RuntimeError => e
$stderr.puts "Error: #{e}"
exit 1
rescue Faraday::Error => e
$stderr.puts "Connection failed. (#{e.message})"
exit 1
rescue HarvestMiddleware::ThrottleFailure => e
$stderr.puts "Too many requests, retrying in #{e.retry_after+5} seconds..."
sleep e.retry_after+5
run
rescue HarvestMiddleware::AuthFailure => e
$stderr.puts "Unable to authenticate: #{e}"
request_config
run
rescue HarvestMiddleware::Failure => e
$stderr.puts "API failure: #{e}"
exit 1
end
end | 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][:updated_at]).strftime "%F %T %:z"
"#{status} [#{updated_at}]"
end | 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["name"],
book_count: s["book_count"],
exclusive: s["exclusive_flag"],
description: s["description"],
sort: s["sort"],
order: s["order"],
per_page: s["per_page"],
display_fields: s["display_fields"],
featured: s["featured"],
recommend_for: s["recommend_for"],
sticky: s["sticky"],
})
end
Hashie::Mash.new(
start: data["shelves"]["start"].to_i,
end: data["shelves"]["end"].to_i,
total: data["shelves"]["total"].to_i,
shelves: shelves
)
end | 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 = [reviews] unless reviews.instance_of?(Array)
books = reviews.map { |e| Hashie::Mash.new(e) }
end
Hashie::Mash.new(
start: data["reviews"]["start"].to_i,
end: data["reviews"]["end"].to_i,
total: data["reviews"]["total"].to_i,
books: books
)
end | 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"]
shelves = [shelves] unless shelves.instance_of?(Array)
shelves = shelves.map do |s|
Hashie::Mash.new({
id: s["id"].to_i,
name: s["name"],
exclusive: s["exclusive"] == "true",
sortable: s["sortable"] == "true",
})
end
Hashie::Mash.new(
id: data["my_review"]["id"].to_i,
book_id: data["my_review"]["book_id"].to_i,
rating: data["my_review"]["rating"].to_i,
body: data["my_review"]["body"],
body_raw: data["my_review"]["body_raw"],
spoiler: data["my_review"]["spoiler_flag"] == "true",
shelves: shelves,
read_at: data["my_review"]["read_at"],
started_at: data["my_review"]["started_at"],
date_added: data["my_review"]["date_added"],
updated_at: data["my_review"]["updated_at"],
)
end | 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, request, result, &block|
case response.code
when 200
response.return!(&block)
when 401
fail(Goodreads::Unauthorized)
when 403
fail(Goodreads::Forbidden)
when 404
fail(Goodreads::NotFound)
end
end
parse(resp)
end | 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("&")
path = "#{path}?#{url_params}"
end
@oauth_token.request(http_method, path, headers)
else
@oauth_token.request(http_method, path, params || {}, headers)
end
case resp
when Net::HTTPUnauthorized
fail Goodreads::Unauthorized
when Net::HTTPNotFound
fail Goodreads::NotFound
end
parse(resp)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.