_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q26700
Aerospike.Command.write_header
test
def write_header(policy, read_attr, write_attr, field_count, operation_count) read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL # Write all header data except total size which must be written last. @data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length. @data_buffer.write_byte(read_attr, 9) @data_buffer.write_byte(write_attr, 10) i = 11 while i <= 25 @data_buffer.write_byte(0, i) i = i.succ end @data_buffer.write_int16(field_count, 26) @data_buffer.write_int16(operation_count, 28) @data_offset = MSG_TOTAL_HEADER_SIZE end
ruby
{ "resource": "" }
q26701
Aerospike.Command.write_header_with_policy
test
def write_header_with_policy(policy, read_attr, write_attr, field_count, operation_count) # Set flags. generation = Integer(0) info_attr = Integer(0) case policy.record_exists_action when Aerospike::RecordExistsAction::UPDATE when Aerospike::RecordExistsAction::UPDATE_ONLY info_attr |= INFO3_UPDATE_ONLY when Aerospike::RecordExistsAction::REPLACE info_attr |= INFO3_CREATE_OR_REPLACE when Aerospike::RecordExistsAction::REPLACE_ONLY info_attr |= INFO3_REPLACE_ONLY when Aerospike::RecordExistsAction::CREATE_ONLY write_attr |= INFO2_CREATE_ONLY end case policy.generation_policy when Aerospike::GenerationPolicy::NONE when Aerospike::GenerationPolicy::EXPECT_GEN_EQUAL generation = policy.generation write_attr |= INFO2_GENERATION when Aerospike::GenerationPolicy::EXPECT_GEN_GT generation = policy.generation write_attr |= INFO2_GENERATION_GT end info_attr |= INFO3_COMMIT_MASTER if policy.commit_level == Aerospike::CommitLevel::COMMIT_MASTER read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL write_attr |= INFO2_DURABLE_DELETE if policy.durable_delete # Write all header data except total size which must be written last. @data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length. @data_buffer.write_byte(read_attr, 9) @data_buffer.write_byte(write_attr, 10) @data_buffer.write_byte(info_attr, 11) @data_buffer.write_byte(0, 12) # unused @data_buffer.write_byte(0, 13) # clear the result code @data_buffer.write_uint32(generation, 14) @data_buffer.write_uint32(policy.ttl, 18) # Initialize timeout. It will be written later. @data_buffer.write_byte(0, 22) @data_buffer.write_byte(0, 23) @data_buffer.write_byte(0, 24) @data_buffer.write_byte(0, 25) @data_buffer.write_int16(field_count, 26) @data_buffer.write_int16(operation_count, 28) @data_offset = MSG_TOTAL_HEADER_SIZE end
ruby
{ "resource": "" }
q26702
Aerospike.ExecuteTask.all_nodes_done?
test
def all_nodes_done? if @scan command = 'scan-list' else command = 'query-list' end nodes = @cluster.nodes done = false nodes.each do |node| conn = node.get_connection(0) responseMap, _ = Info.request(conn, command) node.put_connection(conn) response = responseMap[command] find = "job_id=#{@task_id}:" index = response.index(find) unless index # don't return on first check done = true next end b = index + find.length response = response[b, response.length] find = 'job_status=' index = response.index(find) next unless index b = index + find.length response = response[b, response.length] e = response.index(':') status = response[0, e] case status when 'ABORTED' raise raise Aerospike::Exceptions::QueryTerminated when 'IN PROGRESS' return false when 'DONE' done = true end end done end
ruby
{ "resource": "" }
q26703
Aerospike.Node.get_connection
test
def get_connection(timeout) loop do conn = @connections.poll if conn.connected? conn.timeout = timeout.to_f return conn end end end
ruby
{ "resource": "" }
q26704
Aerospike.MultiCommand.parse_record
test
def parse_record(key, op_count, generation, expiration) bins = op_count > 0 ? {} : nil i = 0 while i < op_count raise Aerospike::Exceptions::QueryTerminated.new unless valid? read_bytes(8) op_size = @data_buffer.read_int32(0).ord particle_type = @data_buffer.read(5).ord name_size = @data_buffer.read(7).ord read_bytes(name_size) name = @data_buffer.read(0, name_size).force_encoding('utf-8') particle_bytes_size = op_size - (4 + name_size) read_bytes(particle_bytes_size) value = Aerospike.bytes_to_particle(particle_type, @data_buffer, 0, particle_bytes_size) bins[name] = value i = i.succ end Record.new(@node, key, bins, generation, expiration) end
ruby
{ "resource": "" }
q26705
Aerospike.Cluster.random_node
test
def random_node # Must copy array reference for copy on write semantics to work. node_array = nodes length = node_array.length i = 0 while i < length # Must handle concurrency with other non-tending threads, so node_index is consistent. index = (@node_index.update{ |v| v+1 } % node_array.length).abs node = node_array[index] return node if node.active? i = i.succ end raise Aerospike::Exceptions::InvalidNode end
ruby
{ "resource": "" }
q26706
Aerospike.Cluster.get_node_by_name
test
def get_node_by_name(node_name) node = find_node_by_name(node_name) raise Aerospike::Exceptions::InvalidNode unless node node end
ruby
{ "resource": "" }
q26707
Aerospike.Client.prepend
test
def prepend(key, bins, options = nil) policy = create_policy(options, WritePolicy, default_write_policy) command = WriteCommand.new(@cluster, policy, key, hash_to_bins(bins), Aerospike::Operation::PREPEND) execute_command(command) end
ruby
{ "resource": "" }
q26708
Aerospike.Client.get_header
test
def get_header(key, options = nil) policy = create_policy(options, Policy, default_read_policy) command = ReadHeaderCommand.new(@cluster, policy, key) execute_command(command) command.record end
ruby
{ "resource": "" }
q26709
Aerospike.Client.batch_exists
test
def batch_exists(keys, options = nil) policy = create_policy(options, BatchPolicy, default_batch_policy) results = Array.new(keys.length) if policy.use_batch_direct key_map = BatchItem.generate_map(keys) execute_batch_direct_commands(keys) do |node, batch| BatchDirectExistsCommand.new(node, batch, policy, key_map, results) end else execute_batch_index_commands(keys) do |node, batch| BatchIndexExistsCommand.new(node, batch, policy, results) end end results end
ruby
{ "resource": "" }
q26710
Aerospike.Client.register_udf
test
def register_udf(udf_body, server_path, language, options = nil) policy = create_policy(options, Policy, default_info_policy) content = Base64.strict_encode64(udf_body).force_encoding('binary') str_cmd = "udf-put:filename=#{server_path};content=#{content};" str_cmd << "content-len=#{content.length};udf-type=#{language};" # Send UDF to one node. That node will distribute the UDF to other nodes. response_map = @cluster.request_info(policy, str_cmd) res = {} response_map.each do |k, response| vals = response.to_s.split(';') vals.each do |pair| k, v = pair.split("=", 2) res[k] = v end end if res['error'] raise Aerospike::Exceptions::CommandRejected.new("Registration failed: #{res['error']}\nFile: #{res['file']}\nLine: #{res['line']}\nMessage: #{res['message']}") end UdfRegisterTask.new(@cluster, server_path) end
ruby
{ "resource": "" }
q26711
Aerospike.Client.remove_udf
test
def remove_udf(udf_name, options = nil) policy = create_policy(options, Policy, default_info_policy) str_cmd = "udf-remove:filename=#{udf_name};" # Send command to one node. That node will distribute it to other nodes. # Send UDF to one node. That node will distribute the UDF to other nodes. response_map = @cluster.request_info(policy, str_cmd) _, response = response_map.first if response == 'ok' UdfRemoveTask.new(@cluster, udf_name) else raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_ERROR, response) end end
ruby
{ "resource": "" }
q26712
Aerospike.Client.list_udf
test
def list_udf(options = nil) policy = create_policy(options, Policy, default_info_policy) str_cmd = 'udf-list' # Send command to one node. That node will distribute it to other nodes. response_map = @cluster.request_info(policy, str_cmd) _, response = response_map.first vals = response.split(';') vals.map do |udf_info| next if udf_info.strip! == '' udf_parts = udf_info.split(',') udf = UDF.new udf_parts.each do |values| k, v = values.split('=', 2) case k when 'filename' udf.filename = v when 'hash' udf.hash = v when 'type' udf.language = v end end udf end end
ruby
{ "resource": "" }
q26713
Aerospike.Client.execute_udf_on_query
test
def execute_udf_on_query(statement, package_name, function_name, function_args=[], options = nil) policy = create_policy(options, QueryPolicy, default_query_policy) nodes = @cluster.nodes if nodes.empty? raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_NOT_AVAILABLE, "Executing UDF failed because cluster is empty.") end # TODO: wait until all migrations are finished statement.set_aggregate_function(package_name, function_name, function_args, false) # Use a thread per node nodes.each do |node| Thread.new do Thread.current.abort_on_exception = true begin command = QueryCommand.new(node, policy, statement, nil) execute_command(command) rescue => e Aerospike.logger.error(e) raise e end end end ExecuteTask.new(@cluster, statement) end
ruby
{ "resource": "" }
q26714
Aerospike.Client.create_index
test
def create_index(namespace, set_name, index_name, bin_name, index_type, collection_type = nil, options = nil) if options.nil? && collection_type.is_a?(Hash) options, collection_type = collection_type, nil end policy = create_policy(options, Policy, default_info_policy) str_cmd = "sindex-create:ns=#{namespace}" str_cmd << ";set=#{set_name}" unless set_name.to_s.strip.empty? str_cmd << ";indexname=#{index_name};numbins=1" str_cmd << ";indextype=#{collection_type.to_s.upcase}" if collection_type str_cmd << ";indexdata=#{bin_name},#{index_type.to_s.upcase}" str_cmd << ";priority=normal" # Send index command to one node. That node will distribute the command to other nodes. response = send_info_command(policy, str_cmd).upcase if response == 'OK' # Return task that could optionally be polled for completion. return IndexTask.new(@cluster, namespace, index_name) end if response.start_with?('FAIL:200') # Index has already been created. Do not need to poll for completion. return IndexTask.new(@cluster, namespace, index_name, true) end raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::INDEX_GENERIC, "Create index failed: #{response}") end
ruby
{ "resource": "" }
q26715
Aerospike.Client.drop_index
test
def drop_index(namespace, set_name, index_name, options = nil) policy = create_policy(options, Policy, default_info_policy) str_cmd = "sindex-delete:ns=#{namespace}" str_cmd << ";set=#{set_name}" unless set_name.to_s.strip.empty? str_cmd << ";indexname=#{index_name}" # Send index command to one node. That node will distribute the command to other nodes. response = send_info_command(policy, str_cmd).upcase return if response == 'OK' # Index did not previously exist. Return without error. return if response.start_with?('FAIL:201') raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::INDEX_GENERIC, "Drop index failed: #{response}") end
ruby
{ "resource": "" }
q26716
Aerospike.Client.scan_node
test
def scan_node(node, namespace, set_name, bin_names = nil, options = nil) policy = create_policy(options, ScanPolicy, default_scan_policy) # wait until all migrations are finished # TODO: implement # @cluster.WaitUntillMigrationIsFinished(policy.timeout) # Retry policy must be one-shot for scans. # copy on write for policy new_policy = policy.clone new_policy.max_retries = 0 node = @cluster.get_node_by_name(node) unless node.is_a?(Aerospike::Node) recordset = Recordset.new(policy.record_queue_size, 1, :scan) Thread.new do Thread.current.abort_on_exception = true command = ScanCommand.new(node, new_policy, namespace, set_name, bin_names, recordset) begin execute_command(command) rescue => e Aerospike.logger.error(e.backtrace.join("\n")) unless e == SCAN_TERMINATED_EXCEPTION recordset.cancel(e) ensure recordset.thread_finished end end recordset end
ruby
{ "resource": "" }
q26717
Aerospike.Client.drop_user
test
def drop_user(user, options = nil) policy = create_policy(options, AdminPolicy, default_admin_policy) command = AdminCommand.new command.drop_user(@cluster, policy, user) end
ruby
{ "resource": "" }
q26718
Aerospike.Client.change_password
test
def change_password(user, password, options = nil) raise Aerospike::Exceptions::Aerospike.new(INVALID_USER) unless @cluster.user && @cluster.user != "" policy = create_policy(options, AdminPolicy, default_admin_policy) hash = AdminCommand.hash_password(password) command = AdminCommand.new if user == @cluster.user # Change own password. command.change_password(@cluster, policy, user, hash) else # Change other user's password by user admin. command.set_password(@cluster, policy, user, hash) end @cluster.change_password(user, hash) end
ruby
{ "resource": "" }
q26719
Aerospike.Client.grant_roles
test
def grant_roles(user, roles, options = nil) policy = create_policy(options, AdminPolicy, default_admin_policy) command = AdminCommand.new command.grant_roles(@cluster, policy, user, roles) end
ruby
{ "resource": "" }
q26720
Aerospike.Client.query_users
test
def query_users(options = nil) policy = create_policy(options, AdminPolicy, default_admin_policy) command = AdminCommand.new command.query_users(@cluster, policy) end
ruby
{ "resource": "" }
q26721
Aerospike.Recordset.next_record
test
def next_record raise @thread_exception.get unless @thread_exception.get.nil? r = @records.deq set_exception if r.nil? r end
ruby
{ "resource": "" }
q26722
Aerospike.Recordset.each
test
def each(&block) r = true while r r = next_record # nil means EOF unless r.nil? block.call(r) else # reached the EOF break end end end
ruby
{ "resource": "" }
q26723
IntercomRails.ScriptTagHelper.intercom_script_tag
test
def intercom_script_tag(user_details = nil, options={}) controller.instance_variable_set(IntercomRails::SCRIPT_TAG_HELPER_CALLED_INSTANCE_VARIABLE, true) if defined?(controller) options[:user_details] = user_details if user_details.present? options[:find_current_user_details] = !options[:user_details] options[:find_current_company_details] = !(options[:user_details] && options[:user_details][:company]) options[:controller] = controller if defined?(controller) ScriptTag.new(options) end
ruby
{ "resource": "" }
q26724
MiniGL.Movement.move_free
test
def move_free(aim, speed) if aim.is_a? Vector x_d = aim.x - @x; y_d = aim.y - @y distance = Math.sqrt(x_d**2 + y_d**2) if distance == 0 @speed.x = @speed.y = 0 return end @speed.x = 1.0 * x_d * speed / distance @speed.y = 1.0 * y_d * speed / distance if (@speed.x < 0 and @x + @speed.x <= aim.x) or (@speed.x >= 0 and @x + @speed.x >= aim.x) @x = aim.x @speed.x = 0 else @x += @speed.x end if (@speed.y < 0 and @y + @speed.y <= aim.y) or (@speed.y >= 0 and @y + @speed.y >= aim.y) @y = aim.y @speed.y = 0 else @y += @speed.y end else rads = aim * Math::PI / 180 @speed.x = speed * Math.cos(rads) @speed.y = speed * Math.sin(rads) @x += @speed.x @y += @speed.y end end
ruby
{ "resource": "" }
q26725
MiniGL.Map.get_absolute_size
test
def get_absolute_size return Vector.new(@tile_size.x * @size.x, @tile_size.y * @size.y) unless @isometric avg = (@size.x + @size.y) * 0.5 Vector.new (avg * @tile_size.x).to_i, (avg * @tile_size.y).to_i end
ruby
{ "resource": "" }
q26726
MiniGL.Map.get_screen_pos
test
def get_screen_pos(map_x, map_y) return Vector.new(map_x * @tile_size.x - @cam.x, map_y * @tile_size.y - @cam.y) unless @isometric Vector.new ((map_x - map_y - 1) * @tile_size.x * 0.5) - @cam.x + @x_offset, ((map_x + map_y) * @tile_size.y * 0.5) - @cam.y end
ruby
{ "resource": "" }
q26727
MiniGL.Map.get_map_pos
test
def get_map_pos(scr_x, scr_y) return Vector.new((scr_x + @cam.x) / @tile_size.x, (scr_y + @cam.y) / @tile_size.y) unless @isometric # Gets the position transformed to isometric coordinates v = get_isometric_position scr_x, scr_y # divides by the square size to find the position in the matrix Vector.new((v.x * @inverse_square_size).to_i, (v.y * @inverse_square_size).to_i) end
ruby
{ "resource": "" }
q26728
MiniGL.Map.is_in_map
test
def is_in_map(v) v.x >= 0 && v.y >= 0 && v.x < @size.x && v.y < @size.y end
ruby
{ "resource": "" }
q26729
MiniGL.Sprite.animate_once
test
def animate_once(indices, interval) if @animate_once_control == 2 return if indices == @animate_once_indices && interval == @animate_once_interval @animate_once_control = 0 end unless @animate_once_control == 1 @anim_counter = 0 @img_index = indices[0] @index_index = 0 @animate_once_indices = indices @animate_once_interval = interval @animate_once_control = 1 return end @anim_counter += 1 return unless @anim_counter >= interval @index_index += 1 @img_index = indices[@index_index] @anim_counter = 0 @animate_once_control = 2 if @index_index == indices.length - 1 end
ruby
{ "resource": "" }
q26730
MiniGL.Sprite.draw
test
def draw(map = nil, scale_x = 1, scale_y = 1, alpha = 0xff, color = 0xffffff, angle = nil, flip = nil, z_index = 0, round = false) if map.is_a? Hash scale_x = map.fetch(:scale_x, 1) scale_y = map.fetch(:scale_y, 1) alpha = map.fetch(:alpha, 0xff) color = map.fetch(:color, 0xffffff) angle = map.fetch(:angle, nil) flip = map.fetch(:flip, nil) z_index = map.fetch(:z_index, 0) round = map.fetch(:round, false) map = map.fetch(:map, nil) end color = (alpha << 24) | color if angle @img[@img_index].draw_rot @x - (map ? map.cam.x : 0) + @img[0].width * scale_x * 0.5, @y - (map ? map.cam.y : 0) + @img[0].height * scale_y * 0.5, z_index, angle, 0.5, 0.5, (flip == :horiz ? -scale_x : scale_x), (flip == :vert ? -scale_y : scale_y), color else x = @x - (map ? map.cam.x : 0) + (flip == :horiz ? scale_x * @img[0].width : 0) y = @y - (map ? map.cam.y : 0) + (flip == :vert ? scale_y * @img[0].height : 0) @img[@img_index].draw (round ? x.round : x), (round ? y.round : y), z_index, (flip == :horiz ? -scale_x : scale_x), (flip == :vert ? -scale_y : scale_y), color end end
ruby
{ "resource": "" }
q26731
MiniGL.Button.update
test
def update return unless @enabled and @visible mouse_over = Mouse.over? @x, @y, @w, @h mouse_press = Mouse.button_pressed? :left mouse_rel = Mouse.button_released? :left if @state == :up if mouse_over @img_index = 1 @state = :over else @img_index = 0 end elsif @state == :over if not mouse_over @img_index = 0 @state = :up elsif mouse_press @img_index = 2 @state = :down else @img_index = 1 end elsif @state == :down if not mouse_over @img_index = 0 @state = :down_out elsif mouse_rel @img_index = 1 @state = :over click else @img_index = 2 end else # :down_out if mouse_over @img_index = 2 @state = :down elsif mouse_rel @img_index = 0 @state = :up else @img_index = 0 end end end
ruby
{ "resource": "" }
q26732
MiniGL.Button.draw
test
def draw(alpha = 0xff, z_index = 0, color = 0xffffff) return unless @visible color = (alpha << 24) | color text_color = if @enabled if @state == :down @down_text_color else @state == :over ? @over_text_color : @text_color end else @disabled_text_color end text_color = (alpha << 24) | text_color @img[@img_index].draw @x, @y, z_index, @scale_x, @scale_y, color if @img if @text if @center_x or @center_y rel_x = @center_x ? 0.5 : 0 rel_y = @center_y ? 0.5 : 0 @font.draw_text_rel @text, @text_x, @text_y, z_index, rel_x, rel_y, @scale_x, @scale_y, text_color else @font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color end end end
ruby
{ "resource": "" }
q26733
MiniGL.TextField.text=
test
def text=(value, trigger_changed = true) @text = value[0...@max_length] @nodes.clear; @nodes << @text_x x = @nodes[0] @text.chars.each { |char| x += @font.text_width(char) * @scale_x @nodes << x } @cur_node = @nodes.size - 1 @anchor1 = nil @anchor2 = nil set_cursor_visible @on_text_changed.call @text, @params if trigger_changed && @on_text_changed end
ruby
{ "resource": "" }
q26734
MiniGL.TextField.set_position
test
def set_position(x, y) d_x = x - @x d_y = y - @y @x = x; @y = y @text_x += d_x @text_y += d_y @nodes.map! do |n| n + d_x end end
ruby
{ "resource": "" }
q26735
MiniGL.TextField.draw
test
def draw(alpha = 0xff, z_index = 0, color = 0xffffff, disabled_color = 0x808080) return unless @visible color = (alpha << 24) | ((@enabled or @disabled_img) ? color : disabled_color) text_color = (alpha << 24) | (@enabled ? @text_color : @disabled_text_color) img = ((@enabled or @disabled_img.nil?) ? @img : @disabled_img) img.draw @x, @y, z_index, @scale_x, @scale_y, color @font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color if @anchor1 and @anchor2 selection_color = ((alpha / 2) << 24) | @selection_color G.window.draw_quad @nodes[@anchor1], @text_y, selection_color, @nodes[@anchor2] + 1, @text_y, selection_color, @nodes[@anchor2] + 1, @text_y + @font.height * @scale_y, selection_color, @nodes[@anchor1], @text_y + @font.height * @scale_y, selection_color, z_index end if @cursor_visible if @cursor_img @cursor_img.draw @nodes[@cur_node] - (@cursor_img.width * @scale_x) / 2, @text_y, z_index, @scale_x, @scale_y else cursor_color = alpha << 24 G.window.draw_quad @nodes[@cur_node], @text_y, cursor_color, @nodes[@cur_node] + 1, @text_y, cursor_color, @nodes[@cur_node] + 1, @text_y + @font.height * @scale_y, cursor_color, @nodes[@cur_node], @text_y + @font.height * @scale_y, cursor_color, z_index end end end
ruby
{ "resource": "" }
q26736
MiniGL.ProgressBar.draw
test
def draw(alpha = 0xff, z_index = 0, color = 0xffffff) return unless @visible if @bg c = (alpha << 24) | color @bg.draw @x, @y, z_index, @scale_x, @scale_y, c else c = (alpha << 24) | @bg_color G.window.draw_quad @x, @y, c, @x + @w, @y, c, @x + @w, @y + @h, c, @x, @y + @h, c, z_index end if @fg c = (alpha << 24) | color w1 = @fg.width * @scale_x w2 = (@value.to_f / @max_value * @w).round x0 = @x + @fg_margin_x x = 0 while x <= w2 - w1 @fg.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c x += w1 end if w2 - x > 0 img = Gosu::Image.new(@fg_path, tileable: true, retro: @retro, rect: [0, 0, ((w2 - x) / @scale_x).round, @fg.height]) img.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c end else c = (alpha << 24) | @fg_color rect_r = @x + (@value.to_f / @max_value * @w).round G.window.draw_quad @x, @y, c, rect_r, @y, c, rect_r, @y + @h, c, @x, @y + @h, c, z_index end if @font c = (alpha << 24) | @text_color @text = @format == '%' ? "#{(@value.to_f / @max_value * 100).round}%" : "#{@value}/#{@max_value}" @font.draw_text_rel @text, @x + @w / 2, @y + @h / 2, z_index, 0.5, 0.5, @scale_x, @scale_y, c end end
ruby
{ "resource": "" }
q26737
MiniGL.DropDownList.update
test
def update return unless @enabled and @visible if @open and Mouse.button_pressed? :left and not Mouse.over?(@x, @y, @w, @max_h) toggle return end @buttons.each { |b| b.update } end
ruby
{ "resource": "" }
q26738
MiniGL.DropDownList.value=
test
def value=(val) if @options.include? val old = @value @value = @buttons[0].text = val @on_changed.call(old, val) if @on_changed end end
ruby
{ "resource": "" }
q26739
MiniGL.DropDownList.draw
test
def draw(alpha = 0xff, z_index = 0, color = 0xffffff, over_color = 0xcccccc) return unless @visible unless @img bottom = @y + (@open ? @max_h : @h) + @scale_y b_color = (alpha << 24) G.window.draw_quad @x - @scale_x, @y - @scale_y, b_color, @x + @w + @scale_x, @y - @scale_y, b_color, @x + @w + @scale_x, bottom, b_color, @x - @scale_x, bottom, b_color, z_index @buttons.each do |b| c = (alpha << 24) | (b.state == :over ? over_color : color) G.window.draw_quad b.x, b.y, c, b.x + b.w, b.y, c, b.x + b.w, b.y + b.h, c, b.x, b.y + b.h, c, z_index + 1 if b.visible end end @buttons[0].draw(alpha, z_index, color) @buttons[1..-1].each { |b| b.draw alpha, z_index + 1, color } end
ruby
{ "resource": "" }
q26740
MiniGL.Label.draw
test
def draw(alpha = 255, z_index = 0, color = 0xffffff) c = @enabled ? @text_color : @disabled_text_color r1 = c >> 16 g1 = (c & 0xff00) >> 8 b1 = (c & 0xff) r2 = color >> 16 g2 = (color & 0xff00) >> 8 b2 = (color & 0xff) r1 *= r2; r1 /= 255 g1 *= g2; g1 /= 255 b1 *= b2; b1 /= 255 color = (alpha << 24) | (r1 << 16) | (g1 << 8) | b1 @font.draw_text(@text, @x, @y, z_index, @scale_x, @scale_y, color) end
ruby
{ "resource": "" }
q26741
MiniGL.TextHelper.write_line
test
def write_line(text, x = nil, y = nil, mode = :left, color = 0, alpha = 0xff, effect = nil, effect_color = 0, effect_size = 1, effect_alpha = 0xff, z_index = 0) if text.is_a? Hash x = text[:x] y = text[:y] mode = text.fetch(:mode, :left) color = text.fetch(:color, 0) alpha = text.fetch(:alpha, 0xff) effect = text.fetch(:effect, nil) effect_color = text.fetch(:effect_color, 0) effect_size = text.fetch(:effect_size, 1) effect_alpha = text.fetch(:effect_alpha, 0xff) z_index = text.fetch(:z_index, 0) text = text[:text] end color = (alpha << 24) | color rel = case mode when :left then 0 when :center then 0.5 when :right then 1 else 0 end if effect effect_color = (effect_alpha << 24) | effect_color if effect == :border @font.draw_markup_rel text, x - effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x, y - effect_size, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x + effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x + effect_size, y, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x + effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x, y + effect_size, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x - effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color @font.draw_markup_rel text, x - effect_size, y, z_index, rel, 0, 1, 1, effect_color elsif effect == :shadow @font.draw_markup_rel text, x + effect_size, y + effect_size, z_index, rel, 0, 1, 1, effect_color end end @font.draw_markup_rel text, x, y, z_index, rel, 0, 1, 1, color end
ruby
{ "resource": "" }
q26742
MiniGL.TextHelper.write_breaking
test
def write_breaking(text, x, y, width, mode = :left, color = 0, alpha = 0xff, z_index = 0) color = (alpha << 24) | color text.split("\n").each do |p| if mode == :justified y = write_paragraph_justified p, x, y, width, color, z_index else rel = case mode when :left then 0 when :center then 0.5 when :right then 1 else 0 end y = write_paragraph p, x, y, width, rel, color, z_index end end end
ruby
{ "resource": "" }
q26743
Fit4Ruby.FitMessageIdMapper.add_global
test
def add_global(message) unless (slot = @entries.index { |e| e.nil? }) # No more free slots. We have to find the least recently used one. slot = 0 0.upto(15) do |i| if i != slot && @entries[slot].last_use > @entries[i].last_use slot = i end end end @entries[slot] = Entry.new(message, Time.now) slot end
ruby
{ "resource": "" }
q26744
Fit4Ruby.FitMessageIdMapper.get_local
test
def get_local(message) 0.upto(15) do |i| if (entry = @entries[i]) && entry.global_message == message entry.last_use = Time.now return i end end nil end
ruby
{ "resource": "" }
q26745
Fit4Ruby.Monitoring_B.check
test
def check last_timestamp = ts_16_offset = nil last_ts_16 = nil # The timestamp_16 is a 2 byte time stamp value that is used instead of # the 4 byte timestamp field for monitoring records that have # current_activity_type_intensity values with an activity type of 6. The # value seems to be in seconds, but the 0 value reference does not seem # to be included in the file. However, it can be approximated using the # surrounding timestamp values. @monitorings.each do |record| if last_ts_16 && ts_16_offset && record.timestamp_16 && record.timestamp_16 < last_ts_16 # Detect timestamp_16 wrap-arounds. timestamp_16 is a 16 bit value. # In case of a wrap-around we adjust the ts_16_offset accordingly. ts_16_offset += 2 ** 16 end if ts_16_offset # We have already found the offset. Adjust all timestamps according # to 'offset + timestamp_16' if record.timestamp_16 record.timestamp = ts_16_offset + record.timestamp_16 last_ts_16 = record.timestamp_16 end else # We are still looking for the offset. if record.timestamp_16 && last_timestamp # We have a previous timestamp and found the first record with a # timestamp_16 value set. We assume that the timestamp of this # record is one minute after the previously found timestamp. # That's just a guess. Who knows what the Garmin engineers were # thinking here? ts_16_offset = last_timestamp + 60 - record.timestamp_16 record.timestamp = ts_16_offset + record.timestamp_16 last_ts_16 = record.timestamp_16 else # Just save the timestamp of the current record. last_timestamp = record.timestamp end end end end
ruby
{ "resource": "" }
q26746
Fit4Ruby.FieldDescription.create_global_definition
test
def create_global_definition(fit_entity) messages = fit_entity.developer_fit_messages unless (gfm = GlobalFitMessages[@native_mesg_num]) Log.error "Developer field description references unknown global " + "message number #{@native_mesg_num}" return end if @developer_data_index >= fit_entity.top_level_record.developer_data_ids.size Log.error "Developer data index #{@developer_data_index} is too large" return end msg = messages[@native_mesg_num] || messages.message(@native_mesg_num, gfm.name) unless (@fit_base_type_id & 0x7F) < FIT_TYPE_DEFS.size Log.error "fit_base_type_id #{@fit_base_type_id} is too large" return end options = {} options[:scale] = @scale if @scale options[:offset] = @offset if @offset options[:array] = @array if @array options[:unit] = @units msg.field(@field_definition_number, FIT_TYPE_DEFS[@fit_base_type_id & 0x7F][1], "_#{@developer_data_index}_#{@field_name}", options) end
ruby
{ "resource": "" }
q26747
Fit4Ruby.DeviceInfo.check
test
def check(index) unless @device_index Log.fatal 'device info record must have a device_index' end if @device_index == 0 unless @manufacturer Log.fatal 'device info record 0 must have a manufacturer field set' end if @manufacturer == 'garmin' unless @garmin_product Log.fatal 'device info record 0 must have a garman_product ' + 'field set' end else unless @product Log.fatal 'device info record 0 must have a product field set' end end if @serial_number.nil? Log.fatal 'device info record 0 must have a serial number set' end end end
ruby
{ "resource": "" }
q26748
Fit4Ruby.ILogger.open
test
def open(io) begin @@logger = Logger.new(io) rescue => e @@logger = Logger.new($stderr) Log.fatal "Cannot open log file: #{e.message}" end end
ruby
{ "resource": "" }
q26749
Fit4Ruby.FitFileEntity.set_type
test
def set_type(type) if @top_level_record Log.fatal "FIT file type has already been set to " + "#{@top_level_record.class}" end case type when 4, 'activity' @top_level_record = Activity.new @type = 'activity' when 32, 'monitoring_b' @top_level_record = Monitoring_B.new @type = 'monitoring_b' when 44, 'metrics' @top_level_record = Metrics.new @type = 'metrics' else Log.error "Unsupported FIT file type #{type}" return nil end @top_level_record end
ruby
{ "resource": "" }
q26750
Fit4Ruby.Activity.check
test
def check unless @timestamp && @timestamp >= Time.parse('1990-01-01T00:00:00+00:00') Log.fatal "Activity has no valid timestamp" end unless @total_timer_time Log.fatal "Activity has no valid total_timer_time" end unless @device_infos.length > 0 Log.fatal "Activity must have at least one device_info section" end @device_infos.each.with_index { |d, index| d.check(index) } @sensor_settings.each.with_index { |s, index| s.check(index) } unless @num_sessions == @sessions.count Log.fatal "Activity record requires #{@num_sessions}, but " "#{@sessions.length} session records were found in the " "FIT file." end # Records must have consecutively growing timestamps and distances. ts = Time.parse('1989-12-31') distance = nil invalid_records = [] @records.each_with_index do |r, idx| Log.fatal "Record has no timestamp" unless r.timestamp if r.timestamp < ts Log.fatal "Record has earlier timestamp than previous record" end if r.distance if distance && r.distance < distance # Normally this should be a fatal error as the FIT file is clearly # broken. Unfortunately, the Skiing/Boarding app in the Fenix3 # produces such broken FIT files. So we just warn about this # problem and discard the earlier records. Log.error "Record #{r.timestamp} has smaller distance " + "(#{r.distance}) than an earlier record (#{distance})." # Index of the list record to be discarded. (idx - 1).downto(0) do |i| if (ri = @records[i]).distance > r.distance # This is just an approximation. It looks like the app adds # records to the FIT file for runs that it meant to discard. # Maybe the two successive time start events are a better # criteria. But this workaround works for now. invalid_records << ri else # All broken records have been found. break end end end distance = r.distance end ts = r.timestamp end unless invalid_records.empty? # Delete all the broken records from the @records Array. Log.warn "Discarding #{invalid_records.length} earlier records" @records.delete_if { |r| invalid_records.include?(r) } end # Laps must have a consecutively growing message index. @laps.each.with_index do |lap, index| lap.check(index) # If we have heart rate zone records, there should be one for each # lap @heart_rate_zones[index].check(index) if @heart_rate_zones[index] end @sessions.each { |s| s.check(self) } end
ruby
{ "resource": "" }
q26751
Fit4Ruby.Activity.total_gps_distance
test
def total_gps_distance timer_stops = [] # Generate a list of all timestamps where the timer was stopped. @events.each do |e| if e.event == 'timer' && e.event_type == 'stop_all' timer_stops << e.timestamp end end # The first record of a FIT file can already have a distance associated # with it. The GPS location of the first record is not where the start # button was pressed. This introduces a slight inaccurcy when computing # the total distance purely on the GPS coordinates found in the records. d = 0.0 last_lat = last_long = nil last_timestamp = nil # Iterate over all the records and accumlate the distances between the # neiboring coordinates. @records.each do |r| if (lat = r.position_lat) && (long = r.position_long) if last_lat && last_long distance = Fit4Ruby::GeoMath.distance(last_lat, last_long, lat, long) d += distance end if last_timestamp speed = distance / (r.timestamp - last_timestamp) end if timer_stops[0] == r.timestamp # If a stop event was found for this record timestamp we clear the # last_* values so that the distance covered while being stopped # is not added to the total. last_lat = last_long = nil last_timestamp = nil timer_stops.shift else last_lat = lat last_long = long last_timestamp = r.timestamp end end end d end
ruby
{ "resource": "" }
q26752
Fit4Ruby.Activity.vo2max
test
def vo2max # First check the event log for a vo2max reporting event. @events.each do |e| return e.vo2max if e.event == 'vo2max' end # Then check the user_data entries for a metmax entry. METmax * 3.5 # is same value as VO2max. @user_data.each do |u| return u.metmax * 3.5 if u.metmax end nil end
ruby
{ "resource": "" }
q26753
Fit4Ruby.Activity.write
test
def write(io, id_mapper) @file_id.write(io, id_mapper) @file_creator.write(io, id_mapper) (@field_descriptions + @developer_data_ids + @device_infos + @sensor_settings + @data_sources + @user_profiles + @physiological_metrics + @events + @sessions + @laps + @records + @heart_rate_zones + @personal_records).sort.each do |s| s.write(io, id_mapper) end super end
ruby
{ "resource": "" }
q26754
Fit4Ruby.Activity.new_fit_data_record
test
def new_fit_data_record(record_type, field_values = {}) case record_type when 'file_id' @file_id = (record = FileId.new(field_values)) when 'field_description' @field_descriptions << (record = FieldDescription.new(field_values)) when 'developer_data_id' @developer_data_ids << (record = DeveloperDataId.new(field_values)) when 'epo_data' @epo_data = (record = EPO_Data.new(field_values)) when 'file_creator' @file_creator = (record = FileCreator.new(field_values)) when 'device_info' @device_infos << (record = DeviceInfo.new(field_values)) when 'sensor_settings' @sensor_settings << (record = SensorSettings.new(field_values)) when 'data_sources' @data_sources << (record = DataSources.new(field_values)) when 'user_data' @user_data << (record = UserData.new(field_values)) when 'user_profile' @user_profiles << (record = UserProfile.new(field_values)) when 'physiological_metrics' @physiological_metrics << (record = PhysiologicalMetrics.new(field_values)) when 'event' @events << (record = Event.new(field_values)) when 'session' unless @cur_lap_records.empty? # Copy selected fields from section to lap. lap_field_values = {} [ :timestamp, :sport ].each do |f| lap_field_values[f] = field_values[f] if field_values.include?(f) end # Ensure that all previous records have been assigned to a lap. record = create_new_lap(lap_field_values) end @num_sessions += 1 @sessions << (record = Session.new(@cur_session_laps, @lap_counter, field_values)) @cur_session_laps = [] when 'lap' record = create_new_lap(field_values) when 'record' @cur_lap_records << (record = Record.new(field_values)) @records << record when 'hrv' @hrv << (record = HRV.new(field_values)) when 'heart_rate_zones' @heart_rate_zones << (record = HeartRateZones.new(field_values)) when 'personal_records' @personal_records << (record = PersonalRecords.new(field_values)) else record = nil end record end
ruby
{ "resource": "" }
q26755
Fit4Ruby.Session.check
test
def check(activity) unless @first_lap_index Log.fatal 'first_lap_index is not set' end unless @num_laps Log.fatal 'num_laps is not set' end @first_lap_index.upto(@first_lap_index - @num_laps) do |i| if (lap = activity.lap[i]) @laps << lap else Log.fatal "Session references lap #{i} which is not contained in " "the FIT file." end end end
ruby
{ "resource": "" }
q26756
Fit4Ruby.GlobalFitMessage.field
test
def field(number, type, name, opts = {}) field = Field.new(type, name, opts) register_field_by_name(field, name) register_field_by_number(field, number) end
ruby
{ "resource": "" }
q26757
Fit4Ruby.GlobalFitMessage.alt_field
test
def alt_field(number, ref_field, &block) unless @fields_by_name.include?(ref_field) raise "Unknown ref_field: #{ref_field}" end field = AltField.new(self, ref_field, &block) register_field_by_number(field, number) end
ruby
{ "resource": "" }
q26758
MailForm.Delivery.spam?
test
def spam? self.class.mail_captcha.each do |field| next if send(field).blank? if defined?(Rails) && Rails.env.development? raise ScriptError, "The captcha field #{field} was supposed to be blank" else return true end end false end
ruby
{ "resource": "" }
q26759
MailForm.Delivery.deliver!
test
def deliver! mailer = MailForm::Notifier.contact(self) if mailer.respond_to?(:deliver_now) mailer.deliver_now else mailer.deliver end end
ruby
{ "resource": "" }
q26760
MailForm.Delivery.mail_form_attributes
test
def mail_form_attributes self.class.mail_attributes.each_with_object({}) do |attr, hash| hash[attr.to_s] = send(attr) end end
ruby
{ "resource": "" }
q26761
SolrWrapper.Instance.start
test
def start extract_and_configure if config.managed? exec('start', p: port, c: config.cloud) # Wait for solr to start unless status sleep config.poll_interval end after_start end end
ruby
{ "resource": "" }
q26762
SolrWrapper.Instance.restart
test
def restart if config.managed? && started? exec('restart', p: port, c: config.cloud) end end
ruby
{ "resource": "" }
q26763
SolrWrapper.Instance.create
test
def create(options = {}) options[:name] ||= SecureRandom.hex create_options = { p: port } create_options[:c] = options[:name] if options[:name] create_options[:n] = options[:config_name] if options[:config_name] create_options[:d] = options[:dir] if options[:dir] Retriable.retriable do raise "Not started yet" unless started? end # short-circuit if we're using persisted data with an existing core/collection return if options[:persist] && create_options[:c] && client.exists?(create_options[:c]) exec("create", create_options) options[:name] end
ruby
{ "resource": "" }
q26764
SolrWrapper.Instance.upconfig
test
def upconfig(options = {}) options[:name] ||= SecureRandom.hex options[:zkhost] ||= zkhost upconfig_options = { upconfig: true, n: options[:name] } upconfig_options[:d] = options[:dir] if options[:dir] upconfig_options[:z] = options[:zkhost] if options[:zkhost] exec 'zk', upconfig_options options[:name] end
ruby
{ "resource": "" }
q26765
SolrWrapper.Instance.downconfig
test
def downconfig(options = {}) options[:name] ||= SecureRandom.hex options[:zkhost] ||= zkhost downconfig_options = { downconfig: true, n: options[:name] } downconfig_options[:d] = options[:dir] if options[:dir] downconfig_options[:z] = options[:zkhost] if options[:zkhost] exec 'zk', downconfig_options options[:name] end
ruby
{ "resource": "" }
q26766
SolrWrapper.Instance.with_collection
test
def with_collection(options = {}) options = config.collection_options.merge(options) return yield if options.empty? name = create(options) begin yield name ensure delete name unless options[:persist] end end
ruby
{ "resource": "" }
q26767
SolrWrapper.Instance.clean!
test
def clean! stop remove_instance_dir! FileUtils.remove_entry(config.download_dir, true) if File.exist?(config.download_dir) FileUtils.remove_entry(config.tmp_save_dir, true) if File.exist? config.tmp_save_dir checksum_validator.clean! FileUtils.remove_entry(config.version_file) if File.exist? config.version_file end
ruby
{ "resource": "" }
q26768
Qt.MetaInfo.get_signals
test
def get_signals all_signals = [] current = @klass while current != Qt::Base meta = Meta[current.name] if !meta.nil? all_signals.concat meta.signals end current = current.superclass end return all_signals end
ruby
{ "resource": "" }
q26769
MotionSupport.Duration.+
test
def +(other) if Duration === other Duration.new(value + other.value, @parts + other.parts) else Duration.new(value + other, @parts + [[:seconds, other]]) end end
ruby
{ "resource": "" }
q26770
DateAndTime.Calculations.days_to_week_start
test
def days_to_week_start(start_day = Date.beginning_of_week) start_day_number = DAYS_INTO_WEEK[start_day] current_day_number = wday != 0 ? wday - 1 : 6 (current_day_number - start_day_number) % 7 end
ruby
{ "resource": "" }
q26771
TTY.ProgressBar.reset
test
def reset @width = 0 if no_width @render_period = frequency == 0 ? 0 : 1.0 / frequency @current = 0 @last_render_time = Time.now @last_render_width = 0 @done = false @stopped = false @start_at = Time.now @started = false @tokens = {} @meter.clear end
ruby
{ "resource": "" }
q26772
TTY.ProgressBar.advance
test
def advance(progress = 1, tokens = {}) return if done? synchronize do emit(:progress, progress) if progress.respond_to?(:to_hash) tokens, progress = progress, 1 end @start_at = Time.now if @current.zero? && !@started @current += progress @tokens = tokens @meter.sample(Time.now, progress) if !no_width && @current >= total finish && return end now = Time.now return if (now - @last_render_time) < @render_period render end end
ruby
{ "resource": "" }
q26773
TTY.ProgressBar.iterate
test
def iterate(collection, progress = 1, &block) update(total: collection.count * progress) unless total progress_enum = Enumerator.new do |iter| collection.each do |elem| advance(progress) iter.yield(elem) end end block_given? ? progress_enum.each(&block) : progress_enum end
ruby
{ "resource": "" }
q26774
TTY.ProgressBar.update
test
def update(options = {}) synchronize do options.each do |name, val| if @configuration.respond_to?("#{name}=") @configuration.public_send("#{name}=", val) end end end end
ruby
{ "resource": "" }
q26775
TTY.ProgressBar.render
test
def render return if done? if hide_cursor && @last_render_width == 0 && !(@current >= total) write(TTY::Cursor.hide) end if @multibar characters_in = @multibar.line_inset(self) update(inset: self.class.display_columns(characters_in)) end formatted = @formatter.decorate(self, @format) @tokens.each do |token, val| formatted = formatted.gsub(":#{token}", val) end padded = padout(formatted) write(padded, true) @last_render_time = Time.now @last_render_width = self.class.display_columns(formatted) end
ruby
{ "resource": "" }
q26776
TTY.ProgressBar.move_to_row
test
def move_to_row if @multibar CURSOR_LOCK.synchronize do if @first_render @row = @multibar.next_row yield if block_given? output.print "\n" @first_render = false else lines_up = (@multibar.rows + 1) - @row output.print TTY::Cursor.save output.print TTY::Cursor.up(lines_up) yield if block_given? output.print TTY::Cursor.restore end end else yield if block_given? end end
ruby
{ "resource": "" }
q26777
TTY.ProgressBar.write
test
def write(data, clear_first = false) return unless tty? # write only to terminal move_to_row do output.print(TTY::Cursor.column(1)) if clear_first characters_in = @multibar.line_inset(self) if @multibar output.print("#{characters_in}#{data}") output.flush end end
ruby
{ "resource": "" }
q26778
TTY.ProgressBar.finish
test
def finish return if done? @current = total unless no_width render clear ? clear_line : write("\n", false) ensure @meter.clear @done = true # reenable cursor if it is turned off if hide_cursor && @last_render_width != 0 write(TTY::Cursor.show, false) end emit(:done) end
ruby
{ "resource": "" }
q26779
TTY.ProgressBar.stop
test
def stop # reenable cursor if it is turned off if hide_cursor && @last_render_width != 0 write(TTY::Cursor.show, false) end return if done? render clear ? clear_line : write("\n", false) ensure @meter.clear @stopped = true emit(:stopped) end
ruby
{ "resource": "" }
q26780
TTY.ProgressBar.log
test
def log(message) sanitized_message = message.gsub(/\r|\n/, ' ') if done? write(sanitized_message + "\n", false) return end sanitized_message = padout(sanitized_message) write(sanitized_message + "\n", true) render end
ruby
{ "resource": "" }
q26781
TTY.ProgressBar.padout
test
def padout(message) message_length = self.class.display_columns(message) if @last_render_width > message_length remaining_width = @last_render_width - message_length message += ' ' * remaining_width end message end
ruby
{ "resource": "" }
q26782
Delayed.Job.lock_exclusively!
test
def lock_exclusively!(max_run_time, worker = worker_name) now = self.class.db_time_now affected_rows = if locked_by != worker # We don't own this job so we will update the locked_by name and the locked_at self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?)", id, (now - max_run_time.to_i)]) else # We already own this job, this may happen if the job queue crashes. # Simply resume and update the locked_at self.class.update_all(["locked_at = ?", now], ["id = ? and locked_by = ?", id, worker]) end if affected_rows == 1 self.locked_at = now self.locked_by = worker return true else return false end end
ruby
{ "resource": "" }
q26783
Elephrame.Trace.setup_tracery
test
def setup_tracery dir_path raise "Provided path not a directory" unless Dir.exist?(dir_path) @grammar = {} Dir.open(dir_path) do |dir| dir.each do |file| # skip our current and parent dir next if file =~ /^\.\.?$/ # read the rule file into the files hash @grammar[file.split('.').first] = createGrammar(JSON.parse(File.read("#{dir_path}/#{file}"))) end end # go ahead and makes a default mention-handler # if we have a reply rule file unless @grammar['reply'].nil? on_reply { |bot| bot.reply_with_mentions('#default#', rules: 'reply') } end end
ruby
{ "resource": "" }
q26784
Elephrame.Trace.expand_and_post
test
def expand_and_post(text, *options) opts = Hash[*options] rules = opts.fetch(:rules, 'default') actually_post(@grammar[rules].flatten(text), **opts.reject {|k| k == :rules }) end
ruby
{ "resource": "" }
q26785
Elephrame.AllInteractions.run_interact
test
def run_interact @streamer.user do |update| if update.kind_of? Mastodon::Notification case update.type when 'mention' # this makes it so .content calls strip instead update.status.class.module_eval { alias_method :content, :strip } if @strip_html store_mention_data update.status @on_reply.call(self, update.status) unless @on_reply.nil? when 'reblog' @on_boost.call(self, update) unless @on_boost.nil? when 'favourite' @on_fave.call(self, update) unless @on_fave.nil? when 'follow' @on_follow.call(self, update) unless @on_follow.nil? end end end end
ruby
{ "resource": "" }
q26786
Elephrame.Reply.reply
test
def reply(text, *options) options = Hash[*options] post("@#{@mention_data[:account].acct} #{text}", **@mention_data.merge(options).reject { |k| k == :mentions or k == :account }) end
ruby
{ "resource": "" }
q26787
Elephrame.Reply.run_reply
test
def run_reply @streamer.user do |update| next unless update.kind_of? Mastodon::Notification and update.type == 'mention' # this makes it so .content calls strip instead update.status.class.module_eval { alias_method :content, :strip } if @strip_html store_mention_data update.status if block_given? yield(self, update.status) else @on_reply.call(self, update.status) end end end
ruby
{ "resource": "" }
q26788
Elephrame.Reply.store_mention_data
test
def store_mention_data(mention) @mention_data = { reply_id: mention.id, visibility: mention.visibility, spoiler: mention.spoiler_text, hide_media: mention.sensitive?, mentions: mention.mentions, account: mention.account } end
ruby
{ "resource": "" }
q26789
Elephrame.Streaming.setup_streaming
test
def setup_streaming stream_uri = @client.instance() .attributes['urls']['streaming_api'].gsub(/^wss?/, 'https') @streamer = Mastodon::Streaming::Client.new(base_url: stream_uri, bearer_token: ENV['TOKEN']) end
ruby
{ "resource": "" }
q26790
PoiseService.Utils.parse_service_name
test
def parse_service_name(path) parts = Pathname.new(path).each_filename.to_a.reverse! # Find the last segment not in common segments, fall back to the last segment. parts.find {|seg| !COMMON_SEGMENTS[seg] } || parts.first end
ruby
{ "resource": "" }
q26791
Net.TCPClient.connect
test
def connect start_time = Time.now retries = 0 close # Number of times to try begin connect_to_server(servers, policy) logger.info(message: "Connected to #{address}", duration: (Time.now - start_time) * 1000) if respond_to?(:logger) rescue ConnectionFailure, ConnectionTimeout => exception cause = exception.is_a?(ConnectionTimeout) ? exception : exception.cause # Retry-able? if self.class.reconnect_on_errors.include?(cause.class) && (retries < connect_retry_count.to_i) retries += 1 logger.warn "#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}" if respond_to?(:logger) sleep(connect_retry_interval) retry else message = "#connect Failed to connect to any of #{servers.join(',')} after #{retries} retries. #{exception.class}: #{exception.message}" logger.benchmark_error(message, exception: exception, duration: (Time.now - start_time)) if respond_to?(:logger) raise ConnectionFailure.new(message, address.to_s, cause) end end end
ruby
{ "resource": "" }
q26792
Net.TCPClient.write
test
def write(data, timeout = write_timeout) data = data.to_s if respond_to?(:logger) payload = {timeout: timeout} # With trace level also log the sent data payload[:data] = data if logger.trace? logger.benchmark_debug('#write', payload: payload) do payload[:bytes] = socket_write(data, timeout) end else socket_write(data, timeout) end rescue Exception => exc close if close_on_error raise exc end
ruby
{ "resource": "" }
q26793
Net.TCPClient.read
test
def read(length, buffer = nil, timeout = read_timeout) if respond_to?(:logger) payload = {bytes: length, timeout: timeout} logger.benchmark_debug('#read', payload: payload) do data = socket_read(length, buffer, timeout) # With trace level also log the received data payload[:data] = data if logger.trace? data end else socket_read(length, buffer, timeout) end rescue Exception => exc close if close_on_error raise exc end
ruby
{ "resource": "" }
q26794
Net.TCPClient.close
test
def close socket.close if socket && !socket.closed? @socket = nil @address = nil true rescue IOError => exception logger.warn "IOError when attempting to close socket: #{exception.class}: #{exception.message}" if respond_to?(:logger) false end
ruby
{ "resource": "" }
q26795
Net.TCPClient.alive?
test
def alive? return false if socket.nil? || closed? if IO.select([socket], nil, nil, 0) !socket.eof? rescue false else true end rescue IOError false end
ruby
{ "resource": "" }
q26796
Net.TCPClient.socket_connect
test
def socket_connect(socket, address, timeout) socket_address = Socket.pack_sockaddr_in(address.port, address.ip_address) # Timeout of -1 means wait forever for a connection return socket.connect(socket_address) if timeout == -1 deadline = Time.now.utc + timeout begin non_blocking(socket, deadline) { socket.connect_nonblock(socket_address) } rescue Errno::EISCONN # Connection was successful. rescue NonBlockingTimeout raise ConnectionTimeout.new("Timed out after #{timeout} seconds trying to connect to #{address}") rescue SystemCallError, IOError => exception message = "#connect Connection failure connecting to '#{address.to_s}': #{exception.class}: #{exception.message}" logger.error message if respond_to?(:logger) raise ConnectionFailure.new(message, address.to_s, exception) end end
ruby
{ "resource": "" }
q26797
Net.TCPClient.socket_write
test
def socket_write(data, timeout) if timeout < 0 socket.write(data) else deadline = Time.now.utc + timeout length = data.bytesize total_count = 0 non_blocking(socket, deadline) do loop do begin count = socket.write_nonblock(data) rescue Errno::EWOULDBLOCK retry end total_count += count return total_count if total_count >= length data = data.byteslice(count..-1) end end end rescue NonBlockingTimeout logger.warn "#write Timeout after #{timeout} seconds" if respond_to?(:logger) raise WriteTimeout.new("Timed out after #{timeout} seconds trying to write to #{address}") rescue SystemCallError, IOError => exception message = "#write Connection failure while writing to '#{address.to_s}': #{exception.class}: #{exception.message}" logger.error message if respond_to?(:logger) raise ConnectionFailure.new(message, address.to_s, exception) end
ruby
{ "resource": "" }
q26798
Net.TCPClient.ssl_connect
test
def ssl_connect(socket, address, timeout) ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.set_params(ssl.is_a?(Hash) ? ssl : {}) ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context) ssl_socket.hostname = address.host_name ssl_socket.sync_close = true begin if timeout == -1 # Timeout of -1 means wait forever for a connection ssl_socket.connect else deadline = Time.now.utc + timeout begin non_blocking(socket, deadline) { ssl_socket.connect_nonblock } rescue Errno::EISCONN # Connection was successful. rescue NonBlockingTimeout raise ConnectionTimeout.new("SSL handshake Timed out after #{timeout} seconds trying to connect to #{address.to_s}") end end rescue SystemCallError, OpenSSL::SSL::SSLError, IOError => exception message = "#connect SSL handshake failure with '#{address.to_s}': #{exception.class}: #{exception.message}" logger.error message if respond_to?(:logger) raise ConnectionFailure.new(message, address.to_s, exception) end # Verify Peer certificate ssl_verify(ssl_socket, address) if ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE ssl_socket end
ruby
{ "resource": "" }
q26799
Sonos.System.party_mode
test
def party_mode new_master = nil return nil unless speakers.length > 1 new_master = find_party_master if new_master.nil? party_over speakers.each do |slave| next if slave.uid == new_master.uid slave.join new_master end rescan @topology end
ruby
{ "resource": "" }