_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q15100
Authorization.Engine.flatten_privileges
train
def flatten_privileges (privileges, context = nil, flattened_privileges = Set.new) # TODO caching? raise AuthorizationUsageError, "No context given or inferable from object" unless context privileges.reject {|priv| flattened_privileges.include?(priv)}.each do |priv| flattened_privileges << priv flatten_privileges(rev_priv_hierarchy[[priv, nil]], context, flattened_privileges) if rev_priv_hierarchy[[priv, nil]] flatten_privileges(rev_priv_hierarchy[[priv, context]], context, flattened_privileges) if rev_priv_hierarchy[[priv, context]] end flattened_privileges.to_a end
ruby
{ "resource": "" }
q15101
Authorization.Attribute.obligation
train
def obligation (attr_validator, hash = nil) hash = (hash || @conditions_hash).clone hash.each do |attr, value| if value.is_a?(Hash) hash[attr] = obligation(attr_validator, value) elsif value.is_a?(Array) and value.length == 2 hash[attr] = [value[0], attr_validator.evaluate(value[1])] else raise AuthorizationError, "Wrong conditions hash format" end end hash end
ruby
{ "resource": "" }
q15102
Authorization.AttributeWithPermission.obligation
train
def obligation (attr_validator, hash_or_attr = nil, path = []) hash_or_attr ||= @attr_hash case hash_or_attr when Symbol @context ||= begin rule_model = attr_validator.context.to_s.classify.constantize context_reflection = self.class.reflection_for_path(rule_model, path + [hash_or_attr]) if context_reflection.klass.respond_to?(:decl_auth_context) context_reflection.klass.decl_auth_context else context_reflection.klass.name.tableize.to_sym end rescue # missing model, reflections hash_or_attr.to_s.pluralize.to_sym end obligations = attr_validator.engine.obligations(@privilege, :context => @context, :user => attr_validator.user) obligations.collect {|obl| {hash_or_attr => obl} } when Hash obligations_array_attrs = [] obligations = hash_or_attr.inject({}) do |all, pair| attr, sub_hash = pair all[attr] = obligation(attr_validator, sub_hash, path + [attr]) if all[attr].length > 1 obligations_array_attrs << attr else all[attr] = all[attr].first end all end obligations = [obligations] obligations_array_attrs.each do |attr| next_array_size = obligations.first[attr].length obligations = obligations.collect do |obls| (0...next_array_size).collect do |idx| obls_wo_array = obls.clone obls_wo_array[attr] = obls_wo_array[attr][idx] obls_wo_array end end.flatten end obligations when NilClass attr_validator.engine.obligations(@privilege, :context => attr_validator.context, :user => attr_validator.user) else raise AuthorizationError, "Wrong conditions hash format: #{hash_or_attr.inspect}" end end
ruby
{ "resource": "" }
q15103
Authorization.ObligationScope.parse!
train
def parse!( obligation ) @current_obligation = obligation @join_table_joins = Set.new obligation_conditions[@current_obligation] ||= {} follow_path( obligation ) rebuild_condition_options! rebuild_join_options! end
ruby
{ "resource": "" }
q15104
Authorization.ObligationScope.follow_path
train
def follow_path( steps, past_steps = [] ) if steps.is_a?( Hash ) steps.each do |step, next_steps| path_to_this_point = [past_steps, step].flatten reflection = reflection_for( path_to_this_point ) rescue nil if reflection follow_path( next_steps, path_to_this_point ) else follow_comparison( next_steps, past_steps, step ) end end elsif steps.is_a?( Array ) && steps.length == 2 if reflection_for( past_steps ) follow_comparison( steps, past_steps, :id ) else follow_comparison( steps, past_steps[0..-2], past_steps[-1] ) end else raise "invalid obligation path #{[past_steps, steps].inspect}" end end
ruby
{ "resource": "" }
q15105
Authorization.ObligationScope.add_obligation_condition_for
train
def add_obligation_condition_for( path, expression ) raise "invalid expression #{expression.inspect}" unless expression.is_a?( Array ) && expression.length == 3 add_obligation_join_for( path ) obligation_conditions[@current_obligation] ||= {} ( obligation_conditions[@current_obligation][path] ||= Set.new ) << expression end
ruby
{ "resource": "" }
q15106
Authorization.ObligationScope.model_for
train
def model_for (path) reflection = reflection_for(path) if Authorization.is_a_association_proxy?(reflection) if Rails.version < "3.2" reflection.proxy_reflection.klass else reflection.proxy_association.reflection.klass end elsif reflection.respond_to?(:klass) reflection.klass else reflection end end
ruby
{ "resource": "" }
q15107
Authorization.ObligationScope.reflection_for
train
def reflection_for(path, for_join_table_only = false) @join_table_joins << path if for_join_table_only and !reflections[path] reflections[path] ||= map_reflection_for( path ) end
ruby
{ "resource": "" }
q15108
Authorization.ObligationScope.map_reflection_for
train
def map_reflection_for( path ) raise "reflection for #{path.inspect} already exists" unless reflections[path].nil? reflection = path.empty? ? top_level_model : begin parent = reflection_for( path[0..-2] ) if !Authorization.is_a_association_proxy?(parent) and parent.respond_to?(:klass) parent.klass.reflect_on_association( path.last ) else parent.reflect_on_association( path.last ) end rescue parent.reflect_on_association( path.last ) end raise "invalid path #{path.inspect}" if reflection.nil? reflections[path] = reflection map_table_alias_for( path ) # Claim a table alias for the path. # Claim alias for join table # TODO change how this is checked if !Authorization.is_a_association_proxy?(reflection) and !reflection.respond_to?(:proxy_scope) and reflection.is_a?(ActiveRecord::Reflection::ThroughReflection) join_table_path = path[0..-2] + [reflection.options[:through]] reflection_for(join_table_path, true) end reflection end
ruby
{ "resource": "" }
q15109
Authorization.ObligationScope.map_table_alias_for
train
def map_table_alias_for( path ) return "table alias for #{path.inspect} already exists" unless table_aliases[path].nil? reflection = reflection_for( path ) table_alias = reflection.table_name if table_aliases.values.include?( table_alias ) max_length = reflection.active_record.connection.table_alias_length # Rails seems to pluralize reflection names table_alias = "#{reflection.name.to_s.pluralize}_#{reflection.active_record.table_name}".to(max_length-1) end while table_aliases.values.include?( table_alias ) if table_alias =~ /\w(_\d+?)$/ table_index = $1.succ table_alias = "#{table_alias[0..-(table_index.length+1)]}_#{table_index}" else table_alias = "#{table_alias[0..(max_length-3)]}_2" end end table_aliases[path] = table_alias end
ruby
{ "resource": "" }
q15110
Authorization.AuthorizationInModel.permitted_to?
train
def permitted_to? (privilege, options = {}, &block) options = { :user => Authorization.current_user, :object => self }.merge(options) Authorization::Engine.instance.permit?(privilege, {:user => options[:user], :object => options[:object]}, &block) end
ruby
{ "resource": "" }
q15111
Authorization.AuthorizationInController.has_role?
train
def has_role? (*roles, &block) user_roles = authorization_engine.roles_for(current_user) result = roles.all? do |role| user_roles.include?(role) end yield if result and block_given? result end
ruby
{ "resource": "" }
q15112
Authorization.AuthorizationInController.has_any_role?
train
def has_any_role?(*roles,&block) user_roles = authorization_engine.roles_for(current_user) result = roles.any? do |role| user_roles.include?(role) end yield if result and block_given? result end
ruby
{ "resource": "" }
q15113
Authorization.AuthorizationInController.has_role_with_hierarchy?
train
def has_role_with_hierarchy?(*roles, &block) user_roles = authorization_engine.roles_with_hierarchy_for(current_user) result = roles.all? do |role| user_roles.include?(role) end yield if result and block_given? result end
ruby
{ "resource": "" }
q15114
Authorization.AuthorizationInController.has_any_role_with_hierarchy?
train
def has_any_role_with_hierarchy?(*roles, &block) user_roles = authorization_engine.roles_with_hierarchy_for(current_user) result = roles.any? do |role| user_roles.include?(role) end yield if result and block_given? result end
ruby
{ "resource": "" }
q15115
Lita.Room.save
train
def save ensure_name_metadata_set redis.pipelined do redis.hmset("id:#{id}", *metadata.to_a.flatten) redis.set("name:#{name}", id) end end
ruby
{ "resource": "" }
q15116
Lita.Robot.join
train
def join(room) room_object = find_room(room) if room_object redis.sadd("persisted_rooms", room_object.id) adapter.join(room_object.id) else adapter.join(room) end end
ruby
{ "resource": "" }
q15117
Lita.Robot.part
train
def part(room) room_object = find_room(room) if room_object redis.srem("persisted_rooms", room_object.id) adapter.part(room_object.id) else adapter.part(room) end end
ruby
{ "resource": "" }
q15118
Lita.Robot.send_messages_with_mention
train
def send_messages_with_mention(target, *strings) return send_messages(target, *strings) if target.private_message? mention_name = target.user.mention_name prefixed_strings = strings.map do |s| "#{adapter.mention_format(mention_name).strip} #{s}" end send_messages(target, *prefixed_strings) end
ruby
{ "resource": "" }
q15119
Lita.Robot.trigger
train
def trigger(event_name, payload = {}) handlers.each do |handler| next unless handler.respond_to?(:trigger) handler.trigger(self, event_name, payload) end end
ruby
{ "resource": "" }
q15120
Lita.Robot.load_adapter
train
def load_adapter adapter_name = config.robot.adapter adapter_class = adapters[adapter_name.to_sym] unless adapter_class logger.fatal I18n.t("lita.robot.unknown_adapter", adapter: adapter_name) abort end adapter_class.new(self) end
ruby
{ "resource": "" }
q15121
Lita.Robot.run_app
train
def run_app http_config = config.http @server_thread = Thread.new do @server = Puma::Server.new(app) begin @server.add_tcp_listener(http_config.host, http_config.port.to_i) rescue Errno::EADDRINUSE, Errno::EACCES => e logger.fatal I18n.t( "lita.http.exception", message: e.message, backtrace: e.backtrace.join("\n") ) abort end @server.min_threads = http_config.min_threads @server.max_threads = http_config.max_threads @server.run end @server_thread.abort_on_exception = true end
ruby
{ "resource": "" }
q15122
Lita.HTTPRoute.register_route
train
def register_route(http_method, path, callback, options) route = new_route(http_method, path, callback, options) route.to(HTTPCallback.new(handler_class, callback)) handler_class.http_routes << route end
ruby
{ "resource": "" }
q15123
Lita.HTTPRoute.new_route
train
def new_route(http_method, path, callback, options) route = ExtendedRoute.new route.path = path route.name = callback.method_name route.add_match_with(options) route.add_request_method(http_method) route.add_request_method("HEAD") if http_method == "GET" route end
ruby
{ "resource": "" }
q15124
Lita.User.save
train
def save mention_name = metadata[:mention_name] || metadata["mention_name"] current_keys = metadata.keys redis_keys = redis.hkeys("id:#{id}") delete_keys = (redis_keys - current_keys) redis.pipelined do redis.hdel("id:#{id}", *delete_keys) if delete_keys.any? redis.hmset("id:#{id}", *metadata.to_a.flatten) redis.set("name:#{name}", id) redis.set("mention_name:#{mention_name}", id) if mention_name end end
ruby
{ "resource": "" }
q15125
Lita.Message.reply_privately
train
def reply_privately(*strings) private_source = source.clone private_source.private_message! @robot.send_messages(private_source, *strings) end
ruby
{ "resource": "" }
q15126
Lita.ConfigurationValidator.validate
train
def validate(type, plugin, attributes, attribute_namespace = []) attributes.each do |attribute| if attribute.children? validate(type, plugin, attribute.children, attribute_namespace.clone.push(attribute.name)) elsif attribute.required? && attribute.value.nil? registry.logger.fatal I18n.t( "lita.config.missing_required_#{type}_attribute", type => plugin.namespace, attribute: full_attribute_name(attribute_namespace, attribute.name) ) abort end end end
ruby
{ "resource": "" }
q15127
Lita.DefaultConfiguration.adapters_config
train
def adapters_config adapters = registry.adapters root.config :adapters do adapters.each do |key, adapter| combine(key, adapter.configuration_builder) end end end
ruby
{ "resource": "" }
q15128
Lita.DefaultConfiguration.handlers_config
train
def handlers_config handlers = registry.handlers root.config :handlers do handlers.each do |handler| if handler.configuration_builder.children? combine(handler.namespace, handler.configuration_builder) end end end end
ruby
{ "resource": "" }
q15129
Lita.DefaultConfiguration.http_config
train
def http_config root.config :http do config :host, type: String, default: "0.0.0.0" config :port, type: [Integer, String], default: 8080 config :min_threads, type: [Integer, String], default: 0 config :max_threads, type: [Integer, String], default: 16 config :middleware, type: MiddlewareRegistry, default: MiddlewareRegistry.new end end
ruby
{ "resource": "" }
q15130
Lita.DefaultConfiguration.robot_config
train
def robot_config root.config :robot do config :name, type: String, default: "Lita" config :mention_name, type: String config :alias, type: String config :adapter, types: [String, Symbol], default: :shell config :locale, types: [String, Symbol], default: I18n.locale config :log_level, types: [String, Symbol], default: :info do validate do |value| unless LOG_LEVELS.include?(value.to_s.downcase.strip) "must be one of: #{LOG_LEVELS.join(', ')}" end end end config :log_formatter, type: Proc, default: (lambda do |severity, datetime, _progname, msg| "[#{datetime.utc}] #{severity}: #{msg}\n" end) config :admins config :error_handler, default: ->(_error, _metadata) {} do validate do |value| "must respond to #call" unless value.respond_to?(:call) end end end end
ruby
{ "resource": "" }
q15131
Lita.Configurable.config
train
def config(*args, **kwargs, &block) if block configuration_builder.config(*args, **kwargs, &block) else configuration_builder.config(*args, **kwargs) end end
ruby
{ "resource": "" }
q15132
Lita.ConfigurationBuilder.config
train
def config(name, types: nil, type: nil, required: false, default: nil, &block) attribute = self.class.new attribute.name = name attribute.types = types || type attribute.required = required attribute.value = default attribute.instance_exec(&block) if block children << attribute end
ruby
{ "resource": "" }
q15133
Lita.ConfigurationBuilder.build_leaf
train
def build_leaf(object) this = self run_validator = method(:run_validator) check_types = method(:check_types) object.instance_exec do define_singleton_method(this.name) { this.value } define_singleton_method("#{this.name}=") do |value| run_validator.call(value) check_types.call(value) this.value = value end end object end
ruby
{ "resource": "" }
q15134
Lita.ConfigurationBuilder.build_nested
train
def build_nested(object) this = self nested_object = Configuration.new children.each { |child| child.build(nested_object) } object.instance_exec { define_singleton_method(this.name) { nested_object } } object end
ruby
{ "resource": "" }
q15135
Lita.ConfigurationBuilder.check_types
train
def check_types(value) if types&.none? { |type| type === value } Lita.logger.fatal( I18n.t("lita.config.type_error", attribute: name, types: types.join(", ")) ) raise ValidationError end end
ruby
{ "resource": "" }
q15136
Lita.RackApp.recognize
train
def recognize(env) env["lita.robot"] = robot recognized_routes_for(env).map { |match| match.route.name } end
ruby
{ "resource": "" }
q15137
Lita.RackApp.compile
train
def compile robot.handlers.each do |handler| next unless handler.respond_to?(:http_routes) handler.http_routes.each { |route| router.add_route(route) } end end
ruby
{ "resource": "" }
q15138
Lita.Authorization.user_in_group?
train
def user_in_group?(user, group) group = normalize_group(group) return user_is_admin?(user) if group == "admins" redis.sismember(group, user.id) end
ruby
{ "resource": "" }
q15139
Lita.Authorization.user_is_admin?
train
def user_is_admin?(user) Array(robot.config.robot.admins).include?(user.id) end
ruby
{ "resource": "" }
q15140
Lita.Authorization.groups_with_users
train
def groups_with_users groups.reduce({}) do |list, group| list[group] = redis.smembers(group).map do |user_id| User.find_by_id(user_id) end list end end
ruby
{ "resource": "" }
q15141
Lita.RouteValidator.passes_route_hooks?
train
def passes_route_hooks?(route, message, robot) robot.hooks[:validate_route].all? do |hook| hook.call(handler: handler, route: route, message: message, robot: robot) end end
ruby
{ "resource": "" }
q15142
Lita.RouteValidator.authorized?
train
def authorized?(robot, user, required_groups) required_groups.nil? || required_groups.any? do |group| robot.auth.user_in_group?(user, group) end end
ruby
{ "resource": "" }
q15143
Lita.Template.context_binding
train
def context_binding(variables) context = TemplateEvaluationContext.new helpers.each { |helper| context.extend(helper) } variables.each do |k, v| context.instance_variable_set("@#{k}", v) end context.__get_binding end
ruby
{ "resource": "" }
q15144
Lita.CLI.start
train
def start check_ruby_verison check_default_handlers begin Bundler.require rescue Bundler::GemfileNotFound say I18n.t("lita.cli.no_gemfile_warning"), :red abort end Lita.run(options[:config]) end
ruby
{ "resource": "" }
q15145
Lita.CLI.validate
train
def validate check_ruby_verison check_default_handlers begin Bundler.require rescue Bundler::GemfileNotFound say I18n.t("lita.cli.no_gemfile_warning"), :red abort end Lita.load_config(options[:config]) end
ruby
{ "resource": "" }
q15146
Prmd.Schema.merge!
train
def merge!(schema) if schema.is_a?(Schema) @data.merge!(schema.data) else @data.merge!(schema) end end
ruby
{ "resource": "" }
q15147
Prmd.Schema.to_json
train
def to_json new_json = JSON.pretty_generate(@data) # nuke empty lines new_json = new_json.split("\n").reject(&:empty?).join("\n") + "\n" new_json end
ruby
{ "resource": "" }
q15148
HTTP2.Framer.common_header
train
def common_header(frame) header = [] unless FRAME_TYPES[frame[:type]] fail CompressionError, "Invalid frame type (#{frame[:type]})" end if frame[:length] > @max_frame_size fail CompressionError, "Frame size is too large: #{frame[:length]}" end if frame[:length] < 0 fail CompressionError, "Frame size is invalid: #{frame[:length]}" end if frame[:stream] > MAX_STREAM_ID fail CompressionError, "Stream ID (#{frame[:stream]}) is too large" end if frame[:type] == :window_update && frame[:increment] > MAX_WINDOWINC fail CompressionError, "Window increment (#{frame[:increment]}) is too large" end header << (frame[:length] >> FRAME_LENGTH_HISHIFT) header << (frame[:length] & FRAME_LENGTH_LOMASK) header << FRAME_TYPES[frame[:type]] header << frame[:flags].reduce(0) do |acc, f| position = FRAME_FLAGS[frame[:type]][f] unless position fail CompressionError, "Invalid frame flag (#{f}) for #{frame[:type]}" end acc | (1 << position) end header << frame[:stream] header.pack(HEADERPACK) # 8+16,8,8,32 end
ruby
{ "resource": "" }
q15149
HTTP2.Framer.read_common_header
train
def read_common_header(buf) frame = {} len_hi, len_lo, type, flags, stream = buf.slice(0, 9).unpack(HEADERPACK) frame[:length] = (len_hi << FRAME_LENGTH_HISHIFT) | len_lo frame[:type], _ = FRAME_TYPES.find { |_t, pos| type == pos } if frame[:type] frame[:flags] = FRAME_FLAGS[frame[:type]].each_with_object([]) do |(name, pos), acc| acc << name if (flags & (1 << pos)) > 0 end end frame[:stream] = stream & RBIT frame end
ruby
{ "resource": "" }
q15150
HTTP2.FlowBuffer.send_data
train
def send_data(frame = nil, encode = false) @send_buffer.push frame unless frame.nil? # FIXME: Frames with zero length with the END_STREAM flag set (that # is, an empty DATA frame) MAY be sent if there is no available space # in either flow control window. while @remote_window > 0 && !@send_buffer.empty? frame = @send_buffer.shift sent, frame_size = 0, frame[:payload].bytesize if frame_size > @remote_window payload = frame.delete(:payload) chunk = frame.dup # Split frame so that it fits in the window # TODO: consider padding! frame[:payload] = payload.slice!(0, @remote_window) chunk[:length] = payload.bytesize chunk[:payload] = payload # if no longer last frame in sequence... frame[:flags] -= [:end_stream] if frame[:flags].include? :end_stream @send_buffer.unshift chunk sent = @remote_window else sent = frame_size end manage_state(frame) do frames = encode ? encode(frame) : [frame] frames.each { |f| emit(:frame, f) } @remote_window -= sent end end end
ruby
{ "resource": "" }
q15151
HTTP2.Client.send_connection_preface
train
def send_connection_preface return unless @state == :waiting_connection_preface @state = :connected emit(:frame, CONNECTION_PREFACE_MAGIC) payload = @local_settings.reject { |k, v| v == SPEC_DEFAULT_CONNECTION_SETTINGS[k] } settings(payload) end
ruby
{ "resource": "" }
q15152
HTTP2.Stream.receive
train
def receive(frame) transition(frame, false) case frame[:type] when :data update_local_window(frame) # Emit DATA frame emit(:data, frame[:payload]) unless frame[:ignore] calculate_window_update(@local_window_max_size) when :headers emit(:headers, frame[:payload]) unless frame[:ignore] when :push_promise emit(:promise_headers, frame[:payload]) unless frame[:ignore] when :priority process_priority(frame) when :window_update process_window_update(frame) when :altsvc # 4. The ALTSVC HTTP/2 Frame # An ALTSVC frame on a # stream other than stream 0 containing non-empty "Origin" information # is invalid and MUST be ignored. if !frame[:origin] || frame[:origin].empty? emit(frame[:type], frame) end when :blocked emit(frame[:type], frame) end complete_transition(frame) end
ruby
{ "resource": "" }
q15153
HTTP2.Stream.send
train
def send(frame) process_priority(frame) if frame[:type] == :priority case frame[:type] when :data # @remote_window is maintained in send_data send_data(frame) when :window_update manage_state(frame) do @local_window += frame[:increment] emit(:frame, frame) end else manage_state(frame) do emit(:frame, frame) end end end
ruby
{ "resource": "" }
q15154
HTTP2.Stream.headers
train
def headers(headers, end_headers: true, end_stream: false) flags = [] flags << :end_headers if end_headers flags << :end_stream if end_stream send(type: :headers, flags: flags, payload: headers) end
ruby
{ "resource": "" }
q15155
HTTP2.Stream.data
train
def data(payload, end_stream: true) # Split data according to each frame is smaller enough # TODO: consider padding? max_size = @connection.remote_settings[:settings_max_frame_size] if payload.bytesize > max_size payload = chunk_data(payload, max_size) do |chunk| send(type: :data, flags: [], payload: chunk) end end flags = [] flags << :end_stream if end_stream send(type: :data, flags: flags, payload: payload) end
ruby
{ "resource": "" }
q15156
HTTP2.Stream.chunk_data
train
def chunk_data(payload, max_size) total = payload.bytesize cursor = 0 while (total - cursor) > max_size yield payload.byteslice(cursor, max_size) cursor += max_size end payload.byteslice(cursor, total - cursor) end
ruby
{ "resource": "" }
q15157
HTTP2.Server.promise
train
def promise(*args, &callback) parent, headers, flags = *args promise = new_stream(parent: parent) promise.send( type: :push_promise, flags: flags, stream: parent.id, promise_stream: promise.id, payload: headers.to_a, ) callback.call(promise) end
ruby
{ "resource": "" }
q15158
HTTP2.Emitter.add_listener
train
def add_listener(event, &block) fail ArgumentError, 'must provide callback' unless block_given? listeners(event.to_sym).push block end
ruby
{ "resource": "" }
q15159
HTTP2.Emitter.emit
train
def emit(event, *args, &block) listeners(event).delete_if do |cb| cb.call(*args, &block) == :delete end end
ruby
{ "resource": "" }
q15160
HTTP2.Connection.new_stream
train
def new_stream(**args) fail ConnectionClosed if @state == :closed fail StreamLimitExceeded if @active_stream_count >= @remote_settings[:settings_max_concurrent_streams] stream = activate_stream(id: @stream_id, **args) @stream_id += 2 stream end
ruby
{ "resource": "" }
q15161
HTTP2.Connection.ping
train
def ping(payload, &blk) send(type: :ping, stream: 0, payload: payload) once(:ack, &blk) if blk end
ruby
{ "resource": "" }
q15162
HTTP2.Connection.goaway
train
def goaway(error = :no_error, payload = nil) last_stream = if (max = @streams.max) max.first else 0 end send(type: :goaway, last_stream: last_stream, error: error, payload: payload) @state = :closed @closed_since = Time.now end
ruby
{ "resource": "" }
q15163
HTTP2.Connection.settings
train
def settings(payload) payload = payload.to_a connection_error if validate_settings(@local_role, payload) @pending_settings << payload send(type: :settings, stream: 0, payload: payload) @pending_settings << payload end
ruby
{ "resource": "" }
q15164
HTTP2.Connection.encode
train
def encode(frame) frames = if frame[:type] == :headers || frame[:type] == :push_promise encode_headers(frame) # HEADERS and PUSH_PROMISE may create more than one frame else [frame] # otherwise one frame end frames.map { |f| @framer.generate(f) } end
ruby
{ "resource": "" }
q15165
HTTP2.Connection.validate_settings
train
def validate_settings(role, settings) settings.each do |key, v| case key when :settings_header_table_size # Any value is valid when :settings_enable_push case role when :server # Section 8.2 # Clients MUST reject any attempt to change the # SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the # message as a connection error (Section 5.4.1) of type PROTOCOL_ERROR. return ProtocolError.new("invalid #{key} value") unless v.zero? when :client # Any value other than 0 or 1 MUST be treated as a # connection error (Section 5.4.1) of type PROTOCOL_ERROR. unless v.zero? || v == 1 return ProtocolError.new("invalid #{key} value") end end when :settings_max_concurrent_streams # Any value is valid when :settings_initial_window_size # Values above the maximum flow control window size of 2^31-1 MUST # be treated as a connection error (Section 5.4.1) of type # FLOW_CONTROL_ERROR. unless v <= 0x7fffffff return FlowControlError.new("invalid #{key} value") end when :settings_max_frame_size # The initial value is 2^14 (16,384) octets. The value advertised # by an endpoint MUST be between this initial value and the maximum # allowed frame size (2^24-1 or 16,777,215 octets), inclusive. # Values outside this range MUST be treated as a connection error # (Section 5.4.1) of type PROTOCOL_ERROR. unless v >= 16_384 && v <= 16_777_215 return ProtocolError.new("invalid #{key} value") end when :settings_max_header_list_size # Any value is valid # else # ignore unknown settings end end nil end
ruby
{ "resource": "" }
q15166
HTTP2.Connection.connection_settings
train
def connection_settings(frame) connection_error unless frame[:type] == :settings && (frame[:stream]).zero? # Apply settings. # side = # local: previously sent and pended our settings should be effective # remote: just received peer settings should immediately be effective settings, side = if frame[:flags].include?(:ack) # Process pending settings we have sent. [@pending_settings.shift, :local] else connection_error(check) if validate_settings(@remote_role, frame[:payload]) [frame[:payload], :remote] end settings.each do |key, v| case side when :local @local_settings[key] = v when :remote @remote_settings[key] = v end case key when :settings_max_concurrent_streams # Do nothing. # The value controls at the next attempt of stream creation. when :settings_initial_window_size # A change to SETTINGS_INITIAL_WINDOW_SIZE could cause the available # space in a flow control window to become negative. A sender MUST # track the negative flow control window, and MUST NOT send new flow # controlled frames until it receives WINDOW_UPDATE frames that cause # the flow control window to become positive. case side when :local @local_window = @local_window - @local_window_limit + v @streams.each do |_id, stream| stream.emit(:local_window, stream.local_window - @local_window_limit + v) end @local_window_limit = v when :remote @remote_window = @remote_window - @remote_window_limit + v @streams.each do |_id, stream| # Event name is :window, not :remote_window stream.emit(:window, stream.remote_window - @remote_window_limit + v) end @remote_window_limit = v end when :settings_header_table_size # Setting header table size might cause some headers evicted case side when :local @compressor.table_size = v when :remote @decompressor.table_size = v end when :settings_enable_push # nothing to do when :settings_max_frame_size # nothing to do # else # ignore unknown settings end end case side when :local # Received a settings_ack. Notify application layer. emit(:settings_ack, frame, @pending_settings.size) when :remote unless @state == :closed || @h2c_upgrade == :start # Send ack to peer send(type: :settings, stream: 0, payload: [], flags: [:ack]) end end end
ruby
{ "resource": "" }
q15167
HTTP2.Connection.decode_headers
train
def decode_headers(frame) if frame[:payload].is_a? Buffer frame[:payload] = @decompressor.decode(frame[:payload]) end rescue CompressionError => e connection_error(:compression_error, e: e) rescue ProtocolError => e connection_error(:protocol_error, e: e) rescue StandardError => e connection_error(:internal_error, e: e) end
ruby
{ "resource": "" }
q15168
HTTP2.Connection.encode_headers
train
def encode_headers(frame) payload = frame[:payload] payload = @compressor.encode(payload) unless payload.is_a? Buffer frames = [] while payload.bytesize > 0 cont = frame.dup cont[:type] = :continuation cont[:flags] = [] cont[:payload] = payload.slice!(0, @remote_settings[:settings_max_frame_size]) frames << cont end if frames.empty? frames = [frame] else frames.first[:type] = frame[:type] frames.first[:flags] = frame[:flags] - [:end_headers] frames.last[:flags] << :end_headers end frames rescue StandardError => e connection_error(:compression_error, e: e) nil end
ruby
{ "resource": "" }
q15169
HTTP2.Connection.activate_stream
train
def activate_stream(id: nil, **args) connection_error(msg: 'Stream ID already exists') if @streams.key?(id) stream = Stream.new({ connection: self, id: id }.merge(args)) # Streams that are in the "open" state, or either of the "half closed" # states count toward the maximum number of streams that an endpoint is # permitted to open. stream.once(:active) { @active_stream_count += 1 } stream.once(:close) do @active_stream_count -= 1 # Store a reference to the closed stream, such that we can respond # to any in-flight frames while close is registered on both sides. # References to such streams will be purged whenever another stream # is closed, with a minimum of 15s RTT time window. @streams_recently_closed[id] = Time.now to_delete = @streams_recently_closed.select { |_, v| (Time.now - v) > 15 } to_delete.each do |stream_id| @streams.delete stream_id @streams_recently_closed.delete stream_id end end stream.on(:promise, &method(:promise)) if self.is_a? Server stream.on(:frame, &method(:send)) @streams[id] = stream end
ruby
{ "resource": "" }
q15170
HTTP2.Connection.connection_error
train
def connection_error(error = :protocol_error, msg: nil, e: nil) goaway(error) unless @state == :closed || @state == :new @state, @error = :closed, error klass = error.to_s.split('_').map(&:capitalize).join msg ||= e && e.message backtrace = (e && e.backtrace) || [] fail Error.const_get(klass), msg, backtrace end
ruby
{ "resource": "" }
q15171
Janky.Branch.build_for
train
def build_for(commit, user, room_id = nil, compare = nil) if compare.nil? && build = commit.last_build compare = build.compare end room_id = room_id.to_s if room_id.empty? || room_id == "0" room_id = repository.room_id end builds.create!( :compare => compare, :user => user, :commit => commit, :room_id => room_id ) end
ruby
{ "resource": "" }
q15172
Janky.Branch.head_build_for
train
def head_build_for(room_id, user) sha_to_build = GitHub.branch_head_sha(repository.nwo, name) return if !sha_to_build commit = repository.commit_for_sha(sha_to_build) current_sha = current_build ? current_build.sha1 : "#{sha_to_build}^" compare_url = repository.github_url("compare/#{current_sha}...#{commit.sha1}") build_for(commit, user, room_id, compare_url) end
ruby
{ "resource": "" }
q15173
Janky.Branch.status
train
def status if current_build && current_build.building? "building" elsif build = completed_builds.first if build.green? "green" elsif build.red? "red" end elsif completed_builds.empty? || builds.empty? "no build" else raise Error, "unexpected branch status: #{id.inspect}" end end
ruby
{ "resource": "" }
q15174
Janky.Branch.to_hash
train
def to_hash { :name => repository.name, :status => status, :sha1 => (current_build && current_build.sha1), :compare => (current_build && current_build.compare) } end
ruby
{ "resource": "" }
q15175
Janky.Repository.job_name
train
def job_name md5 = Digest::MD5.new md5 << name md5 << uri md5 << job_config_path.read md5 << builder.callback_url.to_s "#{name}-#{md5.hexdigest[0,12]}" end
ruby
{ "resource": "" }
q15176
Janky.Build.rerun
train
def rerun(new_room_id = nil) build = branch.build_for(commit, new_room_id) build.run build end
ruby
{ "resource": "" }
q15177
Janky.Build.start
train
def start(url, now) if started? raise Error, "Build #{id} already started" elsif completed? raise Error, "Build #{id} already completed" else update_attributes!(:url => url, :started_at => now) Notifier.started(self) end end
ruby
{ "resource": "" }
q15178
Janky.Build.complete
train
def complete(green, now) if ! started? raise Error, "Build #{id} not started" elsif completed? raise Error, "Build #{id} already completed" else update_attributes!( :green => green, :completed_at => now, :output => output_remote ) Notifier.completed(self) end end
ruby
{ "resource": "" }
q15179
Logster.Message.solved_keys
train
def solved_keys if Array === env versions = env.map { |single_env| single_env["application_version"] } else versions = env["application_version"] end if versions && backtrace && backtrace.length > 0 versions = [versions] if String === versions versions.map do |version| Digest::SHA1.hexdigest "#{version} #{backtrace}" end end end
ruby
{ "resource": "" }
q15180
Datagrid.Helper.datagrid_rows
train
def datagrid_rows(grid, assets = grid.assets, **options, &block) datagrid_renderer.rows(grid, assets, options, &block) end
ruby
{ "resource": "" }
q15181
Datagrid.Helper.datagrid_row
train
def datagrid_row(grid, asset, &block) HtmlRow.new(self, grid, asset).tap do |row| if block_given? return capture(row, &block) end end end
ruby
{ "resource": "" }
q15182
Datagrid.Helper.datagrid_order_path
train
def datagrid_order_path(grid, column, descending) datagrid_renderer.order_path(grid, column, descending, request) end
ruby
{ "resource": "" }
q15183
Datagrid.FormBuilder.datagrid_filter
train
def datagrid_filter(filter_or_attribute, options = {}, &block) filter = datagrid_get_filter(filter_or_attribute) options = add_html_classes(options, filter.name, datagrid_filter_html_class(filter)) # Prevent partials option from appearing in HTML attributes options.delete(:partials) # Legacy option self.send(filter.form_builder_helper_name, filter, options, &block) end
ruby
{ "resource": "" }
q15184
Datagrid.FormBuilder.datagrid_label
train
def datagrid_label(filter_or_attribute, options_or_text = {}, options = {}, &block) filter = datagrid_get_filter(filter_or_attribute) text, options = options_or_text.is_a?(Hash) ? [filter.header, options_or_text] : [options_or_text, options] label(filter.name, text, options, &block) end
ruby
{ "resource": "" }
q15185
BabySqueel.DSL._
train
def _(expr) expr = Arel.sql(expr.to_sql) if expr.is_a? ::ActiveRecord::Relation Nodes.wrap Arel::Nodes::Grouping.new(expr) end
ruby
{ "resource": "" }
q15186
ActsAsTenant.ControllerExtensions.set_current_tenant_by_subdomain
train
def set_current_tenant_by_subdomain(tenant = :account, column = :subdomain ) self.class_eval do cattr_accessor :tenant_class, :tenant_column end self.tenant_class = tenant.to_s.camelcase.constantize self.tenant_column = column.to_sym self.class_eval do before_action :find_tenant_by_subdomain helper_method :current_tenant if respond_to?(:helper_method) private def find_tenant_by_subdomain if request.subdomains.last ActsAsTenant.current_tenant = tenant_class.where(tenant_column => request.subdomains.last.downcase).first end end def current_tenant ActsAsTenant.current_tenant end end end
ruby
{ "resource": "" }
q15187
ActsAsTenant.ControllerExtensions.set_current_tenant_through_filter
train
def set_current_tenant_through_filter self.class_eval do helper_method :current_tenant if respond_to?(:helper_method) private def set_current_tenant(current_tenant_object) ActsAsTenant.current_tenant = current_tenant_object end def current_tenant ActsAsTenant.current_tenant end end end
ruby
{ "resource": "" }
q15188
God.Metric.condition
train
def condition(kind) # Create the condition. begin c = Condition.generate(kind, self.watch) rescue NoSuchConditionError => e abort e.message end # Send to block so config can set attributes. yield(c) if block_given? # Prepare the condition. c.prepare # Test generic and specific validity. unless Condition.valid?(c) && c.valid? abort "Exiting on invalid condition" end # Inherit interval from watch if no poll condition specific interval was # set. if c.kind_of?(PollCondition) && !c.interval if self.watch.interval c.interval = self.watch.interval else abort "No interval set for Condition '#{c.class.name}' in Watch " + "'#{self.watch.name}', and no default Watch interval from " + "which to inherit." end end # Add the condition to the list. self.conditions << c end
ruby
{ "resource": "" }
q15189
God.Socket.start
train
def start begin @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") rescue Errno::EADDRINUSE applog(nil, :info, "Socket already in use") server = DRbObject.new(nil, self.socket) begin Timeout.timeout(5) do server.ping end abort "Socket #{self.socket} already in use by another instance of god" rescue StandardError, Timeout::Error applog(nil, :info, "Socket is stale, reopening") File.delete(self.socket_file) rescue nil @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") end end if File.exists?(self.socket_file) if @user user_method = @user.is_a?(Integer) ? :getpwuid : :getpwnam uid = Etc.send(user_method, @user).uid gid = Etc.send(user_method, @user).gid end if @group group_method = @group.is_a?(Integer) ? :getgrgid : :getgrnam gid = Etc.send(group_method, @group).gid end File.chmod(Integer(@perm), socket_file) if @perm File.chown(uid, gid, socket_file) if uid or gid end end
ruby
{ "resource": "" }
q15190
God.Task.valid?
train
def valid? valid = true # A name must be specified. if self.name.nil? valid = false applog(self, :error, "No name String was specified.") end # Valid states must be specified. if self.valid_states.nil? valid = false applog(self, :error, "No valid_states Array or Symbols was specified.") end # An initial state must be specified. if self.initial_state.nil? valid = false applog(self, :error, "No initial_state Symbol was specified.") end valid end
ruby
{ "resource": "" }
q15191
God.Task.move
train
def move(to_state) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:move, [to_state]) else # Called from within Driver. Record original info. orig_to_state = to_state from_state = self.state # Log. msg = "#{self.name} move '#{from_state}' to '#{to_state}'" applog(self, :info, msg) # Cleanup from current state. self.driver.clear_events self.metrics[from_state].each { |m| m.disable } if to_state == :unmonitored self.metrics[nil].each { |m| m.disable } end # Perform action. self.action(to_state) # Enable simple mode. if [:start, :restart].include?(to_state) && self.metrics[to_state].empty? to_state = :up end # Move to new state. self.metrics[to_state].each { |m| m.enable } # If no from state, enable lifecycle metric. if from_state == :unmonitored self.metrics[nil].each { |m| m.enable } end # Set state. self.state = to_state # Broadcast to interested TriggerConditions. Trigger.broadcast(self, :state_change, [from_state, orig_to_state]) # Log. msg = "#{self.name} moved '#{from_state}' to '#{to_state}'" applog(self, :info, msg) end self end
ruby
{ "resource": "" }
q15192
God.Task.action
train
def action(a, c = nil) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:action, [a, c]) else # Called from within Driver. if self.respond_to?(a) command = self.send(a) case command when String msg = "#{self.name} #{a}: #{command}" applog(self, :info, msg) system(command) when Proc msg = "#{self.name} #{a}: lambda" applog(self, :info, msg) command.call else raise NotImplementedError end end end end
ruby
{ "resource": "" }
q15193
God.Task.handle_event
train
def handle_event(condition) # Lookup metric. metric = self.directory[condition] # Log. messages = self.log_line(self, metric, condition, true) # Notify. if condition.notify self.notify(condition, messages.last) end # Get the destination. dest = if condition.transition # Condition override. condition.transition else # Regular. metric.destination && metric.destination[true] end if dest self.move(dest) end end
ruby
{ "resource": "" }
q15194
God.Task.log_line
train
def log_line(watch, metric, condition, result) status = if self.trigger?(metric, result) "[trigger]" else "[ok]" end messages = [] # Log info if available. if condition.info Array(condition.info).each do |condition_info| messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})" applog(watch, :info, messages.last) end else messages << "#{watch.name} #{status} (#{condition.base_name})" applog(watch, :info, messages.last) end # Log. debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition) applog(watch, :debug, debug_message) messages end
ruby
{ "resource": "" }
q15195
God.Task.dest_desc
train
def dest_desc(metric, condition) if condition.transition {true => condition.transition}.inspect else if metric.destination metric.destination.inspect else 'none' end end end
ruby
{ "resource": "" }
q15196
God.Task.notify
train
def notify(condition, message) spec = Contact.normalize(condition.notify) unmatched = [] # Resolve contacts. resolved_contacts = spec[:contacts].inject([]) do |acc, contact_name_or_group| cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group]) unmatched << contact_name_or_group if cons.empty? acc += cons acc end # Warn about unmatched contacts. unless unmatched.empty? msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'" applog(condition.watch, :warn, msg) end # Notify each contact. resolved_contacts.each do |c| host = `hostname`.chomp rescue 'none' begin c.notify(message, Time.now, spec[:priority], spec[:category], host) msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})" applog(condition.watch, :info, msg % []) rescue Exception => e applog(condition.watch, :error, "#{e.message} #{e.backtrace}") msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})" applog(condition.watch, :error, msg % []) end end end
ruby
{ "resource": "" }
q15197
God.Logger.level=
train
def level=(lev) SysLogger.level = SimpleLogger::CONSTANT_TO_SYMBOL[lev] if Logger.syslog super(lev) end
ruby
{ "resource": "" }
q15198
God.Logger.watch_log_since
train
def watch_log_since(watch_name, since) # initialize watch log if necessary self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) # get and join lines since given time @mutex.synchronize do @spool = Time.now self.logs[watch_name].select do |x| x.first > since end.map do |x| x[1] end.join end end
ruby
{ "resource": "" }
q15199
God.Process.pid
train
def pid contents = File.read(self.pid_file).strip rescue '' real_pid = contents =~ /^\d+$/ ? contents.to_i : nil if real_pid @pid = real_pid real_pid else @pid end end
ruby
{ "resource": "" }