_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q14800 | Daru.Vector.coerce_positions | train | def coerce_positions *positions
if positions.size == 1
case positions.first
when Integer
positions.first
when Range
size.times.to_a[positions.first]
else
raise ArgumentError, 'Unkown position type.'
end
else
positions
end
end | ruby | {
"resource": ""
} |
q14801 | Daru.DataFrame.row_at | train | def row_at *positions
original_positions = positions
positions = coerce_positions(*positions, nrows)
validate_positions(*positions, nrows)
if positions.is_a? Integer
row = get_rows_for([positions])
Daru::Vector.new row, index: @vectors
else
new_rows = get_rows_for(original_positions)
Daru::DataFrame.new new_rows, index: @index.at(*original_positions), order: @vectors
end
end | ruby | {
"resource": ""
} |
q14802 | Daru.DataFrame.set_row_at | train | def set_row_at positions, vector
validate_positions(*positions, nrows)
vector =
if vector.is_a? Daru::Vector
vector.reindex @vectors
else
Daru::Vector.new vector
end
raise SizeError, 'Vector length should match row length' if
vector.size != @vectors.size
@data.each_with_index do |vec, pos|
vec.set_at(positions, vector.at(pos))
end
@index = @data[0].index
set_size
end | ruby | {
"resource": ""
} |
q14803 | Daru.DataFrame.at | train | def at *positions
if AXES.include? positions.last
axis = positions.pop
return row_at(*positions) if axis == :row
end
original_positions = positions
positions = coerce_positions(*positions, ncols)
validate_positions(*positions, ncols)
if positions.is_a? Integer
@data[positions].dup
else
Daru::DataFrame.new positions.map { |pos| @data[pos].dup },
index: @index,
order: @vectors.at(*original_positions),
name: @name
end
end | ruby | {
"resource": ""
} |
q14804 | Daru.DataFrame.set_at | train | def set_at positions, vector
if positions.last == :row
positions.pop
return set_row_at(positions, vector)
end
validate_positions(*positions, ncols)
vector =
if vector.is_a? Daru::Vector
vector.reindex @index
else
Daru::Vector.new vector
end
raise SizeError, 'Vector length should match index length' if
vector.size != @index.size
positions.each { |pos| @data[pos] = vector }
end | ruby | {
"resource": ""
} |
q14805 | Daru.DataFrame.get_sub_dataframe | train | def get_sub_dataframe(keys, by_position: true)
return Daru::DataFrame.new({}) if keys == []
keys = @index.pos(*keys) unless by_position
sub_df = row_at(*keys)
sub_df = sub_df.to_df.transpose if sub_df.is_a?(Daru::Vector)
sub_df
end | ruby | {
"resource": ""
} |
q14806 | Daru.DataFrame.dup_only_valid | train | def dup_only_valid vecs=nil
rows_with_nil = @data.map { |vec| vec.indexes(*Daru::MISSING_VALUES) }
.inject(&:concat)
.uniq
row_indexes = @index.to_a
(vecs.nil? ? self : dup(vecs)).row[*(row_indexes - rows_with_nil)]
end | ruby | {
"resource": ""
} |
q14807 | Daru.DataFrame.reject_values | train | def reject_values(*values)
positions =
size.times.to_a - @data.flat_map { |vec| vec.positions(*values) }
# Handle the case when positions size is 1 and #row_at wouldn't return a df
if positions.size == 1
pos = positions.first
row_at(pos..pos)
else
row_at(*positions)
end
end | ruby | {
"resource": ""
} |
q14808 | Daru.DataFrame.uniq | train | def uniq(*vtrs)
vecs = vtrs.empty? ? vectors.to_a : Array(vtrs)
grouped = group_by(vecs)
indexes = grouped.groups.values.map { |v| v[0] }.sort
row[*indexes]
end | ruby | {
"resource": ""
} |
q14809 | Daru.DataFrame.collect_matrix | train | def collect_matrix
return to_enum(:collect_matrix) unless block_given?
vecs = vectors.to_a
rows = vecs.collect { |row|
vecs.collect { |col|
yield row,col
}
}
Matrix.rows(rows)
end | ruby | {
"resource": ""
} |
q14810 | Daru.DataFrame.delete_row | train | def delete_row index
idx = named_index_for index
raise IndexError, "Index #{index} does not exist." unless @index.include? idx
@index = Daru::Index.new(@index.to_a - [idx])
each_vector do |vector|
vector.delete_at idx
end
set_size
end | ruby | {
"resource": ""
} |
q14811 | Daru.DataFrame.bootstrap | train | def bootstrap(n=nil)
n ||= nrows
Daru::DataFrame.new({}, order: @vectors).tap do |df_boot|
n.times do
df_boot.add_row(row[rand(n)])
end
df_boot.update
end
end | ruby | {
"resource": ""
} |
q14812 | Daru.DataFrame.filter_vector | train | def filter_vector vec, &block
Daru::Vector.new(each_row.select(&block).map { |row| row[vec] })
end | ruby | {
"resource": ""
} |
q14813 | Daru.DataFrame.filter_rows | train | def filter_rows
return to_enum(:filter_rows) unless block_given?
keep_rows = @index.map { |index| yield access_row(index) }
where keep_rows
end | ruby | {
"resource": ""
} |
q14814 | Daru.DataFrame.filter_vectors | train | def filter_vectors &block
return to_enum(:filter_vectors) unless block_given?
dup.tap { |df| df.keep_vector_if(&block) }
end | ruby | {
"resource": ""
} |
q14815 | Daru.DataFrame.order= | train | def order=(order_array)
raise ArgumentError, 'Invalid order' unless
order_array.sort == vectors.to_a.sort
initialize(to_h, order: order_array)
end | ruby | {
"resource": ""
} |
q14816 | Daru.DataFrame.missing_values_rows | train | def missing_values_rows missing_values=[nil]
number_of_missing = each_row.map do |row|
row.indexes(*missing_values).size
end
Daru::Vector.new number_of_missing, index: @index, name: "#{@name}_missing_rows"
end | ruby | {
"resource": ""
} |
q14817 | Daru.DataFrame.nest | train | def nest *tree_keys, &_block
tree_keys = tree_keys[0] if tree_keys[0].is_a? Array
each_row.each_with_object({}) do |row, current|
# Create tree
*keys, last = tree_keys
current = keys.inject(current) { |c, f| c[row[f]] ||= {} }
name = row[last]
if block_given?
current[name] = yield(row, current, name)
else
current[name] ||= []
current[name].push(row.to_h.delete_if { |key,_value| tree_keys.include? key })
end
end
end | ruby | {
"resource": ""
} |
q14818 | Daru.DataFrame.vector_mean | train | def vector_mean max_missing=0
# FIXME: in vector_sum we preserve created vector dtype, but
# here we are not. Is this by design or ...? - zverok, 2016-05-18
mean_vec = Daru::Vector.new [0]*@size, index: @index, name: "mean_#{@name}"
each_row_with_index.each_with_object(mean_vec) do |(row, i), memo|
memo[i] = row.indexes(*Daru::MISSING_VALUES).size > max_missing ? nil : row.mean
end
end | ruby | {
"resource": ""
} |
q14819 | Daru.DataFrame.concat | train | def concat other_df
vectors = (@vectors.to_a + other_df.vectors.to_a).uniq
data = vectors.map do |v|
get_vector_anyways(v).dup.concat(other_df.get_vector_anyways(v))
end
Daru::DataFrame.new(data, order: vectors)
end | ruby | {
"resource": ""
} |
q14820 | Daru.DataFrame.set_index | train | def set_index new_index_col, opts={}
if new_index_col.respond_to?(:to_a)
strategy = SetMultiIndexStrategy
new_index_col = new_index_col.to_a
else
strategy = SetSingleIndexStrategy
end
uniq_size = strategy.uniq_size(self, new_index_col)
raise ArgumentError, 'All elements in new index must be unique.' if
@size != uniq_size
self.index = strategy.new_index(self, new_index_col)
strategy.delete_vector(self, new_index_col) unless opts[:keep]
self
end | ruby | {
"resource": ""
} |
q14821 | Daru.DataFrame.rename_vectors | train | def rename_vectors name_map
existing_targets = name_map.reject { |k,v| k == v }.values & vectors.to_a
delete_vectors(*existing_targets)
new_names = vectors.to_a.map { |v| name_map[v] ? name_map[v] : v }
self.vectors = Daru::Index.new new_names
end | ruby | {
"resource": ""
} |
q14822 | Daru.DataFrame.summary | train | def summary
summary = "= #{name}"
summary << "\n Number of rows: #{nrows}"
@vectors.each do |v|
summary << "\n Element:[#{v}]\n"
summary << self[v].summary(1)
end
summary
end | ruby | {
"resource": ""
} |
q14823 | Daru.DataFrame.pivot_table | train | def pivot_table opts={}
raise ArgumentError, 'Specify grouping index' if Array(opts[:index]).empty?
index = opts[:index]
vectors = opts[:vectors] || []
aggregate_function = opts[:agg] || :mean
values = prepare_pivot_values index, vectors, opts
raise IndexError, 'No numeric vectors to aggregate' if values.empty?
grouped = group_by(index)
return grouped.send(aggregate_function) if vectors.empty?
super_hash = make_pivot_hash grouped, vectors, values, aggregate_function
pivot_dataframe super_hash
end | ruby | {
"resource": ""
} |
q14824 | Daru.DataFrame.one_to_many | train | def one_to_many(parent_fields, pattern)
vars, numbers = one_to_many_components(pattern)
DataFrame.new([], order: [*parent_fields, '_col_id', *vars]).tap do |ds|
each_row do |row|
verbatim = parent_fields.map { |f| [f, row[f]] }.to_h
numbers.each do |n|
generated = one_to_many_row row, n, vars, pattern
next if generated.values.all?(&:nil?)
ds.add_row(verbatim.merge(generated).merge('_col_id' => n))
end
end
ds.update
end
end | ruby | {
"resource": ""
} |
q14825 | Daru.DataFrame.create_sql | train | def create_sql(table,charset='UTF8')
sql = "CREATE TABLE #{table} ("
fields = vectors.to_a.collect do |f|
v = self[f]
f.to_s + ' ' + v.db_type
end
sql + fields.join(",\n ")+") CHARACTER SET=#{charset};"
end | ruby | {
"resource": ""
} |
q14826 | Daru.DataFrame.to_html | train | def to_html(threshold=30)
table_thead = to_html_thead
table_tbody = to_html_tbody(threshold)
path = if index.is_a?(MultiIndex)
File.expand_path('../iruby/templates/dataframe_mi.html.erb', __FILE__)
else
File.expand_path('../iruby/templates/dataframe.html.erb', __FILE__)
end
ERB.new(File.read(path).strip).result(binding)
end | ruby | {
"resource": ""
} |
q14827 | Daru.DataFrame.transpose | train | def transpose
Daru::DataFrame.new(
each_vector.map(&:to_a).transpose,
index: @vectors,
order: @index,
dtype: @dtype,
name: @name
)
end | ruby | {
"resource": ""
} |
q14828 | Daru.DataFrame.aggregate | train | def aggregate(options={}, multi_index_level=-1)
if block_given?
positions_tuples, new_index = yield(@index) # note: use of yield is private for now
else
positions_tuples, new_index = group_index_for_aggregation(@index, multi_index_level)
end
colmn_value = aggregate_by_positions_tuples(options, positions_tuples)
Daru::DataFrame.new(colmn_value, index: new_index, order: options.keys)
end | ruby | {
"resource": ""
} |
q14829 | Daru.DataFrame.validate_positions | train | def validate_positions *positions, size
positions.each do |pos|
raise IndexError, "#{pos} is not a valid position." if pos >= size
end
end | ruby | {
"resource": ""
} |
q14830 | Daru.DataFrame.coerce_vector | train | def coerce_vector vector
case vector
when Daru::Vector
vector.reindex @vectors
when Hash
Daru::Vector.new(vector).reindex @vectors
else
Daru::Vector.new vector
end
end | ruby | {
"resource": ""
} |
q14831 | Daru.Index.valid? | train | def valid? *indexes
indexes.all? { |i| to_a.include?(i) || (i.is_a?(Numeric) && i < size) }
end | ruby | {
"resource": ""
} |
q14832 | Daru.Index.sort | train | def sort opts={}
opts = {ascending: true}.merge(opts)
new_index = @keys.sort
new_index = new_index.reverse unless opts[:ascending]
self.class.new(new_index)
end | ruby | {
"resource": ""
} |
q14833 | Daru.DateTimeIndex.[] | train | def [] *key
return slice(*key) if key.size != 1
key = key[0]
case key
when Numeric
key
when DateTime
Helper.find_index_of_date(@data, key)
when Range
# FIXME: get_by_range is suspiciously close to just #slice,
# but one of specs fails when replacing it with just slice
get_by_range(key.first, key.last)
else
raise ArgumentError, "Key #{key} is out of bounds" if
Helper.key_out_of_bounds?(key, @data)
slice(*Helper.find_date_string_bounds(key))
end
end | ruby | {
"resource": ""
} |
q14834 | Daru.DateTimeIndex.slice | train | def slice first, last
if first.is_a?(Integer) && last.is_a?(Integer)
DateTimeIndex.new(to_a[first..last], freq: @offset)
else
first = Helper.find_date_string_bounds(first)[0] if first.is_a?(String)
last = Helper.find_date_string_bounds(last)[1] if last.is_a?(String)
slice_between_dates first, last
end
end | ruby | {
"resource": ""
} |
q14835 | Daru.DateTimeIndex.shift | train | def shift distance
distance.is_a?(Integer) && distance < 0 and
raise IndexError, "Distance #{distance} cannot be negative"
_shift(distance)
end | ruby | {
"resource": ""
} |
q14836 | Daru.DateTimeIndex.lag | train | def lag distance
distance.is_a?(Integer) && distance < 0 and
raise IndexError, "Distance #{distance} cannot be negative"
_shift(-distance)
end | ruby | {
"resource": ""
} |
q14837 | Daru.DateTimeIndex.include? | train | def include? date_time
return false unless date_time.is_a?(String) || date_time.is_a?(DateTime)
if date_time.is_a?(String)
date_precision = Helper.determine_date_precision_of date_time
date_time = Helper.date_time_from date_time, date_precision
end
result, = @data.bsearch { |d| d[0] >= date_time }
result && result == date_time
end | ruby | {
"resource": ""
} |
q14838 | Daru.Category.initialize_category | train | def initialize_category data, opts={}
@type = :category
initialize_core_attributes data
if opts[:categories]
validate_categories(opts[:categories])
add_extra_categories(opts[:categories] - categories)
order_with opts[:categories]
end
# Specify if the categories are ordered or not.
# By default its unordered
@ordered = opts[:ordered] || false
# The coding scheme to code with. Default is dummy coding.
@coding_scheme = :dummy
# Base category which won't be present in the coding
@base_category = @cat_hash.keys.first
# Stores the name of the vector
@name = opts[:name]
# Index of the vector
@index = coerce_index opts[:index]
self
end | ruby | {
"resource": ""
} |
q14839 | Daru.Category.count | train | def count category=UNDEFINED
return @cat_hash.values.map(&:size).inject(&:+) if category == UNDEFINED # count all
raise ArgumentError, "Invalid category #{category}" unless
categories.include?(category)
@cat_hash[category].size
end | ruby | {
"resource": ""
} |
q14840 | Daru.Category.at | train | def at *positions
original_positions = positions
positions = coerce_positions(*positions)
validate_positions(*positions)
return category_from_position(positions) if positions.is_a? Integer
Daru::Vector.new positions.map { |pos| category_from_position(pos) },
index: @index.at(*original_positions),
name: @name,
type: :category,
ordered: @ordered,
categories: categories
end | ruby | {
"resource": ""
} |
q14841 | Daru.Category.set_at | train | def set_at positions, val
validate_positions(*positions)
positions.map { |pos| modify_category_at pos, val }
self
end | ruby | {
"resource": ""
} |
q14842 | Daru.Category.rename_categories | train | def rename_categories old_to_new
old_categories = categories
data = to_a.map do |cat|
old_to_new.include?(cat) ? old_to_new[cat] : cat
end
initialize_core_attributes data
self.categories = (old_categories - old_to_new.keys) | old_to_new.values
self.base_category = old_to_new[base_category] if
old_to_new.include? base_category
self
end | ruby | {
"resource": ""
} |
q14843 | Daru.Category.remove_unused_categories | train | def remove_unused_categories
old_categories = categories
initialize_core_attributes to_a
self.categories = old_categories & categories
self.base_category = @cat_hash.keys.first unless
categories.include? base_category
self
end | ruby | {
"resource": ""
} |
q14844 | Daru.Category.sort! | train | def sort! # rubocop:disable Metrics/AbcSize
# TODO: Simply the code
assert_ordered :sort
# Build sorted index
old_index = @index.to_a
new_index = @cat_hash.values.map do |positions|
old_index.values_at(*positions)
end.flatten
@index = @index.class.new new_index
# Build sorted data
@cat_hash = categories.inject([{}, 0]) do |acc, cat|
hash, count = acc
cat_count = @cat_hash[cat].size
cat_count.times { |i| @array[count+i] = int_from_cat(cat) }
hash[cat] = (count...(cat_count+count)).to_a
[hash, count + cat_count]
end.first
self
end | ruby | {
"resource": ""
} |
q14845 | Daru.Category.reindex! | train | def reindex! idx
idx = Daru::Index.new idx unless idx.is_a? Daru::Index
raise ArgumentError, 'Invalid index specified' unless
idx.to_a.sort == index.to_a.sort
old_categories = categories
data = idx.map { |i| self[i] }
initialize_core_attributes data
self.categories = old_categories
self.index = idx
self
end | ruby | {
"resource": ""
} |
q14846 | Daru.Category.count_values | train | def count_values(*values)
values.map { |v| @cat_hash[v].size if @cat_hash.include? v }
.compact
.inject(0, :+)
end | ruby | {
"resource": ""
} |
q14847 | Daru.Category.indexes | train | def indexes(*values)
values &= categories
index.to_a.values_at(*values.flat_map { |v| @cat_hash[v] }.sort)
end | ruby | {
"resource": ""
} |
q14848 | YARD.Logger.progress | train | def progress(msg, nontty_log = :debug)
send(nontty_log, msg) if nontty_log
return unless show_progress
icon = ""
if defined?(::Encoding)
icon = PROGRESS_INDICATORS[@progress_indicator] + " "
end
@mutex.synchronize do
print("\e[2K\e[?25l\e[1m#{icon}#{msg}\e[0m\r")
@progress_msg = msg
if Time.now - @progress_last_update > 0.2
@progress_indicator += 1
@progress_indicator %= PROGRESS_INDICATORS.size
@progress_last_update = Time.now
end
end
Thread.new do
sleep(0.05)
progress(msg + ".", nil) if @progress_msg == msg
end
end | ruby | {
"resource": ""
} |
q14849 | YARD.Logger.backtrace | train | def backtrace(exc, level_meth = :error)
return unless show_backtraces
send(level_meth, "#{exc.class.class_name}: #{exc.message}")
send(level_meth, "Stack trace:" +
exc.backtrace[0..5].map {|x| "\n\t#{x}" }.join + "\n")
end | ruby | {
"resource": ""
} |
q14850 | YARD.DocstringParser.tag_is_directive? | train | def tag_is_directive?(tag_name)
list = %w(attribute endgroup group macro method scope visibility)
list.include?(tag_name)
end | ruby | {
"resource": ""
} |
q14851 | YARD.Verifier.call | train | def call(object)
return true if object.is_a?(CodeObjects::Proxy)
modify_nilclass
@object = object
retval = __execute ? true : false
unmodify_nilclass
retval
end | ruby | {
"resource": ""
} |
q14852 | YARD::CodeObjects.ClassObject.inheritance_tree | train | def inheritance_tree(include_mods = false)
list = (include_mods ? mixins(:instance, :class) : [])
if superclass.is_a?(Proxy) || superclass.respond_to?(:inheritance_tree)
list += [superclass] unless superclass == P(:Object) || superclass == P(:BasicObject)
end
[self] + list.map do |m|
next m if m == self
next m unless m.respond_to?(:inheritance_tree)
m.inheritance_tree(include_mods)
end.flatten.uniq
end | ruby | {
"resource": ""
} |
q14853 | YARD::CodeObjects.ClassObject.meths | train | def meths(opts = {})
opts = SymbolHash[:inherited => true].update(opts)
list = super(opts)
list += inherited_meths(opts).reject do |o|
next(false) if opts[:all]
list.find {|o2| o2.name == o.name && o2.scope == o.scope }
end if opts[:inherited]
list
end | ruby | {
"resource": ""
} |
q14854 | YARD::CodeObjects.ClassObject.inherited_meths | train | def inherited_meths(opts = {})
inheritance_tree[1..-1].inject([]) do |list, superclass|
if superclass.is_a?(Proxy)
list
else
list += superclass.meths(opts).reject do |o|
next(false) if opts[:all]
child(:name => o.name, :scope => o.scope) ||
list.find {|o2| o2.name == o.name && o2.scope == o.scope }
end
end
end
end | ruby | {
"resource": ""
} |
q14855 | YARD::CodeObjects.ClassObject.constants | train | def constants(opts = {})
opts = SymbolHash[:inherited => true].update(opts)
super(opts) + (opts[:inherited] ? inherited_constants : [])
end | ruby | {
"resource": ""
} |
q14856 | YARD::CodeObjects.ClassObject.inherited_constants | train | def inherited_constants
inheritance_tree[1..-1].inject([]) do |list, superclass|
if superclass.is_a?(Proxy)
list
else
list += superclass.constants.reject do |o|
child(:name => o.name) || list.find {|o2| o2.name == o.name }
end
end
end
end | ruby | {
"resource": ""
} |
q14857 | YARD::CodeObjects.ClassObject.superclass= | train | def superclass=(object)
case object
when Base, Proxy, NilClass
@superclass = object
when String, Symbol
@superclass = Proxy.new(namespace, object)
else
raise ArgumentError, "superclass must be CodeObject, Proxy, String or Symbol"
end
if name == @superclass.name && namespace != YARD::Registry.root && !object.is_a?(Base)
@superclass = Proxy.new(namespace.namespace, object)
end
if @superclass == self
msg = "superclass #{@superclass.inspect} cannot be the same as the declared class #{inspect}"
@superclass = P("::Object")
raise ArgumentError, msg
end
end | ruby | {
"resource": ""
} |
q14858 | YARD.RegistryResolver.collect_namespaces | train | def collect_namespaces(object)
return [] unless object.respond_to?(:inheritance_tree)
nss = object.inheritance_tree(true)
if object.respond_to?(:superclass)
nss |= [P('Object')] if object.superclass != P('BasicObject')
nss |= [P('BasicObject')]
end
nss
end | ruby | {
"resource": ""
} |
q14859 | YARD.Options.update | train | def update(opts)
opts = opts.to_hash if Options === opts
opts.each do |key, value|
self[key] = value
end
self
end | ruby | {
"resource": ""
} |
q14860 | YARD.Options.each | train | def each
instance_variables.each do |ivar|
name = ivar.to_s.sub(/^@/, '')
yield(name.to_sym, send(name))
end
end | ruby | {
"resource": ""
} |
q14861 | YARD.Options.reset_defaults | train | def reset_defaults
names_set = {}
self.class.ancestors.each do |klass| # look at all ancestors
defaults =
klass.instance_variable_defined?("@defaults") &&
klass.instance_variable_get("@defaults")
next unless defaults
defaults.each do |key, value|
next if names_set[key]
names_set[key] = true
self[key] = Proc === value ? value.call : value
end
end
end | ruby | {
"resource": ""
} |
q14862 | YARD::Templates::Helpers.BaseHelper.link_object | train | def link_object(obj, title = nil)
return title if title
case obj
when YARD::CodeObjects::Base, YARD::CodeObjects::Proxy
obj.title
when String, Symbol
P(obj).title
else
obj
end
end | ruby | {
"resource": ""
} |
q14863 | YARD::Templates::Helpers.BaseHelper.link_file | train | def link_file(filename, title = nil, anchor = nil) # rubocop:disable Lint/UnusedMethodArgument
return filename.filename if CodeObjects::ExtraFileObject === filename
filename
end | ruby | {
"resource": ""
} |
q14864 | YARD.RubygemsHook.setup | train | def setup
self.class.load_yard
if File.exist?(@doc_dir)
raise Gem::FilePermissionError, @doc_dir unless File.writable?(@doc_dir)
else
FileUtils.mkdir_p @doc_dir
end
end | ruby | {
"resource": ""
} |
q14865 | YARD::CodeObjects.MethodObject.scope= | train | def scope=(v)
reregister = @scope ? true : false
# handle module function
if v == :module
other = self.class.new(namespace, name)
other.visibility = :private
@visibility = :public
@module_function = true
@path = nil
end
YARD::Registry.delete(self)
@path = nil
@scope = v.to_sym
@scope = :class if @scope == :module
YARD::Registry.register(self) if reregister
end | ruby | {
"resource": ""
} |
q14866 | YARD::CodeObjects.MethodObject.is_attribute? | train | def is_attribute?
info = attr_info
if info
read_or_write = name.to_s =~ /=$/ ? :write : :read
info[read_or_write] ? true : false
else
false
end
end | ruby | {
"resource": ""
} |
q14867 | YARD::CodeObjects.MethodObject.sep | train | def sep
if scope == :class
namespace && namespace != YARD::Registry.root ? CSEP : NSEP
else
ISEP
end
end | ruby | {
"resource": ""
} |
q14868 | YARD.RegistryStore.put | train | def put(key, value)
if key == ''
@object_types[:root] = [:root]
@store[:root] = value
else
@notfound.delete(key.to_sym)
(@object_types[value.type] ||= []) << key.to_s
if @store[key.to_sym]
@object_types[@store[key.to_sym].type].delete(key.to_s)
end
@store[key.to_sym] = value
end
end | ruby | {
"resource": ""
} |
q14869 | YARD.RegistryStore.load_all | train | def load_all
return unless @file
return if @loaded_objects >= @available_objects
log.debug "Loading entire database: #{@file} ..."
objects = []
all_disk_objects.sort_by(&:size).each do |path|
obj = @serializer.deserialize(path, true)
objects << obj if obj
end
objects.each do |obj|
put(obj.path, obj)
end
@loaded_objects += objects.size
log.debug "Loaded database (file='#{@file}' count=#{objects.size} total=#{@available_objects})"
end | ruby | {
"resource": ""
} |
q14870 | YARD.RegistryStore.save | train | def save(merge = true, file = nil)
if file && file != @file
@file = file
@serializer = Serializers::YardocSerializer.new(@file)
end
destroy unless merge
sdb = Registry.single_object_db
if sdb == true || sdb.nil?
@serializer.serialize(@store)
else
values(false).each do |object|
@serializer.serialize(object)
end
end
write_proxy_types
write_object_types
write_checksums
write_complete_lock
true
end | ruby | {
"resource": ""
} |
q14871 | YARD.RegistryStore.destroy | train | def destroy(force = false)
if (!force && file =~ /\.yardoc$/) || force
if File.file?(@file)
# Handle silent upgrade of old .yardoc format
File.unlink(@file)
elsif File.directory?(@file)
FileUtils.rm_rf(@file)
end
true
else
false
end
end | ruby | {
"resource": ""
} |
q14872 | YARD.Docstring.summary | train | def summary
resolve_reference
return @summary if defined?(@summary) && @summary
stripped = gsub(/[\r\n](?![\r\n])/, ' ').strip
num_parens = 0
idx = length.times do |index|
case stripped[index, 1]
when "."
next_char = stripped[index + 1, 1].to_s
break index - 1 if num_parens <= 0 && next_char =~ /^\s*$/
when "\r", "\n"
next_char = stripped[index + 1, 1].to_s
if next_char =~ /^\s*$/
break stripped[index - 1, 1] == '.' ? index - 2 : index - 1
end
when "{", "(", "["
num_parens += 1
when "}", ")", "]"
num_parens -= 1
end
end
@summary = stripped[0..idx]
if !@summary.empty? && @summary !~ /\A\s*\{include:.+\}\s*\Z/
@summary += '.'
end
@summary
end | ruby | {
"resource": ""
} |
q14873 | YARD.Docstring.to_raw | train | def to_raw
tag_data = tags.map do |tag|
case tag
when Tags::OverloadTag
tag_text = "@#{tag.tag_name} #{tag.signature}\n"
unless tag.docstring.blank?
tag_text += "\n " + tag.docstring.all.gsub(/\r?\n/, "\n ")
end
when Tags::OptionTag
tag_text = "@#{tag.tag_name} #{tag.name}"
tag_text += ' [' + tag.pair.types.join(', ') + ']' if tag.pair.types
tag_text += ' ' + tag.pair.name.to_s if tag.pair.name
tag_text += "\n " if tag.name && tag.text
tag_text += ' (' + tag.pair.defaults.join(', ') + ')' if tag.pair.defaults
tag_text += " " + tag.pair.text.strip.gsub(/\n/, "\n ") if tag.pair.text
else
tag_text = '@' + tag.tag_name
tag_text += ' [' + tag.types.join(', ') + ']' if tag.types
tag_text += ' ' + tag.name.to_s if tag.name
tag_text += "\n " if tag.name && tag.text
tag_text += ' ' + tag.text.strip.gsub(/\n/, "\n ") if tag.text
end
tag_text
end
[strip, tag_data.join("\n")].reject(&:empty?).compact.join("\n")
end | ruby | {
"resource": ""
} |
q14874 | YARD.Docstring.tag | train | def tag(name)
tags.find {|tag| tag.tag_name.to_s == name.to_s }
end | ruby | {
"resource": ""
} |
q14875 | YARD.Docstring.tags | train | def tags(name = nil)
list = stable_sort_by(@tags + convert_ref_tags, &:tag_name)
return list unless name
list.select {|tag| tag.tag_name.to_s == name.to_s }
end | ruby | {
"resource": ""
} |
q14876 | YARD.Docstring.has_tag? | train | def has_tag?(name)
tags.any? {|tag| tag.tag_name.to_s == name.to_s }
end | ruby | {
"resource": ""
} |
q14877 | YARD.Docstring.blank? | train | def blank?(only_visible_tags = true)
if only_visible_tags
empty? && !tags.any? {|tag| Tags::Library.visible_tags.include?(tag.tag_name.to_sym) }
else
empty? && @tags.empty? && @ref_tags.empty?
end
end | ruby | {
"resource": ""
} |
q14878 | YARD.Docstring.convert_ref_tags | train | def convert_ref_tags
list = @ref_tags.reject {|t| CodeObjects::Proxy === t.owner }
@ref_tag_recurse_count ||= 0
@ref_tag_recurse_count += 1
if @ref_tag_recurse_count > 2
log.error "#{@object.file}:#{@object.line}: Detected circular reference tag in " \
"`#{@object}', ignoring all reference tags for this object " \
"(#{@ref_tags.map {|t| "@#{t.tag_name}" }.join(", ")})."
@ref_tags = []
return @ref_tags
end
list = list.map(&:tags).flatten
@ref_tag_recurse_count -= 1
list
end | ruby | {
"resource": ""
} |
q14879 | YARD.Docstring.parse_comments | train | def parse_comments(comments)
parser = self.class.parser
parser.parse(comments, object)
@all = parser.raw_text
@unresolved_reference = parser.reference
add_tag(*parser.tags)
parser.text
end | ruby | {
"resource": ""
} |
q14880 | YARD.Docstring.stable_sort_by | train | def stable_sort_by(list)
list.each_with_index.sort_by {|tag, i| [yield(tag), i] }.map(&:first)
end | ruby | {
"resource": ""
} |
q14881 | YARD::CodeObjects.ModuleObject.inheritance_tree | train | def inheritance_tree(include_mods = false)
return [self] unless include_mods
[self] + mixins(:instance, :class).map do |m|
next if m == self
next m unless m.respond_to?(:inheritance_tree)
m.inheritance_tree(true)
end.compact.flatten.uniq
end | ruby | {
"resource": ""
} |
q14882 | YARD::CodeObjects.NamespaceObject.child | train | def child(opts = {})
if !opts.is_a?(Hash)
children.find {|o| o.name == opts.to_sym }
else
opts = SymbolHash[opts]
children.find do |obj|
opts.each do |meth, value|
break false unless value.is_a?(Array) ? value.include?(obj[meth]) : obj[meth] == value
end
end
end
end | ruby | {
"resource": ""
} |
q14883 | YARD::CodeObjects.NamespaceObject.meths | train | def meths(opts = {})
opts = SymbolHash[
:visibility => [:public, :private, :protected],
:scope => [:class, :instance],
:included => true
].update(opts)
opts[:visibility] = [opts[:visibility]].flatten
opts[:scope] = [opts[:scope]].flatten
ourmeths = children.select do |o|
o.is_a?(MethodObject) &&
opts[:visibility].include?(o.visibility) &&
opts[:scope].include?(o.scope)
end
ourmeths + (opts[:included] ? included_meths(opts) : [])
end | ruby | {
"resource": ""
} |
q14884 | YARD::CodeObjects.NamespaceObject.included_meths | train | def included_meths(opts = {})
opts = SymbolHash[:scope => [:instance, :class]].update(opts)
[opts[:scope]].flatten.map do |scope|
mixins(scope).inject([]) do |list, mixin|
next list if mixin.is_a?(Proxy)
arr = mixin.meths(opts.merge(:scope => :instance)).reject do |o|
next false if opts[:all]
child(:name => o.name, :scope => scope) || list.find {|o2| o2.name == o.name }
end
arr.map! {|o| ExtendedMethodObject.new(o) } if scope == :class
list + arr
end
end.flatten
end | ruby | {
"resource": ""
} |
q14885 | YARD::CodeObjects.NamespaceObject.constants | train | def constants(opts = {})
opts = SymbolHash[:included => true].update(opts)
consts = children.select {|o| o.is_a? ConstantObject }
consts + (opts[:included] ? included_constants : [])
end | ruby | {
"resource": ""
} |
q14886 | YARD::CodeObjects.NamespaceObject.included_constants | train | def included_constants
instance_mixins.inject([]) do |list, mixin|
if mixin.respond_to? :constants
list += mixin.constants.reject do |o|
child(:name => o.name) || list.find {|o2| o2.name == o.name }
end
else
list
end
end
end | ruby | {
"resource": ""
} |
q14887 | Idb.CAInterface.remove_cert | train | def remove_cert(cert)
der = cert.to_der
query = %(DELETE FROM "tsettings" WHERE sha1 = #{blobify(sha1_from_der(der))};)
begin
db = SQLite3::Database.new(@db_path)
db.execute(query)
db.close
rescue StandardError => e
raise "[*] Error writing to SQLite database at #{@db_path}: #{e.message}"
end
end | ruby | {
"resource": ""
} |
q14888 | Impressionist.Impressionable.impressionist_count | train | def impressionist_count(options={})
# Uses these options as defaults unless overridden in options hash
options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
# If a start_date is provided, finds impressions between then and the end_date. Otherwise returns all impressions
imps = options[:start_date].blank? ? impressions : impressions.where("created_at >= ? and created_at <= ?", options[:start_date], options[:end_date])
if options[:message]
imps = imps.where("impressions.message = ?", options[:message])
end
# Count all distinct impressions unless the :all filter is provided.
distinct = options[:filter] != :all
if Rails::VERSION::MAJOR >= 4
distinct ? imps.select(options[:filter]).distinct.count : imps.count
else
distinct ? imps.count(options[:filter], :distinct => true) : imps.count
end
end | ruby | {
"resource": ""
} |
q14889 | Impressionist.Impressionable.impressionist_count | train | def impressionist_count(options={})
# Uses these options as defaults unless overridden in options hash
options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
# If a start_date is provided, finds impressions between then and the end_date.
# Otherwise returns all impressions
imps = options[:start_date].blank? ? impressions :
impressions.between(created_at: options[:start_date]..options[:end_date])
# Count all distinct impressions unless the :all filter is provided
distinct = options[:filter] != :all
distinct ? imps.where(options[:filter].ne => nil).distinct(options[:filter]).count : imps.count
end | ruby | {
"resource": ""
} |
q14890 | ImpressionistController.InstanceMethods.associative_create_statement | train | def associative_create_statement(query_params={})
filter = ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters)
query_params.reverse_merge!(
:controller_name => controller_name,
:action_name => action_name,
:user_id => user_id,
:request_hash => @impressionist_hash,
:session_hash => session_hash,
:ip_address => request.remote_ip,
:referrer => request.referer,
:params => filter.filter(params_hash)
)
end | ruby | {
"resource": ""
} |
q14891 | ImpressionistController.InstanceMethods.unique_query | train | def unique_query(unique_opts,impressionable=nil)
full_statement = direct_create_statement({},impressionable)
# reduce the full statement to the params we need for the specified unique options
unique_opts.reduce({}) do |query, param|
query[param] = full_statement[param]
query
end
end | ruby | {
"resource": ""
} |
q14892 | ImpressionistController.InstanceMethods.direct_create_statement | train | def direct_create_statement(query_params={},impressionable=nil)
query_params.reverse_merge!(
:impressionable_type => controller_name.singularize.camelize,
:impressionable_id => impressionable.present? ? impressionable.id : params[:id]
)
associative_create_statement(query_params)
end | ruby | {
"resource": ""
} |
q14893 | ApiAuth.Helpers.capitalize_keys | train | def capitalize_keys(hsh)
capitalized_hash = {}
hsh.each_pair { |k, v| capitalized_hash[k.to_s.upcase] = v }
capitalized_hash
end | ruby | {
"resource": ""
} |
q14894 | Gruf.Client.execute | train | def execute(call_sig, req, metadata, opts = {}, &block)
operation = nil
result = Gruf::Timer.time do
opts[:return_op] = true
opts[:metadata] = metadata
operation = send(call_sig, req, opts, &block)
operation.execute
end
[result, operation]
end | ruby | {
"resource": ""
} |
q14895 | Gruf.Client.request_object | train | def request_object(request_method, params = {})
desc = rpc_desc(request_method)
desc&.input ? desc.input.new(params) : nil
end | ruby | {
"resource": ""
} |
q14896 | Gruf.Client.build_metadata | train | def build_metadata(metadata = {})
unless opts[:password].empty?
username = opts.fetch(:username, 'grpc').to_s
username = username.empty? ? '' : "#{username}:"
auth_string = Base64.encode64("#{username}#{opts[:password]}")
metadata[:authorization] = "Basic #{auth_string}".tr("\n", '')
end
metadata
end | ruby | {
"resource": ""
} |
q14897 | Gruf.Helpers.build_operation | train | def build_operation(options = {})
double(:operation, {
execute: true,
metadata: {},
trailing_metadata: {},
deadline: Time.now.to_i + 600,
cancelled?: false,
execution_time: rand(1_000..10_000)
}.merge(options))
end | ruby | {
"resource": ""
} |
q14898 | Gruf.Helpers.run_server | train | def run_server(server)
grpc_server = server.server
t = Thread.new { grpc_server.run }
grpc_server.wait_till_running
begin
yield
ensure
grpc_server.stop
sleep(0.1) until grpc_server.stopped?
t.join
end
end | ruby | {
"resource": ""
} |
q14899 | Gruf.Error.add_field_error | train | def add_field_error(field_name, error_code, message = '')
@field_errors << Errors::Field.new(field_name, error_code, message)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.