_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q15000 | Sass::Script::Tree.Funcall._perform | train | def _perform(environment)
args = @args.each_with_index.
map {|a, i| perform_arg(a, environment, signature && signature.args[i])}
keywords = Sass::Util.map_hash(@keywords) do |k, v|
[k, perform_arg(v, environment, k.tr('-', '_'))]
end
splat = Sass::Tree::Visitors::Perform.perform_splat(
@splat, keywords, @kwarg_splat, environment)
fn = @callable || environment.function(@name)
if fn && fn.origin == :stylesheet
environment.stack.with_function(filename, line, name) do
return without_original(perform_sass_fn(fn, args, splat, environment))
end
end
args = construct_ruby_args(ruby_name, args, splat, environment)
if Sass::Script::Functions.callable?(ruby_name) && (!fn || fn.origin == :builtin)
local_environment = Sass::Environment.new(environment.global_env, environment.options)
local_environment.caller = Sass::ReadOnlyEnvironment.new(environment, environment.options)
result = local_environment.stack.with_function(filename, line, name) do
opts(Sass::Script::Functions::EvaluationContext.new(
local_environment).send(ruby_name, *args))
end
without_original(result)
else
opts(to_literal(args))
end
rescue ArgumentError => e
reformat_argument_error(e)
end | ruby | {
"resource": ""
} |
q15001 | Sass.ReadOnlyEnvironment.caller | train | def caller
return @caller if @caller
env = super
@caller ||= env.is_a?(ReadOnlyEnvironment) ? env : ReadOnlyEnvironment.new(env, env.options)
end | ruby | {
"resource": ""
} |
q15002 | Sass.ReadOnlyEnvironment.content | train | def content
# Return the cached content from a previous invocation if any
return @content if @content_cached
# get the content with a read-write environment from the superclass
read_write_content = super
if read_write_content
tree, env = read_write_content
# make the content's environment read-only
if env && !env.is_a?(ReadOnlyEnvironment)
env = ReadOnlyEnvironment.new(env, env.options)
end
@content_cached = true
@content = [tree, env]
else
@content_cached = true
@content = nil
end
end | ruby | {
"resource": ""
} |
q15003 | Sass::Script::Tree.Interpolation.to_string_interpolation | train | def to_string_interpolation(node_or_interp)
unless node_or_interp.is_a?(Interpolation)
node = node_or_interp
return string_literal(node.value.to_s) if node.is_a?(Literal)
if node.is_a?(StringInterpolation)
return concat(string_literal(node.quote), concat(node, string_literal(node.quote)))
end
return StringInterpolation.new(string_literal(""), node, string_literal(""))
end
interp = node_or_interp
after_string_or_interp =
if interp.after
to_string_interpolation(interp.after)
else
string_literal("")
end
if interp.after && interp.whitespace_after
after_string_or_interp = concat(string_literal(' '), after_string_or_interp)
end
mid_string_or_interp = to_string_interpolation(interp.mid)
before_string_or_interp =
if interp.before
to_string_interpolation(interp.before)
else
string_literal("")
end
if interp.before && interp.whitespace_before
before_string_or_interp = concat(before_string_or_interp, string_literal(' '))
end
concat(before_string_or_interp, concat(mid_string_or_interp, after_string_or_interp))
end | ruby | {
"resource": ""
} |
q15004 | Sass::Script::Tree.Interpolation.concat | train | def concat(string_or_interp1, string_or_interp2)
if string_or_interp1.is_a?(Literal) && string_or_interp2.is_a?(Literal)
return string_literal(string_or_interp1.value.value + string_or_interp2.value.value)
end
if string_or_interp1.is_a?(Literal)
string = string_or_interp1
interp = string_or_interp2
before = string_literal(string.value.value + interp.before.value.value)
return StringInterpolation.new(before, interp.mid, interp.after)
end
StringInterpolation.new(
string_or_interp1.before,
string_or_interp1.mid,
concat(string_or_interp1.after, string_or_interp2))
end | ruby | {
"resource": ""
} |
q15005 | Sass::Script::Tree.Interpolation.string_literal | train | def string_literal(string)
Literal.new(Sass::Script::Value::String.new(string, :string))
end | ruby | {
"resource": ""
} |
q15006 | Sass::Exec.SassScss.process_result | train | def process_result
require 'sass'
if !@options[:update] && !@options[:watch] &&
@args.first && colon_path?(@args.first)
if @args.size == 1
@args = split_colon_path(@args.first)
else
@fake_update = true
@options[:update] = true
end
end
load_compass if @options[:compass]
return interactive if @options[:interactive]
return watch_or_update if @options[:watch] || @options[:update]
super
if @options[:sourcemap] != :none && @options[:output_filename]
@options[:sourcemap_filename] = Sass::Util.sourcemap_name(@options[:output_filename])
end
@options[:for_engine][:filename] = @options[:filename]
@options[:for_engine][:css_filename] = @options[:output] if @options[:output].is_a?(String)
@options[:for_engine][:sourcemap_filename] = @options[:sourcemap_filename]
@options[:for_engine][:sourcemap] = @options[:sourcemap]
run
end | ruby | {
"resource": ""
} |
q15007 | Sass.Deprecation.warn | train | def warn(filename, line, column_or_message, message = nil)
return if !@@allow_double_warnings && @seen.add?([filename, line]).nil?
if message
column = column_or_message
else
message = column_or_message
end
location = "line #{line}"
location << ", column #{column}" if column
location << " of #{filename}" if filename
Sass::Util.sass_warn("DEPRECATION WARNING on #{location}:\n#{message}")
end | ruby | {
"resource": ""
} |
q15008 | Sass::Plugin.Compiler.update_stylesheets | train | def update_stylesheets(individual_files = [])
Sass::Plugin.checked_for_updates = true
staleness_checker = StalenessChecker.new(engine_options)
files = file_list(individual_files)
run_updating_stylesheets(files)
updated_stylesheets = []
files.each do |file, css, sourcemap|
# TODO: Does staleness_checker need to check the sourcemap file as well?
if options[:always_update] || staleness_checker.stylesheet_needs_update?(css, file)
# XXX For consistency, this should return the sourcemap too, but it would
# XXX be an API change.
updated_stylesheets << [file, css]
update_stylesheet(file, css, sourcemap)
else
run_not_updating_stylesheet(file, css, sourcemap)
end
end
run_updated_stylesheets(updated_stylesheets)
end | ruby | {
"resource": ""
} |
q15009 | Sass::Plugin.Compiler.file_list | train | def file_list(individual_files = [])
files = individual_files.map do |tuple|
if engine_options[:sourcemap] == :none
tuple[0..1]
elsif tuple.size < 3
[tuple[0], tuple[1], Sass::Util.sourcemap_name(tuple[1])]
else
tuple.dup
end
end
template_location_array.each do |template_location, css_location|
Sass::Util.glob(File.join(template_location, "**", "[^_]*.s[ca]ss")).sort.each do |file|
# Get the relative path to the file
name = Sass::Util.relative_path_from(file, template_location).to_s
css = css_filename(name, css_location)
sourcemap = Sass::Util.sourcemap_name(css) unless engine_options[:sourcemap] == :none
files << [file, css, sourcemap]
end
end
files
end | ruby | {
"resource": ""
} |
q15010 | Sass::Plugin.Compiler.clean | train | def clean(individual_files = [])
file_list(individual_files).each do |(_, css_file, sourcemap_file)|
if File.exist?(css_file)
run_deleting_css css_file
File.delete(css_file)
end
if sourcemap_file && File.exist?(sourcemap_file)
run_deleting_sourcemap sourcemap_file
File.delete(sourcemap_file)
end
end
nil
end | ruby | {
"resource": ""
} |
q15011 | Sass::Script::Value.Color.with | train | def with(attrs)
attrs = attrs.reject {|_k, v| v.nil?}
hsl = !([:hue, :saturation, :lightness] & attrs.keys).empty?
rgb = !([:red, :green, :blue] & attrs.keys).empty?
if hsl && rgb
raise ArgumentError.new("Cannot specify HSL and RGB values for a color at the same time")
end
if hsl
[:hue, :saturation, :lightness].each {|k| attrs[k] ||= send(k)}
elsif rgb
[:red, :green, :blue].each {|k| attrs[k] ||= send(k)}
else
# If we're just changing the alpha channel,
# keep all the HSL/RGB stuff we've calculated
attrs = @attrs.merge(attrs)
end
attrs[:alpha] ||= alpha
Color.new(attrs, nil, :allow_both_rgb_and_hsl)
end | ruby | {
"resource": ""
} |
q15012 | Sass::Script::Value.Color.to_s | train | def to_s(opts = {})
return smallest if options[:style] == :compressed
return representation if representation
# IE10 doesn't properly support the color name "transparent", so we emit
# generated transparent colors as rgba(0, 0, 0, 0) in favor of that. See
# #1782.
return rgba_str if Number.basically_equal?(alpha, 0)
return name if name
alpha? ? rgba_str : hex_str
end | ruby | {
"resource": ""
} |
q15013 | Sass::Source.Map.shift_output_lines | train | def shift_output_lines(delta)
return if delta == 0
@data.each do |m|
m.output.start_pos.line += delta
m.output.end_pos.line += delta
end
end | ruby | {
"resource": ""
} |
q15014 | Sass::Source.Map.shift_output_offsets | train | def shift_output_offsets(delta)
return if delta == 0
@data.each do |m|
break if m.output.start_pos.line > 1
m.output.start_pos.offset += delta
m.output.end_pos.offset += delta if m.output.end_pos.line > 1
end
end | ruby | {
"resource": ""
} |
q15015 | Sass::Tree.CommentNode.lines | train | def lines
@value.inject(0) do |s, e|
next s + e.count("\n") if e.is_a?(String)
next s
end
end | ruby | {
"resource": ""
} |
q15016 | Sass.Plugin.force_update_stylesheets | train | def force_update_stylesheets(individual_files = [])
Compiler.new(
options.dup.merge(
:never_update => false,
:always_update => true,
:cache => false)).update_stylesheets(individual_files)
end | ruby | {
"resource": ""
} |
q15017 | Sass::Script.Functions.ie_hex_str | train | def ie_hex_str(color)
assert_type color, :Color, :color
alpha = Sass::Util.round(color.alpha * 255).to_s(16).rjust(2, '0')
identifier("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
end | ruby | {
"resource": ""
} |
q15018 | Sass::Script.Functions.adjust_color | train | def adjust_color(color, kwargs)
assert_type color, :Color, :color
with = Sass::Util.map_hash(
"red" => [-255..255, ""],
"green" => [-255..255, ""],
"blue" => [-255..255, ""],
"hue" => nil,
"saturation" => [-100..100, "%"],
"lightness" => [-100..100, "%"],
"alpha" => [-1..1, ""]
) do |name, (range, units)|
val = kwargs.delete(name)
next unless val
assert_type val, :Number, name
Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
adjusted = color.send(name) + val.value
adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
[name.to_sym, adjusted]
end
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
color.with(with)
end | ruby | {
"resource": ""
} |
q15019 | Sass::Script.Functions.change_color | train | def change_color(color, kwargs)
assert_type color, :Color, :color
with = Sass::Util.map_hash(
'red' => ['Red value', 0..255],
'green' => ['Green value', 0..255],
'blue' => ['Blue value', 0..255],
'hue' => [],
'saturation' => ['Saturation', 0..100, '%'],
'lightness' => ['Lightness', 0..100, '%'],
'alpha' => ['Alpha channel', 0..1]
) do |name, (desc, range, unit)|
val = kwargs.delete(name)
next unless val
assert_type val, :Number, name
if range
val = Sass::Util.check_range(desc, range, val, unit)
else
val = val.value
end
[name.to_sym, val]
end
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
color.with(with)
end | ruby | {
"resource": ""
} |
q15020 | Sass::Script.Functions.mix | train | def mix(color1, color2, weight = number(50))
assert_type color1, :Color, :color1
assert_type color2, :Color, :color2
assert_type weight, :Number, :weight
Sass::Util.check_range("Weight", 0..100, weight, '%')
# This algorithm factors in both the user-provided weight (w) and the
# difference between the alpha values of the two colors (a) to decide how
# to perform the weighted average of the two RGB values.
#
# It works by first normalizing both parameters to be within [-1, 1],
# where 1 indicates "only use color1", -1 indicates "only use color2", and
# all values in between indicated a proportionately weighted average.
#
# Once we have the normalized variables w and a, we apply the formula
# (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1.
# This formula has two especially nice properties:
#
# * When either w or a are -1 or 1, the combined weight is also that number
# (cases where w * a == -1 are undefined, and handled as a special case).
#
# * When a is 0, the combined weight is w, and vice versa.
#
# Finally, the weight of color1 is renormalized to be within [0, 1]
# and the weight of color2 is given by 1 minus the weight of color1.
p = (weight.value / 100.0).to_f
w = p * 2 - 1
a = color1.alpha - color2.alpha
w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0
w2 = 1 - w1
rgba = color1.rgb.zip(color2.rgb).map {|v1, v2| v1 * w1 + v2 * w2}
rgba << color1.alpha * p + color2.alpha * (1 - p)
rgb_color(*rgba)
end | ruby | {
"resource": ""
} |
q15021 | Sass::Script.Functions.quote | train | def quote(string)
assert_type string, :String, :string
if string.type != :string
quoted_string(string.value)
else
string
end
end | ruby | {
"resource": ""
} |
q15022 | Sass::Script.Functions.to_upper_case | train | def to_upper_case(string)
assert_type string, :String, :string
Sass::Script::Value::String.new(Sass::Util.upcase(string.value), string.type)
end | ruby | {
"resource": ""
} |
q15023 | Sass::Script.Functions.to_lower_case | train | def to_lower_case(string)
assert_type string, :String, :string
Sass::Script::Value::String.new(Sass::Util.downcase(string.value), string.type)
end | ruby | {
"resource": ""
} |
q15024 | Sass::Script.Functions.type_of | train | def type_of(value)
value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
identifier(value.class.name.gsub(/Sass::Script::Value::/, '').downcase)
end | ruby | {
"resource": ""
} |
q15025 | Sass::Script.Functions.comparable | train | def comparable(number1, number2)
assert_type number1, :Number, :number1
assert_type number2, :Number, :number2
bool(number1.comparable_to?(number2))
end | ruby | {
"resource": ""
} |
q15026 | Sass::Script.Functions.percentage | train | def percentage(number)
unless number.is_a?(Sass::Script::Value::Number) && number.unitless?
raise ArgumentError.new("$number: #{number.inspect} is not a unitless number")
end
number(number.value * 100, '%')
end | ruby | {
"resource": ""
} |
q15027 | Sass::Script.Functions.min | train | def min(*numbers)
numbers.each {|n| assert_type n, :Number}
numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
end | ruby | {
"resource": ""
} |
q15028 | Sass::Script.Functions.max | train | def max(*values)
values.each {|v| assert_type v, :Number}
values.inject {|max, val| max.gt(val).to_bool ? max : val}
end | ruby | {
"resource": ""
} |
q15029 | Sass::Script.Functions.set_nth | train | def set_nth(list, n, value)
assert_type n, :Number, :n
Sass::Script::Value::List.assert_valid_index(list, n)
index = n.to_i > 0 ? n.to_i - 1 : n.to_i
new_list = list.to_a.dup
new_list[index] = value
list.with_contents(new_list)
end | ruby | {
"resource": ""
} |
q15030 | Sass::Script.Functions.nth | train | def nth(list, n)
assert_type n, :Number, :n
Sass::Script::Value::List.assert_valid_index(list, n)
index = n.to_i > 0 ? n.to_i - 1 : n.to_i
list.to_a[index]
end | ruby | {
"resource": ""
} |
q15031 | Sass::Script.Functions.join | train | def join(list1, list2,
separator = identifier("auto"), bracketed = identifier("auto"),
kwargs = nil, *rest)
if separator.is_a?(Hash)
kwargs = separator
separator = identifier("auto")
elsif bracketed.is_a?(Hash)
kwargs = bracketed
bracketed = identifier("auto")
elsif rest.last.is_a?(Hash)
rest.unshift kwargs
kwargs = rest.pop
end
unless rest.empty?
# Add 4 to rest.length because we don't want to count the kwargs hash,
# which is always passed.
raise ArgumentError.new("wrong number of arguments (#{rest.length + 4} for 2..4)")
end
if kwargs
separator = kwargs.delete("separator") || separator
bracketed = kwargs.delete("bracketed") || bracketed
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
end
assert_type separator, :String, :separator
unless %w(auto space comma).include?(separator.value)
raise ArgumentError.new("Separator name must be space, comma, or auto")
end
list(list1.to_a + list2.to_a,
separator:
if separator.value == 'auto'
list1.separator || list2.separator || :space
else
separator.value.to_sym
end,
bracketed:
if bracketed.is_a?(Sass::Script::Value::String) && bracketed.value == 'auto'
list1.bracketed
else
bracketed.to_bool
end)
end | ruby | {
"resource": ""
} |
q15032 | Sass::Script.Functions.append | train | def append(list, val, separator = identifier("auto"))
assert_type separator, :String, :separator
unless %w(auto space comma).include?(separator.value)
raise ArgumentError.new("Separator name must be space, comma, or auto")
end
list.with_contents(list.to_a + [val],
separator:
if separator.value == 'auto'
list.separator || :space
else
separator.value.to_sym
end)
end | ruby | {
"resource": ""
} |
q15033 | Sass::Script.Functions.zip | train | def zip(*lists)
length = nil
values = []
lists.each do |list|
array = list.to_a
values << array.dup
length = length.nil? ? array.length : [length, array.length].min
end
values.each do |value|
value.slice!(length)
end
new_list_value = values.first.zip(*values[1..-1])
list(new_list_value.map {|list| list(list, :space)}, :comma)
end | ruby | {
"resource": ""
} |
q15034 | Sass::Script.Functions.index | train | def index(list, value)
index = list.to_a.index {|e| e.eq(value).to_bool}
index ? number(index + 1) : null
end | ruby | {
"resource": ""
} |
q15035 | Sass::Script.Functions.map_remove | train | def map_remove(map, *keys)
assert_type map, :Map, :map
hash = map.to_h.dup
hash.delete_if {|key, _| keys.include?(key)}
map(hash)
end | ruby | {
"resource": ""
} |
q15036 | Sass::Script.Functions.map_has_key | train | def map_has_key(map, key)
assert_type map, :Map, :map
bool(map.to_h.has_key?(key))
end | ruby | {
"resource": ""
} |
q15037 | Sass::Script.Functions.unique_id | train | def unique_id
generator = Sass::Script::Functions.random_number_generator
Thread.current[:sass_last_unique_id] ||= generator.rand(36**8)
# avoid the temptation of trying to guess the next unique value.
value = (Thread.current[:sass_last_unique_id] += (generator.rand(10) + 1))
# the u makes this a legal identifier if it would otherwise start with a number.
identifier("u" + value.to_s(36).rjust(8, '0'))
end | ruby | {
"resource": ""
} |
q15038 | Sass::Script.Functions.variable_exists | train | def variable_exists(name)
assert_type name, :String, :name
bool(environment.caller.var(name.value))
end | ruby | {
"resource": ""
} |
q15039 | Sass::Script.Functions.function_exists | train | def function_exists(name)
assert_type name, :String, :name
exists = Sass::Script::Functions.callable?(name.value.tr("-", "_"))
exists ||= environment.caller.function(name.value)
bool(exists)
end | ruby | {
"resource": ""
} |
q15040 | Sass::Script.Functions.content_exists | train | def content_exists
# frames.last is the stack frame for this function,
# so we use frames[-2] to get the frame before that.
mixin_frame = environment.stack.frames[-2]
unless mixin_frame && mixin_frame.type == :mixin
raise Sass::SyntaxError.new("Cannot call content-exists() except within a mixin.")
end
bool(!environment.caller.content.nil?)
end | ruby | {
"resource": ""
} |
q15041 | Sass::Script.Functions.inspect | train | def inspect(value)
value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
unquoted_string(value.to_sass)
end | ruby | {
"resource": ""
} |
q15042 | Sass::Script.Functions.selector_unify | train | def selector_unify(selector1, selector2)
selector1 = parse_selector(selector1, :selector1)
selector2 = parse_selector(selector2, :selector2)
return null unless (unified = selector1.unify(selector2))
unified.to_sass_script
end | ruby | {
"resource": ""
} |
q15043 | Sass::Script.Functions.numeric_transformation | train | def numeric_transformation(value)
assert_type value, :Number, :value
Sass::Script::Value::Number.new(
yield(value.value), value.numerator_units, value.denominator_units)
end | ruby | {
"resource": ""
} |
q15044 | Sass::Media.Query.merge | train | def merge(other)
m1, t1 = resolved_modifier.downcase, resolved_type.downcase
m2, t2 = other.resolved_modifier.downcase, other.resolved_type.downcase
t1 = t2 if t1.empty?
t2 = t1 if t2.empty?
if (m1 == 'not') ^ (m2 == 'not')
return if t1 == t2
type = m1 == 'not' ? t2 : t1
mod = m1 == 'not' ? m2 : m1
elsif m1 == 'not' && m2 == 'not'
# CSS has no way of representing "neither screen nor print"
return unless t1 == t2
type = t1
mod = 'not'
elsif t1 != t2
return
else # t1 == t2, neither m1 nor m2 are "not"
type = t1
mod = m1.empty? ? m2 : m1
end
Query.new([mod], [type], other.expressions + expressions)
end | ruby | {
"resource": ""
} |
q15045 | Sass::Media.Query.to_css | train | def to_css
css = ''
css << resolved_modifier
css << ' ' unless resolved_modifier.empty?
css << resolved_type
css << ' and ' unless resolved_type.empty? || expressions.empty?
css << expressions.map do |e|
# It's possible for there to be script nodes in Expressions even when
# we're converting to CSS in the case where we parsed the document as
# CSS originally (as in css_test.rb).
e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.to_sass : c.to_s}.join
end.join(' and ')
css
end | ruby | {
"resource": ""
} |
q15046 | Sass::Media.Query.deep_copy | train | def deep_copy
Query.new(
modifier.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c},
type.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c},
expressions.map {|e| e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.deep_copy : c}})
end | ruby | {
"resource": ""
} |
q15047 | Sass::Script::Tree.ListLiteral.element_needs_parens? | train | def element_needs_parens?(element)
if element.is_a?(ListLiteral)
return false if element.elements.length < 2
return false if element.bracketed
return Sass::Script::Parser.precedence_of(element.separator || :space) <=
Sass::Script::Parser.precedence_of(separator || :space)
end
return false unless separator == :space
if element.is_a?(UnaryOperation)
return element.operator == :minus || element.operator == :plus
end
return false unless element.is_a?(Operation)
return true unless element.operator == :div
!(is_literal_number?(element.operand1) && is_literal_number?(element.operand2))
end | ruby | {
"resource": ""
} |
q15048 | Sass::Script::Tree.ListLiteral.is_literal_number? | train | def is_literal_number?(value)
value.is_a?(Literal) &&
value.value.is_a?((Sass::Script::Value::Number)) &&
!value.value.original.nil?
end | ruby | {
"resource": ""
} |
q15049 | Sass.CSS.build_tree | train | def build_tree
root = Sass::SCSS::CssParser.new(@template, @options[:filename], nil).parse
parse_selectors(root)
expand_commas(root)
nest_seqs(root)
parent_ref_rules(root)
flatten_rules(root)
bubble_subject(root)
fold_commas(root)
dump_selectors(root)
root
end | ruby | {
"resource": ""
} |
q15050 | Sass.CSS.nest_seqs | train | def nest_seqs(root)
current_rule = nil
root.children.map! do |child|
unless child.is_a?(Tree::RuleNode)
nest_seqs(child) if child.is_a?(Tree::DirectiveNode)
next child
end
seq = first_seq(child)
seq.members.reject! {|sseq| sseq == "\n"}
first, rest = seq.members.first, seq.members[1..-1]
if current_rule.nil? || first_sseq(current_rule) != first
current_rule = Tree::RuleNode.new([])
current_rule.parsed_rules = make_seq(first)
end
if rest.empty?
current_rule.children += child.children
else
child.parsed_rules = make_seq(*rest)
current_rule << child
end
current_rule
end
root.children.compact!
root.children.uniq!
root.children.each {|v| nest_seqs(v)}
end | ruby | {
"resource": ""
} |
q15051 | Sass.CSS.parent_ref_rules | train | def parent_ref_rules(root)
current_rule = nil
root.children.map! do |child|
unless child.is_a?(Tree::RuleNode)
parent_ref_rules(child) if child.is_a?(Tree::DirectiveNode)
next child
end
sseq = first_sseq(child)
next child unless sseq.is_a?(Sass::Selector::SimpleSequence)
firsts, rest = [sseq.members.first], sseq.members[1..-1]
firsts.push rest.shift if firsts.first.is_a?(Sass::Selector::Parent)
last_simple_subject = rest.empty? && sseq.subject?
if current_rule.nil? || first_sseq(current_rule).members != firsts ||
!!first_sseq(current_rule).subject? != !!last_simple_subject
current_rule = Tree::RuleNode.new([])
current_rule.parsed_rules = make_sseq(last_simple_subject, *firsts)
end
if rest.empty?
current_rule.children += child.children
else
rest.unshift Sass::Selector::Parent.new
child.parsed_rules = make_sseq(sseq.subject?, *rest)
current_rule << child
end
current_rule
end
root.children.compact!
root.children.uniq!
root.children.each {|v| parent_ref_rules(v)}
end | ruby | {
"resource": ""
} |
q15052 | Sass.CSS.flatten_rules | train | def flatten_rules(root)
root.children.each do |child|
case child
when Tree::RuleNode
flatten_rule(child)
when Tree::DirectiveNode
flatten_rules(child)
end
end
end | ruby | {
"resource": ""
} |
q15053 | Sass.CSS.flatten_rule | train | def flatten_rule(rule)
while rule.children.size == 1 && rule.children.first.is_a?(Tree::RuleNode)
child = rule.children.first
if first_simple_sel(child).is_a?(Sass::Selector::Parent)
rule.parsed_rules = child.parsed_rules.resolve_parent_refs(rule.parsed_rules)
else
rule.parsed_rules = make_seq(*(first_seq(rule).members + first_seq(child).members))
end
rule.children = child.children
end
flatten_rules(rule)
end | ruby | {
"resource": ""
} |
q15054 | Sass::Tree::Visitors.Base.visit | train | def visit(node)
if respond_to?(node.class.visit_method, true)
send(node.class.visit_method, node) {visit_children(node)}
else
visit_children(node)
end
end | ruby | {
"resource": ""
} |
q15055 | Sass::Exec.SassConvert.process_result | train | def process_result
require 'sass'
if @options[:recursive]
process_directory
return
end
super
input = @options[:input]
if File.directory?(input)
raise "Error: '#{input.path}' is a directory (did you mean to use --recursive?)"
end
output = @options[:output]
output = input if @options[:in_place]
process_file(input, output)
end | ruby | {
"resource": ""
} |
q15056 | Sass::Script::Value.Number.mod | train | def mod(other)
if other.is_a?(Number)
return Number.new(Float::NAN) if other.value == 0
operate(other, :%)
else
raise NoMethodError.new(nil, :mod)
end
end | ruby | {
"resource": ""
} |
q15057 | Sass::Script::Value.Number.eq | train | def eq(other)
return Bool::FALSE unless other.is_a?(Sass::Script::Value::Number)
this = self
begin
if unitless?
this = this.coerce(other.numerator_units, other.denominator_units)
else
other = other.coerce(@numerator_units, @denominator_units)
end
rescue Sass::UnitConversionError
return Bool::FALSE
end
Bool.new(basically_equal?(this.value, other.value))
end | ruby | {
"resource": ""
} |
q15058 | Sass::Script::Value.Number.gt | train | def gt(other)
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
operate(other, :>)
end | ruby | {
"resource": ""
} |
q15059 | Sass::Script::Value.Number.gte | train | def gte(other)
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
operate(other, :>=)
end | ruby | {
"resource": ""
} |
q15060 | Sass::Script::Value.Number.lt | train | def lt(other)
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
operate(other, :<)
end | ruby | {
"resource": ""
} |
q15061 | Sass::Script::Value.Number.lte | train | def lte(other)
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
operate(other, :<=)
end | ruby | {
"resource": ""
} |
q15062 | Sass::Script::Value.Number.inspect | train | def inspect(opts = {})
return original if original
value = self.class.round(self.value)
str = value.to_s
# Ruby will occasionally print in scientific notation if the number is
# small enough. That's technically valid CSS, but it's not well-supported
# and confusing.
str = ("%0.#{self.class.precision}f" % value).gsub(/0*$/, '') if str.include?('e')
# Sometimes numeric formatting will result in a decimal number with a trailing zero (x.0)
if str =~ /(.*)\.0$/
str = $1
end
# We omit a leading zero before the decimal point in compressed mode.
if @options && options[:style] == :compressed
str.sub!(/^(-)?0\./, '\1.')
end
unitless? ? str : "#{str}#{unit_str}"
end | ruby | {
"resource": ""
} |
q15063 | Sass::Script::Value.Number.is_unit? | train | def is_unit?(unit)
if unit
denominator_units.size == 0 && numerator_units.size == 1 && numerator_units.first == unit
else
unitless?
end
end | ruby | {
"resource": ""
} |
q15064 | Sass::Script::Value.Base.plus | train | def plus(other)
type = other.is_a?(Sass::Script::Value::String) ? other.type : :identifier
Sass::Script::Value::String.new(to_s(:quote => :none) + other.to_s(:quote => :none), type)
end | ruby | {
"resource": ""
} |
q15065 | Sass::Script::Value.Base.with_contents | train | def with_contents(contents, separator: self.separator, bracketed: self.bracketed)
Sass::Script::Value::List.new(contents, separator: separator, bracketed: bracketed)
end | ruby | {
"resource": ""
} |
q15066 | Sass::Script::Tree.Variable._perform | train | def _perform(environment)
val = environment.var(name)
raise Sass::SyntaxError.new("Undefined variable: \"$#{name}\".") unless val
if val.is_a?(Sass::Script::Value::Number) && val.original
val = val.dup
val.original = nil
end
val
end | ruby | {
"resource": ""
} |
q15067 | Sass::Exec.Base.get_line | train | def get_line(exception)
# SyntaxErrors have weird line reporting
# when there's trailing whitespace
if exception.is_a?(::SyntaxError)
return (exception.message.scan(/:(\d+)/).first || ["??"]).first
end
(exception.backtrace[0].scan(/:(\d+)/).first || ["??"]).first
end | ruby | {
"resource": ""
} |
q15068 | Sass::Exec.Base.encoding_option | train | def encoding_option(opts)
encoding_desc = 'Specify the default encoding for input files.'
opts.on('-E', '--default-encoding ENCODING', encoding_desc) do |encoding|
Encoding.default_external = encoding
end
end | ruby | {
"resource": ""
} |
q15069 | Sass::Exec.Base.color | train | def color(color, str)
raise "[BUG] Unrecognized color #{color}" unless COLORS[color]
# Almost any real Unix terminal will support color,
# so we just filter for Windows terms (which don't set TERM)
# and not-real terminals, which aren't ttys.
return str if ENV["TERM"].nil? || ENV["TERM"].empty? || !STDOUT.tty?
"\e[#{COLORS[color]}m#{str}\e[0m"
end | ruby | {
"resource": ""
} |
q15070 | Sass::Script::Value.Helpers.hsl_color | train | def hsl_color(hue, saturation, lightness, alpha = nil)
attrs = {:hue => hue, :saturation => saturation, :lightness => lightness}
attrs[:alpha] = alpha if alpha
Color.new(attrs)
end | ruby | {
"resource": ""
} |
q15071 | Sass::Script::Value.Helpers.rgb_color | train | def rgb_color(red, green, blue, alpha = nil)
attrs = {:red => red, :green => green, :blue => blue}
attrs[:alpha] = alpha if alpha
Color.new(attrs)
end | ruby | {
"resource": ""
} |
q15072 | Sass::Script::Value.Helpers.parse_selector | train | def parse_selector(value, name = nil, allow_parent_ref = false)
str = normalize_selector(value, name)
begin
Sass::SCSS::StaticParser.new(str, nil, nil, 1, 1, allow_parent_ref).parse_selector
rescue Sass::SyntaxError => e
err = "#{value.inspect} is not a valid selector: #{e}"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end
end | ruby | {
"resource": ""
} |
q15073 | Sass::Script::Value.Helpers.parse_complex_selector | train | def parse_complex_selector(value, name = nil, allow_parent_ref = false)
selector = parse_selector(value, name, allow_parent_ref)
return seq if selector.members.length == 1
err = "#{value.inspect} is not a complex selector"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end | ruby | {
"resource": ""
} |
q15074 | Sass::Script::Value.Helpers.parse_compound_selector | train | def parse_compound_selector(value, name = nil, allow_parent_ref = false)
assert_type value, :String, name
selector = parse_selector(value, name, allow_parent_ref)
seq = selector.members.first
sseq = seq.members.first
if selector.members.length == 1 && seq.members.length == 1 &&
sseq.is_a?(Sass::Selector::SimpleSequence)
return sseq
end
err = "#{value.inspect} is not a compound selector"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end | ruby | {
"resource": ""
} |
q15075 | Sass::Script::Value.Helpers.normalize_selector | train | def normalize_selector(value, name)
if (str = selector_to_str(value))
return str
end
err = "#{value.inspect} is not a valid selector: it must be a string,\n" +
"a list of strings, or a list of lists of strings"
err = "$#{name.to_s.tr('_', '-')}: #{err}" if name
raise ArgumentError.new(err)
end | ruby | {
"resource": ""
} |
q15076 | Sass::Script::Value.Helpers.selector_to_str | train | def selector_to_str(value)
return value.value if value.is_a?(Sass::Script::String)
return unless value.is_a?(Sass::Script::List)
if value.separator == :comma
return value.to_a.map do |complex|
next complex.value if complex.is_a?(Sass::Script::String)
return unless complex.is_a?(Sass::Script::List) && complex.separator == :space
return unless (str = selector_to_str(complex))
str
end.join(', ')
end
value.to_a.map do |compound|
return unless compound.is_a?(Sass::Script::String)
compound.value
end.join(' ')
end | ruby | {
"resource": ""
} |
q15077 | Sass.SyntaxError.backtrace | train | def backtrace
return nil if super.nil?
return super if sass_backtrace.all? {|h| h.empty?}
sass_backtrace.map do |h|
"#{h[:filename] || '(sass)'}:#{h[:line]}" +
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
end + super
end | ruby | {
"resource": ""
} |
q15078 | Sass.SyntaxError.sass_backtrace_str | train | def sass_backtrace_str(default_filename = "an unknown file")
lines = message.split("\n")
msg = lines[0] + lines[1..-1].
map {|l| "\n" + (" " * "Error: ".size) + l}.join
"Error: #{msg}" +
sass_backtrace.each_with_index.map do |entry, i|
"\n #{i == 0 ? 'on' : 'from'} line #{entry[:line]}" +
" of #{entry[:filename] || default_filename}" +
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
end.join
end | ruby | {
"resource": ""
} |
q15079 | Rabl.CacheEngine.fetch | train | def fetch(key, cache_options, &block)
if defined?(Rails)
Rails.cache.fetch(key, cache_options, &block)
else
@cache[key] ||= yield
end
end | ruby | {
"resource": ""
} |
q15080 | Rabl.MultiBuilder.map_cache_key_to_engine | train | def map_cache_key_to_engine(engine)
if cache_key = cache_key_for(engine)
result_cache_key = ActiveSupport::Cache.expand_cache_key(cache_key, :rabl)
@cache_key_to_engine[result_cache_key] = engine
disable_cache_read_on_render(engine)
end
end | ruby | {
"resource": ""
} |
q15081 | Rabl.MultiBuilder.read_cache_results | train | def read_cache_results
@cache_results ||= begin
mutable_keys = @cache_key_to_engine.keys.map { |k| k.dup }
if mutable_keys.empty?
{}
else
Rabl.configuration.cache_engine.read_multi(*mutable_keys)
end
end
end | ruby | {
"resource": ""
} |
q15082 | Rabl.MultiBuilder.replace_engines_with_cache_results | train | def replace_engines_with_cache_results
@cache_results.each do |key, value|
engine = @cache_key_to_engine[key]
builder = @engine_to_builder[engine]
builder.replace_engine(engine, value) if value
end
end | ruby | {
"resource": ""
} |
q15083 | Rabl.Renderer.process_source | train | def process_source(source)
return source if source.is_a?(String) && source =~ /\n/
source, _ = engine.fetch_source(source, { :view_path => options[:view_path] })
source
end | ruby | {
"resource": ""
} |
q15084 | Rabl.Helpers.determine_object_root | train | def determine_object_root(data_token, data_name = nil, include_root = true)
return if object_root_name == false
root_name = data_name.to_s if include_root
if is_object?(data_token) || data_token.nil?
root_name
elsif is_collection?(data_token)
object_root_name || (root_name.singularize if root_name)
end
end | ruby | {
"resource": ""
} |
q15085 | Rabl.Helpers.is_collection? | train | def is_collection?(obj, follow_symbols = true)
data_obj = follow_symbols ? data_object(obj) : obj
data_obj &&
data_obj.is_a?(Enumerable) &&
!(data_obj.is_a?(Struct) ||
defined?(Hashie::Mash) && data_obj.is_a?(Hashie::Mash))
end | ruby | {
"resource": ""
} |
q15086 | Rabl.Helpers.object_to_engine | train | def object_to_engine(object, options = {}, &block)
return if object.nil?
options.reverse_merge!({
:format => "hash".freeze,
:view_path => view_path,
:root => (options[:root] || false)
})
Engine.new(options[:source], options).apply(context_scope, :object => object, :locals => options[:locals], &block)
end | ruby | {
"resource": ""
} |
q15087 | Rabl.Helpers.template_cache_configured? | train | def template_cache_configured?
if defined?(Rails)
defined?(ActionController::Base) && ActionController::Base.perform_caching
else
Rabl.configuration.perform_caching
end
end | ruby | {
"resource": ""
} |
q15088 | Rabl.Engine.object | train | def object(template_data)
current_data = (@_locals[:object].nil? || template_data == false) ? template_data : @_locals[:object]
@_data_object = data_object(current_data)
@_root_name_data = template_data.is_a?(Hash) && !current_data.is_a?(Hash) ? template_data : current_data
@_root_name_data = @_root_name_data.values.first if @_root_name_data.is_a?(Hash)
# If we turn this around, `@_root_name_date ==` may trigger data to be loaded unnecessarily.
# TODO: is nil a different semantic? otherwise don't use `false ==`, use !
if false == @_root_name_data
@_object_root_name = false
@_collection_name = false
end
end | ruby | {
"resource": ""
} |
q15089 | Rabl.Engine.collection | train | def collection(data, options = {})
@_collection_name = options[:root] if options[:root]
@_collection_name ||= data.values.first if data.is_a?(Hash)
@_object_root_name = options[:object_root] if options.has_key?(:object_root)
object(data_object(data) || [])
end | ruby | {
"resource": ""
} |
q15090 | Rabl.Engine.default_object | train | def default_object
return unless context_scope.respond_to?(:controller)
controller_name = context_scope.controller.controller_name
stripped_name = controller_name.split(%r{::|\/}).last
ivar_object = instance_variable_get("@#{stripped_name}")
ivar_object if is_object?(ivar_object)
end | ruby | {
"resource": ""
} |
q15091 | Rabl.Engine.request_format | train | def request_format
format = request_params[:format]
if format.nil? && context_scope.respond_to?(:request)
request = context_scope.request
format = request.format.to_sym.to_s if request.respond_to?(:format)
end
format = "json" unless format && respond_to?("to_#{format}")
format
end | ruby | {
"resource": ""
} |
q15092 | Rabl.Engine.method_missing | train | def method_missing(name, *args, &block)
context_scope.respond_to?(name, true) ? context_scope.__send__(name, *args, &block) : super
end | ruby | {
"resource": ""
} |
q15093 | Rabl.Sources.fetch_padrino_source | train | def fetch_padrino_source(file, options = {})
view_path = Array(options[:view_path] || context_scope.settings.views)
# use Padrino's own template resolution mechanism
file_path, _ = context_scope.instance_eval { resolve_template(file) }
# Padrino chops the extension, stitch it back on
File.join(view_path.first.to_s, (file_path.to_s + ".rabl"))
end | ruby | {
"resource": ""
} |
q15094 | Rabl.Sources.fetch_rails_source | train | def fetch_rails_source(file, options = {})
# use Rails template resolution mechanism if possible (find_template)
source_format = request_format if defined?(request_format)
if source_format && context_scope.respond_to?(:lookup_context) # Rails 3
lookup_proc = lambda do |partial|
if ActionPack::VERSION::MAJOR == 3 && ActionPack::VERSION::MINOR < 2
context_scope.lookup_context.find(file, [], partial)
else # Rails 3.2 and higher
# pull format directly from rails unless it is html
request_format = context_scope.request.format.to_sym
source_format = request_format unless request_format == :html
context_scope.lookup_context.find(file, [], partial, [], { :formats => [source_format] })
end
end
template = lookup_proc.call(false) rescue nil
template ||= lookup_proc.call(true) rescue nil
template.identifier if template
elsif source_format && context_scope.respond_to?(:view_paths) # Rails 2
template = context_scope.view_paths.find_template(file, source_format, false)
template.filename if template
end
end | ruby | {
"resource": ""
} |
q15095 | Rabl.Sources.fetch_sinatra_source | train | def fetch_sinatra_source(file, options = {})
view_path = Array(options[:view_path] || context_scope.settings.views)
fetch_manual_template(view_path, file)
end | ruby | {
"resource": ""
} |
q15096 | Rabl.Builder.child | train | def child(data, options = {}, &block)
return unless data.present? && resolve_condition(options)
name = is_name_value?(options[:root]) ? options[:root] : data_name(data)
object = data_object(data)
engine_options = @options.slice(:child_root)
engine_options[:root] = is_collection?(object) && options.fetch(:object_root, @options[:child_root]) # child @users
engine_options[:object_root_name] = options[:object_root] if is_name_value?(options[:object_root])
object = { object => name } if data.is_a?(Hash) && object # child :users => :people
engines << { create_key(name) => object_to_engine(object, engine_options, &block) }
end | ruby | {
"resource": ""
} |
q15097 | Rabl.Builder.glue | train | def glue(data, options = {}, &block)
return unless data.present? && resolve_condition(options)
object = data_object(data)
engine = object_to_engine(object, :root => false, &block)
engines << engine if engine
end | ruby | {
"resource": ""
} |
q15098 | Authorization.Engine.permit? | train | def permit? (privilege, options = {}) # :yields:
if permit!(privilege, options.merge(:bang=> false))
yield if block_given?
true
else
false
end
end | ruby | {
"resource": ""
} |
q15099 | Authorization.Engine.roles_for | train | def roles_for (user)
user ||= Authorization.current_user
raise AuthorizationUsageError, "User object doesn't respond to roles (#{user.inspect})" \
if !user.respond_to?(:role_symbols) and !user.respond_to?(:roles)
Rails.logger.info("The use of user.roles is deprecated. Please add a method " +
"role_symbols to your User model.") if defined?(Rails) and Rails.respond_to?(:logger) and !user.respond_to?(:role_symbols)
roles = user.respond_to?(:role_symbols) ? user.role_symbols : user.roles
raise AuthorizationUsageError, "User.#{user.respond_to?(:role_symbols) ? 'role_symbols' : 'roles'} " +
"doesn't return an Array of Symbols (#{roles.inspect})" \
if !roles.is_a?(Array) or (!roles.empty? and !roles[0].is_a?(Symbol))
(roles.empty? ? [Authorization.default_role] : roles)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.