_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q19300
Appsignal.Transaction.sanitized_environment
train
def sanitized_environment env = environment return if env.empty? {}.tap do |out| Appsignal.config[:request_headers].each do |key| out[key] = env[key] if env[key] end end end
ruby
{ "resource": "" }
q19301
Appsignal.Transaction.sanitized_session_data
train
def sanitized_session_data return if Appsignal.config[:skip_session_data] || !request.respond_to?(:session) session = request.session return unless session Appsignal::Utils::HashSanitizer.sanitize( session.to_hash, Appsignal.config[:filter_session_data] ) end
ruby
{ "resource": "" }
q19302
RedisAnalytics.Visit.for_each_time_range
train
def for_each_time_range(t) RedisAnalytics.redis_key_timestamps.map{|x, y| t.strftime(x)}.each do |ts| yield(ts) end end
ruby
{ "resource": "" }
q19303
RedisAnalytics.Visit.record
train
def record if @current_visit_seq track("visit_time", @t.to_i - @last_visit_end_time.to_i) else @current_visit_seq ||= counter("visits") track("visits", 1) # track core 'visit' metric if @first_visit_seq track("repeat_visits", 1) else @first_visit_seq ||= counter("unique_visits") track("first_visits", 1) track("unique_visits", 1) end exec_custom_methods('visit') # custom methods that are measured on a per-visit basis end exec_custom_methods('hit') # custom methods that are measured on a per-page-view (per-hit) basis track("page_views", 1) # track core 'page_view' metric track("second_page_views", 1) if @page_view_seq_no.to_i == 1 # @last_visit_start_time and (@last_visit_start_time.to_i == @last_visit_end_time.to_i) @rack_response end
ruby
{ "resource": "" }
q19304
VkontakteApi.Configuration.reset
train
def reset @adapter = DEFAULT_ADAPTER @http_verb = DEFAULT_HTTP_VERB @faraday_options = {} @max_retries = DEFAULT_MAX_RETRIES @logger = ::Logger.new(STDOUT) @log_requests = DEFAULT_LOGGER_OPTIONS[:requests] @log_errors = DEFAULT_LOGGER_OPTIONS[:errors] @log_responses = DEFAULT_LOGGER_OPTIONS[:responses] @api_version = nil end
ruby
{ "resource": "" }
q19305
VkontakteApi.Method.call
train
def call(args = {}, &block) response = API.call(full_name, args, token) Result.process(response, type, block) end
ruby
{ "resource": "" }
q19306
VkontakteApi.Authorization.authorization_url
train
def authorization_url(options = {}) type = options.delete(:type) || :site # redirect_uri passed in options overrides the global setting options[:redirect_uri] ||= VkontakteApi.redirect_uri options[:scope] = VkontakteApi::Utils.flatten_argument(options[:scope]) if options[:scope] case type when :site client.auth_code.authorize_url(options) when :client client.implicit.authorize_url(options) else raise ArgumentError, "Unknown authorization type #{type.inspect}" end end
ruby
{ "resource": "" }
q19307
Writexlsx.Chart.add_series
train
def add_series(params) # Check that the required input has been specified. unless params.has_key?(:values) raise "Must specify ':values' in add_series" end if @requires_category != 0 && !params.has_key?(:categories) raise "Must specify ':categories' in add_series for this chart type" end @series << Series.new(self, params) # Set the secondary axis properties. x2_axis = params[:x2_axis] y2_axis = params[:y2_axis] # Store secondary status for combined charts. if ptrue?(x2_axis) || ptrue?(y2_axis) @is_secondary = true end # Set the gap and overlap for Bar/Column charts. if params[:gap] if ptrue?(y2_axis) @series_gap_2 = params[:gap] else @series_gap_1 = params[:gap] end end # Set the overlap for Bar/Column charts. if params[:overlap] if ptrue?(y2_axis) @series_overlap_2 = params[:overlap] else @series_overlap_1 = params[:overlap] end end end
ruby
{ "resource": "" }
q19308
Writexlsx.Chart.set_size
train
def set_size(params = {}) @width = params[:width] if params[:width] @height = params[:height] if params[:height] @x_scale = params[:x_scale] if params[:x_scale] @y_scale = params[:y_scale] if params[:y_scale] @x_offset = params[:x_offset] if params[:x_offset] @y_offset = params[:y_offset] if params[:y_offset] end
ruby
{ "resource": "" }
q19309
Writexlsx.Chart.set_up_down_bars
train
def set_up_down_bars(params = {}) # Map border to line. [:up, :down].each do |up_down| if params[up_down] params[up_down][:line] = params[up_down][:border] if params[up_down][:border] else params[up_down] = {} end end # Set the up and down bar properties. @up_down_bars = { :_up => Chartline.new(params[:up]), :_down => Chartline.new(params[:down]) } end
ruby
{ "resource": "" }
q19310
Writexlsx.Chart.convert_font_args
train
def convert_font_args(params) return unless params font = params_to_font(params) # Convert font size units. font[:_size] *= 100 if font[:_size] && font[:_size] != 0 # Convert rotation into 60,000ths of a degree. if ptrue?(font[:_rotation]) font[:_rotation] = 60_000 * font[:_rotation].to_i end font end
ruby
{ "resource": "" }
q19311
Writexlsx.Chart.process_names
train
def process_names(name = nil, name_formula = nil) # :nodoc: # Name looks like a formula, use it to set name_formula. if name.respond_to?(:to_ary) cell = xl_rowcol_to_cell(name[1], name[2], 1, 1) name_formula = "#{quote_sheetname(name[0])}!#{cell}" name = '' elsif name && name =~ /^=[^!]+!\$/ name_formula = name name = '' end [name, name_formula] end
ruby
{ "resource": "" }
q19312
Writexlsx.Chart.get_data_type
train
def get_data_type(data) # :nodoc: # Check for no data in the series. return 'none' unless data return 'none' if data.empty? return 'multi_str' if data.first.kind_of?(Array) # If the token isn't a number assume it is a string. data.each do |token| next unless token return 'str' unless token.kind_of?(Numeric) end # The series data was all numeric. 'num' end
ruby
{ "resource": "" }
q19313
Writexlsx.Chart.color
train
def color(color_code) # :nodoc: if color_code and color_code =~ /^#[0-9a-fA-F]{6}$/ # Convert a HTML style #RRGGBB color. color_code.sub(/^#/, '').upcase else index = Format.color(color_code) raise "Unknown color '#{color_code}' used in chart formatting." unless index palette_color(index) end end
ruby
{ "resource": "" }
q19314
Writexlsx.Chart.get_font_style_attributes
train
def get_font_style_attributes(font) return [] unless font attributes = [] attributes << ['sz', font[:_size]] if ptrue?(font[:_size]) attributes << ['b', font[:_bold]] if font[:_bold] attributes << ['i', font[:_italic]] if font[:_italic] attributes << ['u', 'sng'] if font[:_underline] # Turn off baseline when testing fonts that don't have it. if font[:_baseline] != -1 attributes << ['baseline', font[:_baseline]] end attributes end
ruby
{ "resource": "" }
q19315
Writexlsx.Chart.get_font_latin_attributes
train
def get_font_latin_attributes(font) return [] unless font attributes = [] attributes << ['typeface', font[:_name]] if ptrue?(font[:_name]) attributes << ['pitchFamily', font[:_pitch_family]] if font[:_pitch_family] attributes << ['charset', font[:_charset]] if font[:_charset] attributes end
ruby
{ "resource": "" }
q19316
Writexlsx.Chart.write_series_name
train
def write_series_name(series) # :nodoc: if series.name_formula write_tx_formula(series.name_formula, series.name_id) elsif series.name write_tx_value(series.name) end end
ruby
{ "resource": "" }
q19317
Writexlsx.Chart.write_axis_font
train
def write_axis_font(font) # :nodoc: return unless font @writer.tag_elements('c:txPr') do write_a_body_pr(font[:_rotation]) write_a_lst_style @writer.tag_elements('a:p') do write_a_p_pr_rich(font) write_a_end_para_rpr end end end
ruby
{ "resource": "" }
q19318
Writexlsx.Chart.write_error_bars
train
def write_error_bars(error_bars) return unless ptrue?(error_bars) if error_bars[:_x_error_bars] write_err_bars('x', error_bars[:_x_error_bars]) end if error_bars[:_y_error_bars] write_err_bars('y', error_bars[:_y_error_bars]) end end
ruby
{ "resource": "" }
q19319
Writexlsx.Chart.write_custom_error
train
def write_custom_error(error_bars) if ptrue?(error_bars.plus_values) write_custom_error_base('c:plus', error_bars.plus_values, error_bars.plus_data) write_custom_error_base('c:minus', error_bars.minus_values, error_bars.minus_data) end end
ruby
{ "resource": "" }
q19320
Writexlsx.Worksheet.protect
train
def protect(password = nil, options = {}) check_parameter(options, protect_default_settings.keys, 'protect') @protect = protect_default_settings.merge(options) # Set the password after the user defined values. @protect[:password] = sprintf("%X", encode_password(password)) if password && password != '' end
ruby
{ "resource": "" }
q19321
Writexlsx.Worksheet.set_header
train
def set_header(string = '', margin = 0.3, options = {}) raise 'Header string must be less than 255 characters' if string.length >= 255 # Replace the Excel placeholder &[Picture] with the internal &G. @page_setup.header = string.gsub(/&\[Picture\]/, '&G') if string.size >= 255 raise 'Header string must be less than 255 characters' end if options[:align_with_margins] @page_setup.header_footer_aligns = options[:align_with_margins] end if options[:scale_with_doc] @page_setup.header_footer_scales = options[:scale_with_doc] end # Reset the array in case the function is called more than once. @header_images = [] [ [:image_left, 'LH'], [:image_center, 'CH'], [:image_right, 'RH'] ].each do |p| if options[p.first] @header_images << [options[p.first], p.last] end end # placeholeder /&G/ の数 placeholder_count = @page_setup.header.scan(/&G/).count image_count = @header_images.count if image_count != placeholder_count raise "Number of header image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.header}" end @has_header_vml = true if image_count > 0 @page_setup.margin_header = margin || 0.3 @page_setup.header_footer_changed = true end
ruby
{ "resource": "" }
q19322
Writexlsx.Worksheet.set_footer
train
def set_footer(string = '', margin = 0.3, options = {}) raise 'Footer string must be less than 255 characters' if string.length >= 255 @page_setup.footer = string.dup # Replace the Excel placeholder &[Picture] with the internal &G. @page_setup.footer = string.gsub(/&\[Picture\]/, '&G') if string.size >= 255 raise 'Header string must be less than 255 characters' end if options[:align_with_margins] @page_setup.header_footer_aligns = options[:align_with_margins] end if options[:scale_with_doc] @page_setup.header_footer_scales = options[:scale_with_doc] end # Reset the array in case the function is called more than once. @footer_images = [] [ [:image_left, 'LF'], [:image_center, 'CF'], [:image_right, 'RF'] ].each do |p| if options[p.first] @footer_images << [options[p.first], p.last] end end # placeholeder /&G/ の数 placeholder_count = @page_setup.footer.scan(/&G/).count image_count = @footer_images.count if image_count != placeholder_count raise "Number of footer image (#{image_count}) doesn't match placeholder count (#{placeholder_count}) in string: #{@page_setup.footer}" end @has_header_vml = true if image_count > 0 @page_setup.margin_footer = margin @page_setup.header_footer_changed = true end
ruby
{ "resource": "" }
q19323
Writexlsx.Worksheet.repeat_rows
train
def repeat_rows(row_min, row_max = nil) row_max ||= row_min # Convert to 1 based. row_min += 1 row_max += 1 area = "$#{row_min}:$#{row_max}" # Build up the print titles "Sheet1!$1:$2" sheetname = quote_sheetname(@name) @page_setup.repeat_rows = "#{sheetname}!#{area}" end
ruby
{ "resource": "" }
q19324
Writexlsx.Worksheet.print_across
train
def print_across(across = true) if across @page_setup.across = true @page_setup.page_setup_changed = true else @page_setup.across = false end end
ruby
{ "resource": "" }
q19325
Writexlsx.Worksheet.filter_column
train
def filter_column(col, expression) raise "Must call autofilter before filter_column" unless @autofilter_area col = prepare_filter_column(col) tokens = extract_filter_tokens(expression) unless tokens.size == 3 || tokens.size == 7 raise "Incorrect number of tokens in expression '#{expression}'" end tokens = parse_filter_expression(expression, tokens) # Excel handles single or double custom filters as default filters. We need # to check for them and handle them accordingly. if tokens.size == 2 && tokens[0] == 2 # Single equality. filter_column_list(col, tokens[1]) elsif tokens.size == 5 && tokens[0] == 2 && tokens[2] == 1 && tokens[3] == 2 # Double equality with "or" operator. filter_column_list(col, tokens[1], tokens[4]) else # Non default custom filter. @filter_cols[col] = Array.new(tokens) @filter_type[col] = 0 end @filter_on = 1 end
ruby
{ "resource": "" }
q19326
Writexlsx.Worksheet.filter_column_list
train
def filter_column_list(col, *tokens) tokens.flatten! raise "Incorrect number of arguments to filter_column_list" if tokens.empty? raise "Must call autofilter before filter_column_list" unless @autofilter_area col = prepare_filter_column(col) @filter_cols[col] = tokens @filter_type[col] = 1 # Default style. @filter_on = 1 end
ruby
{ "resource": "" }
q19327
Writexlsx.Worksheet.set_h_pagebreaks
train
def set_h_pagebreaks(*args) breaks = args.collect do |brk| Array(brk) end.flatten @page_setup.hbreaks += breaks end
ruby
{ "resource": "" }
q19328
Writexlsx.Worksheet.get_range_data
train
def get_range_data(row_start, col_start, row_end, col_end) # :nodoc: # TODO. Check for worksheet limits. # Iterate through the table data. data = [] (row_start .. row_end).each do |row_num| # Store nil if row doesn't exist. if !@cell_data_table[row_num] data << nil next end (col_start .. col_end).each do |col_num| if cell = @cell_data_table[row_num][col_num] data << cell.data else # Store nil if col doesn't exist. data << nil end end end return data end
ruby
{ "resource": "" }
q19329
Writexlsx.Worksheet.position_object_pixels
train
def position_object_pixels(col_start, row_start, x1, y1, width, height) #:nodoc: # Calculate the absolute x offset of the top-left vertex. if @col_size_changed x_abs = (0 .. col_start-1).inject(0) {|sum, col| sum += size_col(col)} else # Optimisation for when the column widths haven't changed. x_abs = @default_col_pixels * col_start end x_abs += x1 # Calculate the absolute y offset of the top-left vertex. # Store the column change to allow optimisations. if @row_size_changed y_abs = (0 .. row_start-1).inject(0) {|sum, row| sum += size_row(row)} else # Optimisation for when the row heights haven't changed. y_abs = @default_row_pixels * row_start end y_abs += y1 # Adjust start column for offsets that are greater than the col width. x1, col_start = adjust_column_offset(x1, col_start) # Adjust start row for offsets that are greater than the row height. y1, row_start = adjust_row_offset(y1, row_start) # Initialise end cell to the same as the start cell. col_end = col_start row_end = row_start width += x1 height += y1 # Subtract the underlying cell widths to find the end cell of the object. width, col_end = adjust_column_offset(width, col_end) # Subtract the underlying cell heights to find the end cell of the object. height, row_end = adjust_row_offset(height, row_end) # The end vertices are whatever is left from the width and height. x2 = width y2 = height [col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs] end
ruby
{ "resource": "" }
q19330
Writexlsx.Worksheet.prepare_vml_objects
train
def prepare_vml_objects(vml_data_id, vml_shape_id, vml_drawing_id, comment_id) set_external_vml_links(vml_drawing_id) set_external_comment_links(comment_id) if has_comments? # The VML o:idmap data id contains a comma separated range when there is # more than one 1024 block of comments, like this: data="1,2". data = "#{vml_data_id}" (1 .. num_comments_block).each do |i| data += ",#{vml_data_id + i}" end @vml_data_id = data @vml_shape_id = vml_shape_id end
ruby
{ "resource": "" }
q19331
Writexlsx.Worksheet.prepare_tables
train
def prepare_tables(table_id) if tables_count > 0 id = table_id tables.each do |table| table.prepare(id) # Store the link used for the rels file. @external_table_links << ['/table', "../tables/table#{id}.xml"] id += 1 end end tables_count || 0 end
ruby
{ "resource": "" }
q19332
Writexlsx.Worksheet.write_formatted_blank_to_area
train
def write_formatted_blank_to_area(row_first, row_last, col_first, col_last, format) (row_first .. row_last).each do |row| (col_first .. col_last).each do |col| next if row == row_first && col == col_first write_blank(row, col, format) end end end
ruby
{ "resource": "" }
q19333
Writexlsx.Worksheet.parse_filter_tokens
train
def parse_filter_tokens(expression, tokens) #:nodoc: operators = { '==' => 2, '=' => 2, '=~' => 2, 'eq' => 2, '!=' => 5, '!~' => 5, 'ne' => 5, '<>' => 5, '<' => 1, '<=' => 3, '>' => 4, '>=' => 6, } operator = operators[tokens[1]] token = tokens[2] # Special handling of "Top" filter expressions. if tokens[0] =~ /^top|bottom$/i value = tokens[1] if (value =~ /\D/ or value.to_i < 1 or value.to_i > 500) raise "The value '#{value}' in expression '#{expression}' " + "must be in the range 1 to 500" end token.downcase! if (token != 'items' and token != '%') raise "The type '#{token}' in expression '#{expression}' " + "must be either 'items' or '%'" end if (tokens[0] =~ /^top$/i) operator = 30 else operator = 32 end if (tokens[2] == '%') operator += 1 end token = value end if (not operator and tokens[0]) raise "Token '#{tokens[1]}' is not a valid operator " + "in filter expression '#{expression}'" end # Special handling for Blanks/NonBlanks. if (token =~ /^blanks|nonblanks$/i) # Only allow Equals or NotEqual in this context. if (operator != 2 and operator != 5) raise "The operator '#{tokens[1]}' in expression '#{expression}' " + "is not valid in relation to Blanks/NonBlanks'" end token.downcase! # The operator should always be 2 (=) to flag a "simple" equality in # the binary record. Therefore we convert <> to =. if token == 'blanks' if operator == 5 token = ' ' end else if operator == 5 operator = 2 token = 'blanks' else operator = 5 token = ' ' end end end # if the string token contains an Excel match character then change the # operator type to indicate a non "simple" equality. if (operator == 2 and token =~ /[*?]/) operator = 22 end [operator, token] end
ruby
{ "resource": "" }
q19334
Writexlsx.Worksheet.position_object_emus
train
def position_object_emus(col_start, row_start, x1, y1, width, height, x_dpi = 96, y_dpi = 96) #:nodoc: col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs = position_object_pixels(col_start, row_start, x1, y1, width, height) # Convert the pixel values to EMUs. See above. x1 = (0.5 + 9_525 * x1).to_i y1 = (0.5 + 9_525 * y1).to_i x2 = (0.5 + 9_525 * x2).to_i y2 = (0.5 + 9_525 * y2).to_i x_abs = (0.5 + 9_525 * x_abs).to_i y_abs = (0.5 + 9_525 * y_abs).to_i [col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs] end
ruby
{ "resource": "" }
q19335
Writexlsx.Worksheet.size_col
train
def size_col(col) #:nodoc: # Look up the cell value to see if it has been changed. if @col_sizes[col] width = @col_sizes[col] # Convert to pixels. if width == 0 pixels = 0 elsif width < 1 pixels = (width * (MAX_DIGIT_WIDTH + PADDING) + 0.5).to_i else pixels = (width * MAX_DIGIT_WIDTH + 0.5).to_i + PADDING end else pixels = @default_col_pixels end pixels end
ruby
{ "resource": "" }
q19336
Writexlsx.Worksheet.size_row
train
def size_row(row) #:nodoc: # Look up the cell value to see if it has been changed if @row_sizes[row] height = @row_sizes[row] if height == 0 pixels = 0 else pixels = (4 / 3.0 * height).to_i end else pixels = (4 / 3.0 * @default_row_height).to_i end pixels end
ruby
{ "resource": "" }
q19337
Writexlsx.Worksheet.prepare_shape
train
def prepare_shape(index, drawing_id) shape = @shapes[index] # Create a Drawing object to use with worksheet unless one already exists. unless drawing? @drawing = Drawing.new @drawing.embedded = 1 @external_drawing_links << ['/drawing', "../drawings/drawing#{drawing_id}.xml"] @has_shapes = true end # Validate the he shape against various rules. shape.validate(index) shape.calc_position_emus(self) drawing_type = 3 drawing.add_drawing_object(drawing_type, shape.dimensions, shape.name, shape) end
ruby
{ "resource": "" }
q19338
Writexlsx.Worksheet.button_params
train
def button_params(row, col, params) button = Writexlsx::Package::Button.new button_number = 1 + @buttons_array.size # Set the button caption. caption = params[:caption] || "Button #{button_number}" button.font = { :_caption => caption } # Set the macro name. if params[:macro] button.macro = "[0]!#{params[:macro]}" else button.macro = "[0]!Button#{button_number}_Click" end # Ensure that a width and height have been set. default_width = @default_col_pixels default_height = @default_row_pixels params[:width] = default_width if !params[:width] params[:height] = default_height if !params[:height] # Set the x/y offsets. params[:x_offset] = 0 if !params[:x_offset] params[:y_offset] = 0 if !params[:y_offset] # Scale the size of the comment box if required. if params[:x_scale] params[:width] = params[:width] * params[:x_scale] end if params[:y_scale] params[:height] = params[:height] * params[:y_scale] end # Round the dimensions to the nearest pixel. params[:width] = (0.5 + params[:width]).to_i params[:height] = (0.5 + params[:height]).to_i params[:start_row] = row params[:start_col] = col # Calculate the positions of comment object. vertices = position_object_pixels( params[:start_col], params[:start_row], params[:x_offset], params[:y_offset], params[:width], params[:height] ) # Add the width and height for VML. vertices << [params[:width], params[:height]] button.vertices = vertices button end
ruby
{ "resource": "" }
q19339
Writexlsx.Worksheet.write_rows
train
def write_rows #:nodoc: calculate_spans (@dim_rowmin .. @dim_rowmax).each do |row_num| # Skip row if it doesn't contain row formatting or cell data. next if not_contain_formatting_or_data?(row_num) span_index = row_num / 16 span = @row_spans[span_index] # Write the cells if the row contains data. if @cell_data_table[row_num] args = @set_rows[row_num] || [] write_row_element(row_num, span, *args) do write_cell_column_dimension(row_num) end elsif @comments[row_num] write_empty_row(row_num, span, *(@set_rows[row_num])) else # Row attributes only. write_empty_row(row_num, span, *(@set_rows[row_num])) end end end
ruby
{ "resource": "" }
q19340
Writexlsx.Worksheet.calculate_x_split_width
train
def calculate_x_split_width(width) #:nodoc: # Convert to pixels. if width < 1 pixels = int(width * 12 + 0.5) else pixels = (width * MAX_DIGIT_WIDTH + 0.5).to_i + PADDING end # Convert to points. points = pixels * 3 / 4 # Convert to twips (twentieths of a point). twips = points * 20 # Add offset/padding. twips + 390 end
ruby
{ "resource": "" }
q19341
Writexlsx.Worksheet.write_autofilters
train
def write_autofilters #:nodoc: col1, col2 = @filter_range (col1 .. col2).each do |col| # Skip if column doesn't have an active filter. next unless @filter_cols[col] # Retrieve the filter tokens and write the autofilter records. tokens = @filter_cols[col] type = @filter_type[col] # Filters are relative to first column in the autofilter. write_filter_column(col - col1, type, *tokens) end end
ruby
{ "resource": "" }
q19342
Writexlsx.Shape.calc_position_emus
train
def calc_position_emus(worksheet) c_start, r_start, xx1, yy1, c_end, r_end, xx2, yy2, x_abslt, y_abslt = worksheet.position_object_pixels( @column_start, @row_start, @x_offset, @y_offset, @width * @scale_x, @height * @scale_y ) # Now that x2/y2 have been calculated with a potentially negative # width/height we use the absolute value and convert to EMUs. @width_emu = (@width * 9_525).abs.to_i @height_emu = (@height * 9_525).abs.to_i @column_start = c_start.to_i @row_start = r_start.to_i @column_end = c_end.to_i @row_end = r_end.to_i # Convert the pixel values to EMUs. See above. @x1 = (xx1 * 9_525).to_i @y1 = (yy1 * 9_525).to_i @x2 = (xx2 * 9_525).to_i @y2 = (yy2 * 9_525).to_i @x_abs = (x_abslt * 9_525).to_i @y_abs = (y_abslt * 9_525).to_i end
ruby
{ "resource": "" }
q19343
Writexlsx.Shape.auto_locate_connectors
train
def auto_locate_connectors(shapes, shape_hash) # Valid connector shapes. connector_shapes = { :straightConnector => 1, :Connector => 1, :bentConnector => 1, :curvedConnector => 1, :line => 1 } shape_base = @type.chop.to_sym # Remove the number of segments from end of type. @connect = connector_shapes[shape_base] ? 1 : 0 return if @connect == 0 # Both ends have to be connected to size it. return if @start == 0 && @end == 0 # Both ends need to provide info about where to connect. return if @start_side == 0 && @end_side == 0 sid = @start eid = @end slink_id = shape_hash[sid] || 0 sls = shapes.fetch(slink_id, Shape.new) elink_id = shape_hash[eid] || 0 els = shapes.fetch(elink_id, Shape.new) # Assume shape connections are to the middle of an object, and # not a corner (for now). connect_type = @start_side + @end_side smidx = sls.x_offset + sls.width / 2 emidx = els.x_offset + els.width / 2 smidy = sls.y_offset + sls.height / 2 emidy = els.y_offset + els.height / 2 netx = (smidx - emidx).abs nety = (smidy - emidy).abs if connect_type == 'bt' sy = sls.y_offset + sls.height ey = els.y_offset @width = (emidx - smidx).to_i.abs @x_offset = [smidx, emidx].min.to_i @height = (els.y_offset - (sls.y_offset + sls.height)).to_i.abs @y_offset = [sls.y_offset + sls.height, els.y_offset].min.to_i @flip_h = smidx < emidx ? 1 : 0 @rotation = 90 if sy > ey @flip_v = 1 # Create 3 adjustments for an end shape vertically above a # start @ Adjustments count from the upper left object. if @adjustments.empty? @adjustments = [-10, 50, 110] end @type = 'bentConnector5' end elsif connect_type == 'rl' @width = (els.x_offset - (sls.x_offset + sls.width)).to_i.abs @height = (emidy - smidy).to_i.abs @x_offset = [sls.x_offset + sls.width, els.x_offset].min @y_offset = [smidy, emidy].min @flip_h = 1 if smidx < emidx && smidy > emidy @flip_h = 1 if smidx > emidx && smidy < emidy if smidx > emidx # Create 3 adjustments for an end shape to the left of a # start @ if @adjustments.empty? @adjustments = [-10, 50, 110] end @type = 'bentConnector5' end end end
ruby
{ "resource": "" }
q19344
Writexlsx.Shape.validate
train
def validate(index) unless %w[l ctr r just].include?(@align) raise "Shape #{index} (#{@type}) alignment (#{@align}) not in ['l', 'ctr', 'r', 'just']\n" end unless %w[t ctr b].include?(@valign) raise "Shape #{index} (#{@type}) vertical alignment (#{@valign}) not in ['t', 'ctr', 'v']\n" end end
ruby
{ "resource": "" }
q19345
Writexlsx.Format.copy
train
def copy(other) reserve = [ :xf_index, :dxf_index, :xdf_format_indices, :palette ] (instance_variables - reserve).each do |v| instance_variable_set(v, other.instance_variable_get(v)) end end
ruby
{ "resource": "" }
q19346
Writexlsx.Utility.layout_properties
train
def layout_properties(args, is_text = false) return unless ptrue?(args) properties = is_text ? [:x, :y] : [:x, :y, :width, :height] # Check for valid properties. args.keys.each do |key| unless properties.include?(key.to_sym) raise "Property '#{key}' not allowed in layout options\n" end end # Set the layout properties layout = Hash.new properties.each do |property| value = args[property] # Convert to the format used by Excel for easier testing. layout[property] = sprintf("%.17g", value) end layout end
ruby
{ "resource": "" }
q19347
Writexlsx.Utility.pixels_to_points
train
def pixels_to_points(vertices) col_start, row_start, x1, y1, col_end, row_end, x2, y2, left, top, width, height = vertices.flatten left *= 0.75 top *= 0.75 width *= 0.75 height *= 0.75 [left, top, width, height] end
ruby
{ "resource": "" }
q19348
Writexlsx.Sparkline.write_spark_color
train
def write_spark_color(element, color) # :nodoc: attr = [] attr << ['rgb', color[:_rgb]] if color[:_rgb] attr << ['theme', color[:_theme]] if color[:_theme] attr << ['tint', color[:_tint]] if color[:_tint] @writer.empty_tag(element, attr) end
ruby
{ "resource": "" }
q19349
Writexlsx.Workbook.assemble_xml_file
train
def assemble_xml_file #:nodoc: return unless @writer # Prepare format object for passing to Style.rb. prepare_format_properties write_xml_declaration do # Write the root workbook element. write_workbook do # Write the XLSX file version. write_file_version # Write the workbook properties. write_workbook_pr # Write the workbook view properties. write_book_views # Write the worksheet names and ids. @worksheets.write_sheets(@writer) # Write the workbook defined names. write_defined_names # Write the workbook calculation properties. write_calc_pr # Write the workbook extension storage. #write_ext_lst end end end
ruby
{ "resource": "" }
q19350
Writexlsx.Workbook.add_format
train
def add_format(property_hash = {}) properties = {} if @excel2003_style properties.update(:font => 'Arial', :size => 10, :theme => -1) end properties.update(property_hash) format = Format.new(@formats, properties) @formats.formats.push(format) # Store format reference format end
ruby
{ "resource": "" }
q19351
Writexlsx.Workbook.add_shape
train
def add_shape(properties = {}) shape = Shape.new(properties) shape.palette = @palette @shapes ||= [] @shapes << shape #Store shape reference. shape end
ruby
{ "resource": "" }
q19352
Writexlsx.Workbook.set_properties
train
def set_properties(params) # Ignore if no args were passed. return -1 if params.empty? # List of valid input parameters. valid = { :title => 1, :subject => 1, :author => 1, :keywords => 1, :comments => 1, :last_author => 1, :created => 1, :category => 1, :manager => 1, :company => 1, :status => 1 } # Check for valid input parameters. params.each_key do |key| return -1 unless valid.has_key?(key) end # Set the creation time unless specified by the user. params[:created] = @local_time unless params.has_key?(:created) @doc_properties = params.dup end
ruby
{ "resource": "" }
q19353
Writexlsx.Workbook.set_custom_color
train
def set_custom_color(index, red = 0, green = 0, blue = 0) # Match a HTML #xxyyzz style parameter if red =~ /^#(\w\w)(\w\w)(\w\w)/ red = $1.hex green = $2.hex blue = $3.hex end # Check that the colour index is the right range if index < 8 || index > 64 raise "Color index #{index} outside range: 8 <= index <= 64" end # Check that the colour components are in the right range if (red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255) raise "Color component outside range: 0 <= color <= 255" end index -=8 # Adjust colour index (wingless dragonfly) # Set the RGB value @palette[index] = [red, green, blue] # Store the custome colors for the style.xml file. @custom_colors << sprintf("FF%02X%02X%02X", red, green, blue) index + 8 end
ruby
{ "resource": "" }
q19354
Writexlsx.Workbook.store_workbook
train
def store_workbook #:nodoc: # Add a default worksheet if non have been added. add_worksheet if @worksheets.empty? # Ensure that at least one worksheet has been selected. @worksheets.visible_first.select if @activesheet == 0 # Set the active sheet. @activesheet = @worksheets.visible_first.index if @activesheet == 0 @worksheets[@activesheet].activate # Prepare the worksheet VML elements such as comments and buttons. prepare_vml_objects # Set the defined names for the worksheets such as Print Titles. prepare_defined_names # Prepare the drawings, charts and images. prepare_drawings # Add cached data to charts. add_chart_data # Prepare the worksheet tables. prepare_tables # Package the workbook. packager = Package::Packager.new(self) packager.set_package_dir(tempdir) packager.create_package # Free up the Packager object. packager = nil # Store the xlsx component files with the temp dir name removed. ZipFileUtils.zip("#{tempdir}", filename) IO.copy_stream(filename, fileobj) if fileobj Writexlsx::Utility.delete_files(tempdir) end
ruby
{ "resource": "" }
q19355
Writexlsx.Workbook.prepare_formats
train
def prepare_formats #:nodoc: @formats.formats.each do |format| xf_index = format.xf_index dxf_index = format.dxf_index @xf_formats[xf_index] = format if xf_index @dxf_formats[dxf_index] = format if dxf_index end end
ruby
{ "resource": "" }
q19356
Writexlsx.Workbook.prepare_fonts
train
def prepare_fonts #:nodoc: fonts = {} @xf_formats.each { |format| format.set_font_info(fonts) } @font_count = fonts.size # For the DXF formats we only need to check if the properties have changed. @dxf_formats.each do |format| # The only font properties that can change for a DXF format are: color, # bold, italic, underline and strikethrough. if format.color? || format.bold? || format.italic? || format.underline? || format.strikeout? format.has_dxf_font(true) end end end
ruby
{ "resource": "" }
q19357
Writexlsx.Workbook.prepare_num_formats
train
def prepare_num_formats #:nodoc: num_formats = {} index = 164 num_format_count = 0 (@xf_formats + @dxf_formats).each do |format| num_format = format.num_format # Check if num_format is an index to a built-in number format. # Also check for a string of zeros, which is a valid number format # string but would evaluate to zero. # if num_format.to_s =~ /^\d+$/ && num_format.to_s !~ /^0+\d/ # Index to a built-in number format. format.num_format_index = num_format next end if num_formats[num_format] # Number format has already been used. format.num_format_index = num_formats[num_format] else # Add a new number format. num_formats[num_format] = index format.num_format_index = index index += 1 # Only increase font count for XF formats (not for DXF formats). num_format_count += 1 if ptrue?(format.xf_index) end end @num_format_count = num_format_count end
ruby
{ "resource": "" }
q19358
Writexlsx.Workbook.prepare_borders
train
def prepare_borders #:nodoc: borders = {} @xf_formats.each { |format| format.set_border_info(borders) } @border_count = borders.size # For the DXF formats we only need to check if the properties have changed. @dxf_formats.each do |format| key = format.get_border_key format.has_dxf_border(true) if key =~ /[^0:]/ end end
ruby
{ "resource": "" }
q19359
Writexlsx.Workbook.prepare_fills
train
def prepare_fills #:nodoc: fills = {} index = 2 # Start from 2. See above. # Add the default fills. fills['0:0:0'] = 0 fills['17:0:0'] = 1 # Store the DXF colors separately since them may be reversed below. @dxf_formats.each do |format| if format.pattern != 0 || format.bg_color != 0 || format.fg_color != 0 format.has_dxf_fill(true) format.dxf_bg_color = format.bg_color format.dxf_fg_color = format.fg_color end end @xf_formats.each do |format| # The following logical statements jointly take care of special cases # in relation to cell colours and patterns: # 1. For a solid fill (_pattern == 1) Excel reverses the role of # foreground and background colours, and # 2. If the user specifies a foreground or background colour without # a pattern they probably wanted a solid fill, so we fill in the # defaults. # if format.pattern == 1 && ne_0?(format.bg_color) && ne_0?(format.fg_color) format.fg_color, format.bg_color = format.bg_color, format.fg_color elsif format.pattern <= 1 && ne_0?(format.bg_color) && eq_0?(format.fg_color) format.fg_color = format.bg_color format.bg_color = 0 format.pattern = 1 elsif format.pattern <= 1 && eq_0?(format.bg_color) && ne_0?(format.fg_color) format.bg_color = 0 format.pattern = 1 end key = format.get_fill_key if fills[key] # Fill has already been used. format.fill_index = fills[key] format.has_fill(false) else # This is a new fill. fills[key] = index format.fill_index = index format.has_fill(true) index += 1 end end @fill_count = index end
ruby
{ "resource": "" }
q19360
Writexlsx.Workbook.prepare_defined_names
train
def prepare_defined_names #:nodoc: @worksheets.each do |sheet| # Check for Print Area settings. if sheet.autofilter_area @defined_names << [ '_xlnm._FilterDatabase', sheet.index, sheet.autofilter_area, 1 ] end # Check for Print Area settings. if !sheet.print_area.empty? @defined_names << [ '_xlnm.Print_Area', sheet.index, sheet.print_area ] end # Check for repeat rows/cols. aka, Print Titles. if !sheet.print_repeat_cols.empty? || !sheet.print_repeat_rows.empty? if !sheet.print_repeat_cols.empty? && !sheet.print_repeat_rows.empty? range = sheet.print_repeat_cols + ',' + sheet.print_repeat_rows else range = sheet.print_repeat_cols + sheet.print_repeat_rows end # Store the defined names. @defined_names << ['_xlnm.Print_Titles', sheet.index, range] end end @defined_names = sort_defined_names(@defined_names) @named_ranges = extract_named_ranges(@defined_names) end
ruby
{ "resource": "" }
q19361
Writexlsx.Workbook.prepare_vml_objects
train
def prepare_vml_objects #:nodoc: comment_id = 0 vml_drawing_id = 0 vml_data_id = 1 vml_header_id = 0 vml_shape_id = 1024 comment_files = 0 has_button = false @worksheets.each do |sheet| next if !sheet.has_vml? && !sheet.has_header_vml? if sheet.has_vml? if sheet.has_comments? comment_files += 1 comment_id += 1 end vml_drawing_id += 1 sheet.prepare_vml_objects(vml_data_id, vml_shape_id, vml_drawing_id, comment_id) # Each VML file should start with a shape id incremented by 1024. vml_data_id += 1 * ( 1 + sheet.num_comments_block ) vml_shape_id += 1024 * ( 1 + sheet.num_comments_block ) end if sheet.has_header_vml? vml_header_id += 1 vml_drawing_id += 1 sheet.prepare_header_vml_objects(vml_header_id, vml_drawing_id) end # Set the sheet vba_codename if it has a button and the workbook # has a vbaProject binary. unless sheet.buttons_data.empty? has_button = true if @vba_project && !sheet.vba_codename sheet.set_vba_name end end end add_font_format_for_cell_comments if num_comment_files > 0 # Set the workbook vba_codename if one of the sheets has a button and # the workbook has a vbaProject binary. if has_button && @vba_project && !@vba_codename set_vba_name end end
ruby
{ "resource": "" }
q19362
Writexlsx.Workbook.extract_named_ranges
train
def extract_named_ranges(defined_names) #:nodoc: named_ranges = [] defined_names.each do |defined_name| name, index, range = defined_name # Skip autoFilter ranges. next if name == '_xlnm._FilterDatabase' # We are only interested in defined names with ranges. if range =~ /^([^!]+)!/ sheet_name = $1 # Match Print_Area and Print_Titles xlnm types. if name =~ /^_xlnm\.(.*)$/ xlnm_type = $1 name = "#{sheet_name}!#{xlnm_type}" elsif index != -1 name = "#{sheet_name}!#{name}" end named_ranges << name end end named_ranges end
ruby
{ "resource": "" }
q19363
Writexlsx.Workbook.prepare_drawings
train
def prepare_drawings #:nodoc: chart_ref_id = 0 image_ref_id = 0 drawing_id = 0 @worksheets.each do |sheet| chart_count = sheet.charts.size image_count = sheet.images.size shape_count = sheet.shapes.size header_image_count = sheet.header_images.size footer_image_count = sheet.footer_images.size has_drawing = false # Check that some image or drawing needs to be processed. next if chart_count + image_count + shape_count + header_image_count + footer_image_count == 0 # Don't increase the drawing_id header/footer images. if chart_count + image_count + shape_count > 0 drawing_id += 1 has_drawing = true end # Prepare the worksheet charts. sheet.charts.each_with_index do |chart, index| chart_ref_id += 1 sheet.prepare_chart(index, chart_ref_id, drawing_id) end # Prepare the worksheet images. sheet.images.each_with_index do |image, index| type, width, height, name, x_dpi, y_dpi = get_image_properties(image[2]) image_ref_id += 1 sheet.prepare_image(index, image_ref_id, drawing_id, width, height, name, type, x_dpi, y_dpi) end # Prepare the worksheet shapes. sheet.shapes.each_with_index do |shape, index| sheet.prepare_shape(index, drawing_id) end # Prepare the header images. header_image_count.times do |index| filename = sheet.header_images[index][0] position = sheet.header_images[index][1] type, width, height, name, x_dpi, y_dpi = get_image_properties(filename) image_ref_id += 1 sheet.prepare_header_image(image_ref_id, width, height, name, type, position, x_dpi, y_dpi) end # Prepare the footer images. footer_image_count.times do |index| filename = sheet.footer_images[index][0] position = sheet.footer_images[index][1] type, width, height, name, x_dpi, y_dpi = get_image_properties(filename) image_ref_id += 1 sheet.prepare_header_image(image_ref_id, width, height, name, type, position, x_dpi, y_dpi) end if has_drawing drawing = sheet.drawing @drawings << drawing end end # Sort the workbook charts references into the order that the were # written from the worksheets above. @charts = @charts.select { |chart| chart.id != -1 }. sort_by { |chart| chart.id } @drawing_count = drawing_id end
ruby
{ "resource": "" }
q19364
Writexlsx.Workbook.get_image_properties
train
def get_image_properties(filename) # Note the image_id, and previous_images mechanism isn't currently used. x_dpi = 96 y_dpi = 96 # Open the image file and import the data. data = File.binread(filename) if data.unpack('x A3')[0] == 'PNG' # Test for PNGs. type, width, height, x_dpi, y_dpi = process_png(data) @image_types[:png] = 1 elsif data.unpack('n')[0] == 0xFFD8 # Test for JPEG files. type, width, height, x_dpi, y_dpi = process_jpg(data, filename) @image_types[:jpeg] = 1 elsif data.unpack('A2')[0] == 'BM' # Test for BMPs. type, width, height = process_bmp(data, filename) @image_types[:bmp] = 1 else # TODO. Add Image::Size to support other types. raise "Unsupported image format for file: #{filename}\n" end @images << [filename, type] [type, width, height, File.basename(filename), x_dpi, y_dpi] end
ruby
{ "resource": "" }
q19365
Writexlsx.Workbook.process_png
train
def process_png(data) type = 'png' width = 0 height = 0 x_dpi = 96 y_dpi = 96 offset = 8 data_length = data.size # Search through the image data to read the height and width in th the # IHDR element. Also read the DPI in the pHYs element. while offset < data_length length = data[offset + 0, 4].unpack("N")[0] png_type = data[offset + 4, 4].unpack("A4")[0] case png_type when "IHDR" width = data[offset + 8, 4].unpack("N")[0] height = data[offset + 12, 4].unpack("N")[0] when "pHYs" x_ppu = data[offset + 8, 4].unpack("N")[0] y_ppu = data[offset + 12, 4].unpack("N")[0] units = data[offset + 16, 1].unpack("C")[0] if units == 1 x_dpi = x_ppu * 0.0254 y_dpi = y_ppu * 0.0254 end end offset = offset + length + 12 break if png_type == "IEND" end raise "#{filename}: no size data found in png image.\n" unless height [type, width, height, x_dpi, y_dpi] end
ruby
{ "resource": "" }
q19366
Writexlsx.Workbook.process_bmp
train
def process_bmp(data, filename) #:nodoc: type = 'bmp' # Check that the file is big enough to be a bitmap. raise "#{filename} doesn't contain enough data." if data.bytesize <= 0x36 # Read the bitmap width and height. Verify the sizes. width, height = data.unpack("x18 V2") raise "#{filename}: largest image width #{width} supported is 65k." if width > 0xFFFF raise "#{filename}: largest image height supported is 65k." if height > 0xFFFF # Read the bitmap planes and bpp data. Verify them. planes, bitcount = data.unpack("x26 v2") raise "#{filename} isn't a 24bit true color bitmap." unless bitcount == 24 raise "#{filename}: only 1 plane supported in bitmap image." unless planes == 1 # Read the bitmap compression. Verify compression. compression = data.unpack("x30 V")[0] raise "#{filename}: compression not supported in bitmap image." unless compression == 0 [type, width, height] end
ruby
{ "resource": "" }
q19367
XRay.Configuration.daemon_address=
train
def daemon_address=(v) v = ENV[DaemonConfig::DAEMON_ADDRESS_KEY] || v config = DaemonConfig.new(addr: v) emitter.daemon_config = config sampler.daemon_config = config if sampler.respond_to?(:daemon_config=) end
ruby
{ "resource": "" }
q19368
XRay.Subsegment.all_children_count
train
def all_children_count size = subsegments.count subsegments.each { |v| size += v.all_children_count } size end
ruby
{ "resource": "" }
q19369
XRay.LocalSampler.sample_request?
train
def sample_request?(sampling_req) sample = sample? return sample if sampling_req.nil? || sampling_req.empty? @custom_rules ||= [] @custom_rules.each do |c| return should_sample?(c) if c.applies?(sampling_req) end # use previously made decision based on default rule # if no path-based rule has been matched sample end
ruby
{ "resource": "" }
q19370
XRay.Recorder.begin_segment
train
def begin_segment(name, trace_id: nil, parent_id: nil, sampled: nil) seg_name = name || config.name raise SegmentNameMissingError if seg_name.to_s.empty? # sampling decision comes from outside has higher precedence. sample = sampled.nil? ? config.sample? : sampled if sample segment = Segment.new name: seg_name, trace_id: trace_id, parent_id: parent_id populate_runtime_context(segment, sample) else segment = DummySegment.new name: seg_name, trace_id: trace_id, parent_id: parent_id end context.store_entity entity: segment segment end
ruby
{ "resource": "" }
q19371
XRay.Recorder.end_segment
train
def end_segment(end_time: nil) segment = current_segment return unless segment segment.close end_time: end_time context.clear! emitter.send_entity entity: segment if segment.ready_to_send? end
ruby
{ "resource": "" }
q19372
XRay.Recorder.begin_subsegment
train
def begin_subsegment(name, namespace: nil, segment: nil) entity = segment || current_entity return unless entity if entity.sampled subsegment = Subsegment.new name: name, segment: entity.segment, namespace: namespace else subsegment = DummySubsegment.new name: name, segment: entity.segment end # attach the new created subsegment under the current active entity entity.add_subsegment subsegment: subsegment # associate the new subsegment to the current context context.store_entity entity: subsegment subsegment end
ruby
{ "resource": "" }
q19373
XRay.Recorder.end_subsegment
train
def end_subsegment(end_time: nil) entity = current_entity return unless entity.is_a?(Subsegment) entity.close end_time: end_time # update current context if entity.parent.closed? context.clear! else context.store_entity entity: entity.parent end # check if the entire segment can be send. # If not, stream subsegments when threshold is reached. segment = entity.segment if segment.ready_to_send? emitter.send_entity entity: segment elsif streamer.eligible? segment: segment streamer.stream_subsegments root: segment, emitter: emitter end end
ruby
{ "resource": "" }
q19374
XRay.Recorder.capture
train
def capture(name, namespace: nil, segment: nil) subsegment = begin_subsegment name, namespace: namespace, segment: segment # prevent passed block from failing in case of context missing with log error if subsegment.nil? segment = DummySegment.new name: name subsegment = DummySubsegment.new name: name, segment: segment end begin yield subsegment rescue Exception => e subsegment.add_exception exception: e raise e ensure end_subsegment end end
ruby
{ "resource": "" }
q19375
XRay.Recorder.metadata
train
def metadata(namespace: :default) entity = current_entity if entity entity.metadata(namespace: namespace) else FacadeMetadata end end
ruby
{ "resource": "" }
q19376
XRay.Reservoir.borrow_or_take
train
def borrow_or_take(now, borrowable) @lock.synchronize do reset_new_sec(now) # Don't borrow if the quota is available and fresh. if quota_fresh?(now) return SamplingDecision::NOT_SAMPLE if @taken_this_sec >= @quota @taken_this_sec += 1 return SamplingDecision::TAKE end # Otherwise try to borrow if the quota is not present or expired. if borrowable return SamplingDecision::NOT_SAMPLE if @borrowed_this_sec >= 1 @borrowed_this_sec += 1 return SamplingDecision::BORROW end # Cannot sample if quota expires and cannot borrow SamplingDecision::NOT_SAMPLE end end
ruby
{ "resource": "" }
q19377
XRay.DefaultSampler.sample_request?
train
def sample_request?(sampling_req) start unless @started now = Time.now.to_i if sampling_req.nil? sampling_req = { service_type: @origin } if @origin elsif !sampling_req.key?(:service_type) sampling_req[:service_type] = @origin if @origin end matched_rule = @cache.get_matched_rule(sampling_req, now: now) if !matched_rule.nil? logger.debug %(Rule #{matched_rule.name} is selected to make a sampling decision.') process_matched_rule(matched_rule, now) else logger.warn %(No effective centralized sampling rule match. Fallback to local rules.) @local_sampler.sample_request?(sampling_req) end end
ruby
{ "resource": "" }
q19378
Bigcommerce.PathBuilder.build
train
def build(keys = []) keys = [] if keys.nil? keys = [keys] if keys.is_a? Numeric ids = uri.scan('%d').count + uri.scan('%s').count str = ids > keys.size ? uri.chomp('%d').chomp('%s').chomp('/') : uri (str % keys).chomp('/') end
ruby
{ "resource": "" }
q19379
Bigcommerce.Customer.login_token
train
def login_token(config: Bigcommerce.config) payload = { 'iss' => config.client_id, 'iat' => Time.now.to_i, 'jti' => SecureRandom.uuid, 'operation' => 'customer_login', 'store_hash' => config.store_hash, 'customer_id' => id } JWT.encode(payload, config.client_secret, 'HS256') end
ruby
{ "resource": "" }
q19380
JasmineRails.OfflineAssetPaths.compute_public_path
train
def compute_public_path(source, dir, options={}) JasmineRails::OfflineAssetPaths.disabled ? super : compute_asset_path(source, options) end
ruby
{ "resource": "" }
q19381
JasmineRails.SaveFixture.save_fixture
train
def save_fixture(file_name, content = rendered) fixture_path = File.join(Rails.root, FIXTURE_DIRECTORY, file_name) fixture_directory = File.dirname(fixture_path) FileUtils.mkdir_p fixture_directory unless File.exists?(fixture_directory) File.open(fixture_path, 'w') do |file| file.puts(content) end ignore_generated_fixtures end
ruby
{ "resource": "" }
q19382
Airbrussh.Console.print_line
train
def print_line(obj="") string = obj.to_s string = truncate_to_console_width(string) if console_width string = strip_ascii_color(string) unless color_enabled? write(string + "\n") output.flush end
ruby
{ "resource": "" }
q19383
Spinach.Runner.init_reporters
train
def init_reporters Spinach.config[:reporter_classes].each do |reporter_class| reporter_options = default_reporter_options.merge(Spinach.config.reporter_options) reporter = Support.constantize(reporter_class).new(reporter_options) reporter.bind end end
ruby
{ "resource": "" }
q19384
Spinach.Runner.run
train
def run require_dependencies require_frameworks init_reporters suite_passed = true Spinach.hooks.run_before_run features_to_run.each do |feature| feature_passed = FeatureRunner.new(feature, orderer: orderer).run suite_passed &&= feature_passed break if fail_fast? && !feature_passed end Spinach.hooks.run_after_run(suite_passed) suite_passed end
ruby
{ "resource": "" }
q19385
Spinach.Runner.orderer
train
def orderer @orderer ||= Support.constantize(Spinach.config[:orderer_class]).new( seed: Spinach.config.seed ) end
ruby
{ "resource": "" }
q19386
Spinach.Config.parse_from_file
train
def parse_from_file parsed_opts = YAML.load_file(config_path) parsed_opts.delete_if{|k| k.to_s == 'config_path'} parsed_opts.each_pair{|k,v| self[k] = v} true rescue Errno::ENOENT false end
ruby
{ "resource": "" }
q19387
Spinach.Hooks.on_tag
train
def on_tag(tag) before_scenario do |scenario, step_definitions| tags = scenario.tags next unless tags.any? yield(scenario, step_definitions) if tags.include? tag.to_s end end
ruby
{ "resource": "" }
q19388
Spinach.Auditor.get_feature_and_defs
train
def get_feature_and_defs(file) feature = Parser.open_file(file).parse [feature, Spinach.find_step_definitions(feature.name)] end
ruby
{ "resource": "" }
q19389
Spinach.Auditor.step_missing?
train
def step_missing?(step, step_defs) method_name = Spinach::Support.underscore step.name return true unless step_defs.respond_to?(method_name) # Remember that we have used this step used_steps << step_defs.step_location_for(step.name).join(':') false end
ruby
{ "resource": "" }
q19390
Spinach.Auditor.store_unused_steps
train
def store_unused_steps(names, step_defs) names.each do |name| location = step_defs.step_location_for(name).join(':') unused_steps[location] = name end end
ruby
{ "resource": "" }
q19391
Spinach.Auditor.step_names_for_class
train
def step_names_for_class(klass) klass.ancestors.map { |a| a.respond_to?(:steps) ? a.steps : [] }.flatten end
ruby
{ "resource": "" }
q19392
Spinach.Auditor.report_unused_steps
train
def report_unused_steps # Remove any unused_steps that were in common modules and used # in another feature used_steps.each { |location| unused_steps.delete location } unused_steps.each do |location, name| puts "\n" + "Unused step: #{location} ".colorize(:yellow) + "'#{name}'".colorize(:light_yellow) end end
ruby
{ "resource": "" }
q19393
Spinach.Auditor.report_missing_steps
train
def report_missing_steps(steps) puts "\nMissing steps:".colorize(:light_cyan) steps.each do |step| puts Generators::StepGenerator.new(step).generate.gsub(/^/, ' ') .colorize(:cyan) end end
ruby
{ "resource": "" }
q19394
Spinach.Reporter.bind
train
def bind Spinach.hooks.tap do |hooks| hooks.before_run { |*args| before_run(*args) } hooks.after_run { |*args| after_run(*args) } hooks.before_feature { |*args| before_feature_run(*args) } hooks.after_feature { |*args| after_feature_run(*args) } hooks.on_undefined_feature { |*args| on_feature_not_found(*args) } hooks.before_scenario { |*args| before_scenario_run(*args) } hooks.around_scenario { |*args, &block| around_scenario_run(*args, &block) } hooks.after_scenario { |*args| after_scenario_run(*args) } hooks.on_successful_step { |*args| on_successful_step(*args) } hooks.on_undefined_step { |*args| on_undefined_step(*args) } hooks.on_pending_step { |*args| on_pending_step(*args) } hooks.on_failed_step { |*args| on_failed_step(*args) } hooks.on_error_step { |*args| on_error_step(*args) } hooks.on_skipped_step { |*args| on_skipped_step(*args) } hooks.before_feature { |*args| set_current_feature(*args) } hooks.after_feature { |*args| clear_current_feature(*args) } hooks.before_scenario { |*args| set_current_scenario(args.first) } hooks.after_scenario { |*args| clear_current_scenario(args.first) } end end
ruby
{ "resource": "" }
q19395
Spinach.Cli.feature_files
train
def feature_files files_to_run = [] @args.each do |arg| if arg.match(/\.feature/) if File.exists? arg.gsub(/:\d*/, '') files_to_run << arg else fail! "#{arg} could not be found" end elsif File.directory?(arg) files_to_run << Dir.glob(File.join(arg, '**', '*.feature')) elsif arg != "{}" fail! "invalid argument - #{arg}" end end if !files_to_run.empty? files_to_run.flatten else Dir.glob(File.join(Spinach.config[:features_path], '**', '*.feature')) end end
ruby
{ "resource": "" }
q19396
Spinach.Cli.parse_options
train
def parse_options config = {} begin OptionParser.new do |opts| opts.on('-c', '--config_path PATH', 'Parse options from file (will get overriden by flags)') do |file| Spinach.config[:config_path] = file end opts.on('-b', '--backtrace', 'Show backtrace of errors') do |show_backtrace| config[:reporter_options] = {backtrace: show_backtrace} end opts.on('-t', '--tags TAG', 'Run all scenarios for given tags.') do |tag| config[:tags] ||= [] tags = tag.delete('@').split(',') if (config[:tags] + tags).flatten.none? { |t| t =~ /wip$/ } tags.unshift '~wip' end config[:tags] << tags end opts.on('-g', '--generate', 'Auto-generate the feature steps files') do config[:generate] = true end opts.on_tail('--version', 'Show version') do puts Spinach::VERSION exit end opts.on('-f', '--features_path PATH', 'Path where your features will be searched for') do |path| config[:features_path] = path end opts.on('-r', '--reporter CLASS_NAMES', 'Formatter class names, separated by commas') do |class_names| names = class_names.split(',').map { |c| reporter_class(c) } config[:reporter_classes] = names end opts.on('--rand', "Randomize the order of features and scenarios") do config[:orderer_class] = orderer_class(:random) end opts.on('--seed SEED', Integer, "Provide a seed for randomizing the order of features and scenarios") do |seed| config[:orderer_class] = orderer_class(:random) config[:seed] = seed end opts.on_tail('--fail-fast', 'Terminate the suite run on the first failure') do |class_name| config[:fail_fast] = true end opts.on('-a', '--audit', "Audit steps instead of running them, outputting missing \ and obsolete steps") do config[:audit] = true end end.parse!(@args) Spinach.config.parse_from_file config.each{|k,v| Spinach.config[k] = v} if Spinach.config.tags.empty? || Spinach.config.tags.flatten.none?{ |t| t =~ /wip$/ } Spinach.config.tags.unshift ['~wip'] end rescue OptionParser::ParseError => exception puts exception.message.capitalize exit 1 end end
ruby
{ "resource": "" }
q19397
KnifeSolo.SshCommand.run_with_fallbacks
train
def run_with_fallbacks(commands, options = {}) commands.each do |command| result = run_command(command, options) return result if result.success? end SshConnection::ExecResult.new(1) end
ruby
{ "resource": "" }
q19398
Neo4j.Transaction.run
train
def run(*args) session, run_in_tx = session_and_run_in_tx_from_args(args) fail ArgumentError, 'Expected a block to run in Transaction.run' unless block_given? return yield(nil) unless run_in_tx tx = Neo4j::Transaction.new(session) yield tx rescue Exception => e # rubocop:disable Lint/RescueException # print_exception_cause(e) tx.mark_failed unless tx.nil? raise e ensure tx.close unless tx.nil? end
ruby
{ "resource": "" }
q19399
Neo4j.Transaction.session_and_run_in_tx_from_args
train
def session_and_run_in_tx_from_args(args) fail ArgumentError, 'Too few arguments' if args.empty? fail ArgumentError, 'Too many arguments' if args.size > 2 if args.size == 1 fail ArgumentError, 'Session must be specified' if !args[0].is_a?(Neo4j::Core::CypherSession) [args[0], true] else [true, false].include?(args[0]) ? args.reverse : args.dup end end
ruby
{ "resource": "" }