_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q15200
God.Process.signal
train
def signal(sig) sig = sig.to_i if sig.to_i != 0 applog(self, :info, "#{self.name} sending signal '#{sig}' to pid #{self.pid}") ::Process.kill(sig, self.pid) rescue nil end
ruby
{ "resource": "" }
q15201
God.Process.ensure_stop
train
def ensure_stop applog(self, :warn, "#{self.name} ensuring stop...") unless self.pid applog(self, :warn, "#{self.name} stop called but pid is uknown") return end # Poll to see if it's dead @stop_timeout.times do begin ::Process.kill(0, self.pid) rescue Errno::ESRCH # It died. Good. return end sleep 1 end # last resort ::Process.kill('KILL', self.pid) rescue nil applog(self, :warn, "#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL") end
ruby
{ "resource": "" }
q15202
God.DriverEventQueue.pop
train
def pop @monitor.synchronize do if @events.empty? raise ThreadError, "queue empty" if @shutdown @resource.wait else delay = @events.first.at - Time.now @resource.wait(delay) if delay > 0 end @events.shift end end
ruby
{ "resource": "" }
q15203
God.Driver.schedule
train
def schedule(condition, delay = condition.interval) applog(nil, :debug, "driver schedule #{condition} in #{delay} seconds") @events.push(DriverEvent.new(delay, @task, condition)) end
ruby
{ "resource": "" }
q15204
God.Watch.call_action
train
def call_action(condition, action) # Before. before_items = self.behaviors before_items += [condition] if condition before_items.each do |b| info = b.send("before_#{action}") if info msg = "#{self.name} before_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end # Log. if self.send(action) msg = "#{self.name} #{action}: #{self.send(action).to_s}" applog(self, :info, msg) end # Execute. @process.call_action(action) # After. after_items = self.behaviors after_items += [condition] if condition after_items.each do |b| info = b.send("after_#{action}") if info msg = "#{self.name} after_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end end
ruby
{ "resource": "" }
q15205
InheritedResources.BaseHelpers.collection
train
def collection get_collection_ivar || begin c = end_of_association_chain set_collection_ivar(c.respond_to?(:scoped) ? c.scoped : c.all) end end
ruby
{ "resource": "" }
q15206
InheritedResources.BaseHelpers.end_of_association_chain
train
def end_of_association_chain #:nodoc: if chain = association_chain.last if method_for_association_chain apply_scopes_if_available(chain.send(method_for_association_chain)) else # This only happens when we specify begin_of_association_chain in # a singleton controller without parents. In this case, the chain # is exactly the begin_of_association_chain which is already an # instance and then not scopable. chain end else apply_scopes_if_available(resource_class) end end
ruby
{ "resource": "" }
q15207
InheritedResources.BaseHelpers.smart_collection_url
train
def smart_collection_url url = nil if respond_to? :index url ||= collection_url rescue nil end if respond_to? :parent, true url ||= parent_url rescue nil end url ||= root_url rescue nil end
ruby
{ "resource": "" }
q15208
InheritedResources.BaseHelpers.build_resource_params
train
def build_resource_params parameters = permitted_params || params rparams = [parameters[resource_request_name] || parameters[resource_instance_name] || {}] if without_protection_given? rparams << without_protection else rparams << as_role if role_given? end rparams end
ruby
{ "resource": "" }
q15209
InheritedResources.ClassMethods.actions
train
def actions(*actions_to_keep) raise ArgumentError, 'Wrong number of arguments. You have to provide which actions you want to keep.' if actions_to_keep.empty? options = actions_to_keep.extract_options! actions_to_remove = Array(options[:except]) actions_to_remove += ACTIONS - actions_to_keep.map { |a| a.to_sym } unless actions_to_keep.first == :all actions_to_remove.map! { |a| a.to_sym }.uniq! (instance_methods.map { |m| m.to_sym } & actions_to_remove).each do |action| undef_method action, "#{action}!" end end
ruby
{ "resource": "" }
q15210
InheritedResources.ClassMethods.polymorphic_belongs_to
train
def polymorphic_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(polymorphic: true) belongs_to(*symbols, options, &block) end
ruby
{ "resource": "" }
q15211
InheritedResources.ClassMethods.singleton_belongs_to
train
def singleton_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(singleton: true) belongs_to(*symbols, options, &block) end
ruby
{ "resource": "" }
q15212
InheritedResources.ClassMethods.optional_belongs_to
train
def optional_belongs_to(*symbols, &block) options = symbols.extract_options! options.merge!(optional: true) belongs_to(*symbols, options, &block) end
ruby
{ "resource": "" }
q15213
InheritedResources.ClassMethods.custom_actions
train
def custom_actions(options) self.resources_configuration[:self][:custom_actions] = options options.each do | resource_or_collection, actions | [*actions].each do | action | create_custom_action(resource_or_collection, action) end end create_resources_url_helpers! [*options[:resource]].each do | action | helper_method "#{action}_resource_path", "#{action}_resource_url" end [*options[:collection]].each do | action | helper_method "#{action}_resources_path", "#{action}_resources_url" end end
ruby
{ "resource": "" }
q15214
InheritedResources.ClassMethods.initialize_resources_class_accessors!
train
def initialize_resources_class_accessors! #:nodoc: # First priority is the namespaced model, e.g. User::Group self.resource_class ||= begin namespaced_class = self.name.sub(/Controller$/, '').singularize namespaced_class.constantize rescue NameError nil end # Second priority is the top namespace model, e.g. EngineName::Article for EngineName::Admin::ArticlesController self.resource_class ||= begin namespaced_classes = self.name.sub(/Controller$/, '').split('::') namespaced_class = [namespaced_classes.first, namespaced_classes.last].join('::').singularize namespaced_class.constantize rescue NameError nil end # Third priority the camelcased c, i.e. UserGroup self.resource_class ||= begin camelcased_class = self.name.sub(/Controller$/, '').gsub('::', '').singularize camelcased_class.constantize rescue NameError nil end # Otherwise use the Group class, or fail self.resource_class ||= begin class_name = self.controller_name.classify class_name.constantize rescue NameError => e raise unless e.message.include?(class_name) nil end self.parents_symbols = self.parents_symbols.try(:dup) || [] # Initialize resources configuration hash self.resources_configuration = self.resources_configuration.try(:dup) || {} self.resources_configuration.each do |key, value| next unless value.is_a?(Hash) || value.is_a?(Array) self.resources_configuration[key] = value.dup end config = (self.resources_configuration[:self] ||= {}) config[:collection_name] = self.controller_name.to_sym config[:instance_name] = self.controller_name.singularize.to_sym config[:route_collection_name] = config[:collection_name] config[:route_instance_name] = config[:instance_name] # Deal with namespaced controllers namespaces = self.controller_path.split('/')[0..-2] # Remove namespace if its a mountable engine namespaces.delete_if do |namespace| begin "#{namespace}/engine".camelize.constantize.isolated? rescue StandardError, LoadError false end end config[:route_prefix] = namespaces.join('_') unless namespaces.empty? # Deal with default request parameters in namespaced controllers, e.g. # Forum::Thread#create will properly pick up the request parameter # which will be forum_thread, and not thread # Additionally make this work orthogonally with instance_name config[:request_name] = self.resource_class.to_s.underscore.gsub('/', '_') # Initialize polymorphic, singleton, scopes and belongs_to parameters polymorphic = self.resources_configuration[:polymorphic] || { symbols: [], optional: false } polymorphic[:symbols] = polymorphic[:symbols].dup self.resources_configuration[:polymorphic] = polymorphic end
ruby
{ "resource": "" }
q15215
InheritedResources.PolymorphicHelpers.symbols_for_association_chain
train
def symbols_for_association_chain #:nodoc: polymorphic_config = resources_configuration[:polymorphic] parents_symbols.map do |symbol| if symbol == :polymorphic params_keys = params.keys keys = polymorphic_config[:symbols].map do |poly| params_keys.include?(resources_configuration[poly][:param].to_s) ? poly : nil end.compact if keys.empty? raise ScriptError, "Could not find param for polymorphic association. The request " << "parameters are #{params.keys.inspect} and the polymorphic " << "associations are #{polymorphic_config[:symbols].inspect}." unless polymorphic_config[:optional] nil else @parent_type = keys[-1].to_sym @parent_types = keys.map(&:to_sym) end else symbol end end.flatten.compact end
ruby
{ "resource": "" }
q15216
Unsplash.Connection.authorization_url
train
def authorization_url(requested_scopes = ["public"]) @oauth.auth_code.authorize_url(redirect_uri: Unsplash.configuration.application_redirect_uri, scope: requested_scopes.join(" ")) end
ruby
{ "resource": "" }
q15217
Unsplash.Client.reload!
train
def reload! if links && links["self"] attrs = JSON.parse(connection.get(links["self"]).body) @attributes = OpenStruct.new(attrs) self else raise Unsplash::Error.new "Missing self link for #{self.class} with ID #{self.id}" end end
ruby
{ "resource": "" }
q15218
Unsplash.User.photos
train
def photos(page = 1, per_page = 10) params = { page: page, per_page: per_page } list = JSON.parse(connection.get("/users/#{username}/photos", params).body) list.map do |photo| Unsplash::Photo.new photo.to_hash end end
ruby
{ "resource": "" }
q15219
Unsplash.User.collections
train
def collections(page = 1, per_page = 10) params = { page: page, per_page: per_page } list = JSON.parse(connection.get("/users/#{username}/collections", params).body) list.map do |collection| Unsplash::Collection.new collection.to_hash end end
ruby
{ "resource": "" }
q15220
Unsplash.Collection.update
train
def update(title: nil, description: nil, private: nil) params = { title: title, description: description, private: private }.select { |k,v| v } updated = JSON.parse(connection.put("/collections/#{id}", params).body) self.title = updated["title"] self.description = updated["description"] self end
ruby
{ "resource": "" }
q15221
Unsplash.Collection.add
train
def add(photo) response = JSON.parse(connection.post("/collections/#{id}/add", { photo_id: photo.id }).body) { photo_id: response["photo"]["id"], collection_id: response["collection"]["id"], user_id: response["user"]["id"], created_at: response["created_at"] } end
ruby
{ "resource": "" }
q15222
Unsplash.Collection.remove
train
def remove(photo) response = connection.delete("/collections/#{id}/remove", photo_id: photo.id) (200..299).include?(response.status) end
ruby
{ "resource": "" }
q15223
Fugit.Duration.drop_seconds
train
def drop_seconds h = @h.dup h.delete(:sec) h[:min] = 0 if h.empty? self.class.allocate.init(nil, { literal: true }, h) end
ruby
{ "resource": "" }
q15224
RuCaptcha.ControllerHelpers.rucaptcha_sesion_key_key
train
def rucaptcha_sesion_key_key session_id = session.respond_to?(:id) ? session.id : session[:session_id] warning_when_session_invalid if session_id.blank? ['rucaptcha-session', session_id].join(':') end
ruby
{ "resource": "" }
q15225
RuCaptcha.ControllerHelpers.generate_rucaptcha
train
def generate_rucaptcha res = RuCaptcha.generate() session_val = { code: res[0], time: Time.now.to_i } RuCaptcha.cache.write(rucaptcha_sesion_key_key, session_val, expires_in: RuCaptcha.config.expires_in) res[1] end
ruby
{ "resource": "" }
q15226
RuCaptcha.ControllerHelpers.verify_rucaptcha?
train
def verify_rucaptcha?(resource = nil, opts = {}) opts ||= {} store_info = RuCaptcha.cache.read(rucaptcha_sesion_key_key) # make sure move used key RuCaptcha.cache.delete(rucaptcha_sesion_key_key) unless opts[:keep_session] # Make sure session exist if store_info.blank? return add_rucaptcha_validation_error end # Make sure not expire if (Time.now.to_i - store_info[:time]) > RuCaptcha.config.expires_in return add_rucaptcha_validation_error end # Make sure parama have captcha captcha = (opts[:captcha] || params[:_rucaptcha] || '').downcase.strip if captcha.blank? return add_rucaptcha_validation_error end if captcha != store_info[:code] return add_rucaptcha_validation_error end true end
ruby
{ "resource": "" }
q15227
Billy.Authority.generate
train
def generate cert = OpenSSL::X509::Certificate.new configure(cert) add_extensions(cert) cert.sign(key, OpenSSL::Digest::SHA256.new) end
ruby
{ "resource": "" }
q15228
Billy.CertificateChain.file
train
def file contents = certificates.map { |cert| cert.to_pem }.join write_file("chain-#{domain}.pem", contents) end
ruby
{ "resource": "" }
q15229
ActiveRecordShards.ConnectionSwitcher.connection_pool_name
train
def connection_pool_name # :nodoc: name = current_shard_selection.shard_name(self) if configurations[name].nil? && on_slave? current_shard_selection.shard_name(self, false) else name end end
ruby
{ "resource": "" }
q15230
Builder.XmlMarkup.declare!
train
def declare!(inst, *args, &block) _indent @target << "<!#{inst}" args.each do |arg| case arg when ::String @target << %{ "#{arg}"} # " WART when ::Symbol @target << " #{arg}" end end if ::Kernel::block_given? @target << " [" _newline _nested_structures(block) @target << "]" end @target << ">" _newline end
ruby
{ "resource": "" }
q15231
Builder.XmlMarkup.instruct!
train
def instruct!(directive_tag=:xml, attrs={}) _ensure_no_block ::Kernel::block_given? if directive_tag == :xml a = { :version=>"1.0", :encoding=>"UTF-8" } attrs = a.merge attrs @encoding = attrs[:encoding].downcase end _special( "<?#{directive_tag}", "?>", nil, attrs, [:version, :encoding, :standalone]) end
ruby
{ "resource": "" }
q15232
Builder.XmlMarkup._special
train
def _special(open, close, data=nil, attrs=nil, order=[]) _indent @target << open @target << data if data _insert_attributes(attrs, order) if attrs @target << close _newline end
ruby
{ "resource": "" }
q15233
Builder.XmlBase.method_missing
train
def method_missing(sym, *args, &block) cache_method_call(sym) if ::Builder::XmlBase.cache_method_calls tag!(sym, *args, &block) end
ruby
{ "resource": "" }
q15234
Builder.XmlBase.cache_method_call
train
def cache_method_call(sym) class << self; self; end.class_eval do unless method_defined?(sym) define_method(sym) do |*args, &block| tag!(sym, *args, &block) end end end end
ruby
{ "resource": "" }
q15235
Sablon.Template.render_to_file
train
def render_to_file(output_path, context, properties = {}) File.open(output_path, 'wb') do |f| f.write render_to_string(context, properties) end end
ruby
{ "resource": "" }
q15236
Sablon.Configuration.register_html_tag
train
def register_html_tag(tag_name, type = :inline, **options) tag = HTMLTag.new(tag_name, type, **options) @permitted_html_tags[tag.name] = tag end
ruby
{ "resource": "" }
q15237
Celluloid.ClassMethods.pool_link
train
def pool_link(klass, config = {}, &block) Supervision::Container::Pool.new_link(pooling_options(config, block: block, actors: klass)) end
ruby
{ "resource": "" }
q15238
Celluloid.ClassMethods.new_link
train
def new_link(*args, &block) raise NotActorError, "can't link outside actor context" unless Celluloid.actor? proxy = Cell.new(allocate, behavior_options, actor_options).proxy Actor.link(proxy) proxy._send_(:initialize, *args, &block) proxy end
ruby
{ "resource": "" }
q15239
Celluloid.Condition.wait
train
def wait(timeout = nil) raise ConditionError, "cannot wait for signals while exclusive" if Celluloid.exclusive? if actor = Thread.current[:celluloid_actor] task = Task.current if timeout bt = caller timer = actor.timers.after(timeout) do exception = ConditionError.new("timeout after #{timeout.inspect} seconds") exception.set_backtrace bt task.resume exception end end else task = Thread.current end waiter = Waiter.new(self, task, Celluloid.mailbox, timeout) @mutex.synchronize do @waiters << waiter end result = Celluloid.suspend :condwait, waiter timer.cancel if timer raise result if result.is_a?(ConditionError) return yield(result) if block_given? result end
ruby
{ "resource": "" }
q15240
Celluloid.Condition.signal
train
def signal(value = nil) @mutex.synchronize do if waiter = @waiters.shift waiter << SignalConditionRequest.new(waiter.task, value) else Internals::Logger.with_backtrace(caller(3)) do |logger| logger.debug("Celluloid::Condition signaled spuriously") end end end end
ruby
{ "resource": "" }
q15241
Celluloid.Condition.broadcast
train
def broadcast(value = nil) @mutex.synchronize do @waiters.each { |waiter| waiter << SignalConditionRequest.new(waiter.task, value) } @waiters.clear end end
ruby
{ "resource": "" }
q15242
Celluloid.Future.execute
train
def execute(receiver, method, args, block) @mutex.synchronize do raise "already calling" if @call @call = Call::Sync.new(self, method, args, block) end receiver << @call end
ruby
{ "resource": "" }
q15243
Celluloid.Future.value
train
def value(timeout = nil) ready = result = nil begin @mutex.lock if @ready ready = true result = @result else case @forwards when Array @forwards << Celluloid.mailbox when NilClass @forwards = Celluloid.mailbox else @forwards = [@forwards, Celluloid.mailbox] end end ensure @mutex.unlock end unless ready result = Celluloid.receive(timeout) do |msg| msg.is_a?(Future::Result) && msg.future == self end end if result result.respond_to?(:value) ? result.value : result else raise TimedOut, "Timed out" end end
ruby
{ "resource": "" }
q15244
Celluloid.Future.signal
train
def signal(value) return if @cancelled result = Result.new(value, self) @mutex.synchronize do raise "the future has already happened!" if @ready if @forwards @forwards.is_a?(Array) ? @forwards.each { |f| f << result } : @forwards << result end @result = result @ready = true end end
ruby
{ "resource": "" }
q15245
Celluloid.Actor.run
train
def run while @running begin @timers.wait do |interval| interval = 0 if interval && interval < 0 if message = @mailbox.check(interval) handle_message(message) break unless @running end end rescue MailboxShutdown @running = false rescue MailboxDead # TODO: not tests (but fails occasionally in tests) @running = false end end shutdown rescue ::Exception => ex handle_crash(ex) raise unless ex.is_a?(StandardError) || ex.is_a?(Celluloid::Interruption) end
ruby
{ "resource": "" }
q15246
Celluloid.Actor.linking_request
train
def linking_request(receiver, type) Celluloid.exclusive do receiver.mailbox << LinkingRequest.new(Actor.current, type) system_events = [] Timers::Wait.for(LINKING_TIMEOUT) do |remaining| begin message = @mailbox.receive(remaining) do |msg| msg.is_a?(LinkingResponse) && msg.actor.mailbox.address == receiver.mailbox.address && msg.type == type end rescue TaskTimeout next # IO reactor did something, no message in queue yet. end if message.instance_of? LinkingResponse # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Celluloid::Probe.actors_linked(self, receiver) if $CELLULOID_MONITORING # rubocop:enable Style/GlobalVars system_events.each { |ev| @mailbox << ev } return elsif message.is_a? SystemEvent # Queue up pending system events to be processed after we've successfully linked system_events << message else raise "Unexpected message type: #{message.class}. Expected LinkingResponse, NilClass, SystemEvent." end end raise TaskTimeout, "linking timeout of #{LINKING_TIMEOUT} seconds exceeded with receiver: #{receiver}" end end
ruby
{ "resource": "" }
q15247
Celluloid.Actor.receive
train
def receive(timeout = nil, &block) loop do message = @receivers.receive(timeout, &block) return message unless message.is_a?(SystemEvent) handle_system_event(message) end end
ruby
{ "resource": "" }
q15248
Celluloid.Actor.handle_message
train
def handle_message(message) # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Metrics/LineLength, Style/GlobalVars Internals::Logger.debug "Discarded message (unhandled): #{message}" if !@handlers.handle_message(message) && !@receivers.handle_message(message) && $CELLULOID_DEBUG # rubocop:enable Metrics/LineLength, Style/GlobalVars message end
ruby
{ "resource": "" }
q15249
Celluloid.Actor.handle_crash
train
def handle_crash(exception) # TODO: add meta info Internals::Logger.crash("Actor crashed!", exception) shutdown ExitEvent.new(behavior_proxy, exception) rescue => ex Internals::Logger.crash("Actor#handle_crash CRASHED!", ex) end
ruby
{ "resource": "" }
q15250
Celluloid.Actor.shutdown
train
def shutdown(exit_event = ExitEvent.new(behavior_proxy)) @behavior.shutdown cleanup exit_event ensure Thread.current[:celluloid_actor] = nil Thread.current[:celluloid_mailbox] = nil end
ruby
{ "resource": "" }
q15251
Celluloid.Actor.cleanup
train
def cleanup(exit_event) # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Celluloid::Probe.actor_died(self) if $CELLULOID_MONITORING # rubocop:enable Style/GlobalVars @mailbox.shutdown @links.each do |actor| actor.mailbox << exit_event if actor.mailbox.alive? end tasks.to_a.each do |task| begin task.terminate rescue DeadTaskError # TODO: not tested (failed on Travis) end end rescue => ex # TODO: metadata Internals::Logger.crash("CLEANUP CRASHED!", ex) end
ruby
{ "resource": "" }
q15252
Celluloid.Task.suspend
train
def suspend(status) raise "Cannot suspend while in exclusive mode" if exclusive? raise "Cannot suspend a task from outside of itself" unless Task.current == self @status = status # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars if $CELLULOID_DEBUG && @dangerous_suspend Internals::Logger.with_backtrace(caller[2...8]) do |logger| logger.warn "Dangerously suspending task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" end end # rubocop:enable Style/GlobalVars value = signal @status = :running raise value if value.is_a?(Celluloid::Interruption) value end
ruby
{ "resource": "" }
q15253
Celluloid.Task.resume
train
def resume(value = nil) guard "Cannot resume a task from inside of a task" if Thread.current[:celluloid_task] if running? deliver(value) else # rubocop:disable Metrics/LineLength Internals::Logger.warn "Attempted to resume a dead task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" # rubocop:enable Metrics/LineLength end nil end
ruby
{ "resource": "" }
q15254
Celluloid.Task.terminate
train
def terminate raise "Cannot terminate an exclusive task" if exclusive? if running? # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars if $CELLULOID_DEBUG Internals::Logger.with_backtrace(backtrace) do |logger| type = @dangerous_suspend ? :warn : :debug logger.send(type, "Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}") end end # rubocop:enable Style/GlobalVars exception = TaskTerminated.new("task was terminated") exception.set_backtrace(caller) resume exception else raise DeadTaskError, "task is already dead" end end
ruby
{ "resource": "" }
q15255
Celluloid.Cell.shutdown
train
def shutdown return unless @finalizer && @subject.respond_to?(@finalizer, true) task(:finalizer, @finalizer, { call: @finalizer, subject: @subject }, dangerous_suspend: true, &Cell.shutdown) end
ruby
{ "resource": "" }
q15256
Celluloid.Mailbox.<<
train
def <<(message) @mutex.lock begin if mailbox_full || @dead dead_letter(message) return end if message.is_a?(SystemEvent) # SystemEvents are high priority messages so they get added to the # head of our message queue instead of the end @messages.unshift message else @messages << message end @condition.signal nil ensure begin @mutex.unlock rescue nil end end end
ruby
{ "resource": "" }
q15257
Celluloid.Mailbox.check
train
def check(timeout = nil, &block) message = nil @mutex.lock begin raise MailboxDead, "attempted to receive from a dead mailbox" if @dead message = nil Timers::Wait.for(timeout) do |remaining| message = next_message(&block) break if message @condition.wait(@mutex, remaining) end ensure begin @mutex.unlock rescue nil end end message end
ruby
{ "resource": "" }
q15258
Celluloid.Mailbox.receive
train
def receive(timeout = nil, &block) message = nil Timers::Wait.for(timeout) do |_remaining| message = check(timeout, &block) break if message end return message if message raise TaskTimeout, "receive timeout exceeded" end
ruby
{ "resource": "" }
q15259
Celluloid.Mailbox.shutdown
train
def shutdown raise MailboxDead, "mailbox already shutdown" if @dead @mutex.lock begin yield if block_given? messages = @messages @messages = [] @dead = true ensure begin @mutex.unlock rescue nil end end messages.each do |msg| dead_letter msg msg.cleanup if msg.respond_to? :cleanup end true end
ruby
{ "resource": "" }
q15260
Celluloid.Mailbox.next_message
train
def next_message message = nil if block_given? index = @messages.index do |msg| yield(msg) || msg.is_a?(SystemEvent) end message = @messages.slice!(index, 1).first if index else message = @messages.shift end message end
ruby
{ "resource": "" }
q15261
Celluloid.Incident.merge
train
def merge(*other_incidents) merged_events = other_incidents.flatten.inject(events) do |events, incident| events += incident.events end Incident.new(merged_events.sort, triggering_event) end
ruby
{ "resource": "" }
q15262
Celluloid.Actor.handle_system_event
train
def handle_system_event(event) if handler = SystemEvent.handle(event.class) send(handler, event) else # !!! DO NOT INTRODUCE ADDITIONAL GLOBAL VARIABLES !!! # rubocop:disable Style/GlobalVars Internals::Logger.debug "Discarded message (unhandled): #{message}" if $CELLULOID_DEBUG # rubocop:enable Style/GlobalVars end end
ruby
{ "resource": "" }
q15263
Celluloid.IncidentLogger.add
train
def add(severity, message = nil, progname = nil, &block) progname ||= @progname severity ||= UNKNOWN return event.id if severity < @level if message.nil? && !block_given? message = progname progname = @progname end event = LogEvent.new(severity, message, progname, &block) @buffers[progname][severity] << event if severity >= @threshold begin Celluloid::Notifications.notifier.async.publish(incident_topic, create_incident(event)) rescue => ex @fallback_logger.error(ex) end end event.id end
ruby
{ "resource": "" }
q15264
Redwood.CryptoManager.decrypt
train
def decrypt payload, armor=false # a RubyMail::Message object return unknown_status(@not_working_reason) unless @not_working_reason.nil? gpg_opts = {:protocol => GPGME::PROTOCOL_OpenPGP} gpg_opts = HookManager.run("gpg-options", {:operation => "decrypt", :options => gpg_opts}) || gpg_opts ctx = GPGME::Ctx.new(gpg_opts) cipher_data = GPGME::Data.from_str(format_payload(payload)) if GPGME::Data.respond_to?('empty') plain_data = GPGME::Data.empty else plain_data = GPGME::Data.empty! end begin ctx.decrypt_verify(cipher_data, plain_data) rescue GPGME::Error => exc return Chunk::CryptoNotice.new(:invalid, "This message could not be decrypted", gpgme_exc_msg(exc.message)) end begin sig = self.verified_ok? ctx.verify_result rescue ArgumentError => exc sig = unknown_status [gpgme_exc_msg(exc.message)] end plain_data.seek(0, IO::SEEK_SET) output = plain_data.read output.transcode(Encoding::ASCII_8BIT, output.encoding) ## TODO: test to see if it is still necessary to do a 2nd run if verify ## fails. # ## check for a valid signature in an extra run because gpg aborts if the ## signature cannot be verified (but it is still able to decrypt) #sigoutput = run_gpg "#{payload_fn.path}" #sig = self.old_verified_ok? sigoutput, $? if armor msg = RMail::Message.new # Look for Charset, they are put before the base64 crypted part charsets = payload.body.split("\n").grep(/^Charset:/) if !charsets.empty? and charsets[0] =~ /^Charset: (.+)$/ output.transcode($encoding, $1) end msg.body = output else # It appears that some clients use Windows new lines - CRLF - but RMail # splits the body and header on "\n\n". So to allow the parse below to # succeed, we will convert the newlines to what RMail expects output = output.gsub(/\r\n/, "\n") # This is gross. This decrypted payload could very well be a multipart # element itself, as opposed to a simple payload. For example, a # multipart/signed element, like those generated by Mutt when encrypting # and signing a message (instead of just clearsigning the body). # Supposedly, decrypted_payload being a multipart element ought to work # out nicely because Message::multipart_encrypted_to_chunks() runs the # decrypted message through message_to_chunks() again to get any # children. However, it does not work as intended because these inner # payloads need not carry a MIME-Version header, yet they are fed to # RMail as a top-level message, for which the MIME-Version header is # required. This causes for the part not to be detected as multipart, # hence being shown as an attachment. If we detect this is happening, # we force the decrypted payload to be interpreted as MIME. msg = RMail::Parser.read output if msg.header.content_type =~ %r{^multipart/} && !msg.multipart? output = "MIME-Version: 1.0\n" + output output.fix_encoding! msg = RMail::Parser.read output end end notice = Chunk::CryptoNotice.new :valid, "This message has been decrypted for display" [notice, sig, msg] end
ruby
{ "resource": "" }
q15265
Redwood.Logger.send_message
train
def send_message m @mutex.synchronize do @sinks.each do |sink| sink << m sink.flush if sink.respond_to?(:flush) and level == "debug" end @buf << m end end
ruby
{ "resource": "" }
q15266
Redwood.MBox.each_raw_message_line
train
def each_raw_message_line offset @mutex.synchronize do ensure_open @f.seek offset until @f.eof? || MBox::is_break_line?(l = @f.gets) yield l end end end
ruby
{ "resource": "" }
q15267
Redwood.AccountManager.add_account
train
def add_account hash, default=false raise ArgumentError, "no email specified for account" unless hash[:email] unless default [:name, :sendmail, :signature, :gpgkey].each { |k| hash[k] ||= @default_account.send(k) } end hash[:alternates] ||= [] fail "alternative emails are not an array: #{hash[:alternates]}" unless hash[:alternates].kind_of? Array [:name, :signature].each { |x| hash[x] ? hash[x].fix_encoding! : nil } a = Account.new hash @accounts[a] = true if default raise ArgumentError, "multiple default accounts" if @default_account @default_account = a end ([hash[:email]] + hash[:alternates]).each do |email| next if @email_map.member? email @email_map[email] = a end hash[:regexen].each do |re| @regexen[Regexp.new(re)] = a end if hash[:regexen] end
ruby
{ "resource": "" }
q15268
Redwood.ThreadIndexMode.select
train
def select t=nil, when_done=nil t ||= cursor_thread or return Redwood::reporting_thread("load messages for thread-view-mode") do num = t.size message = "Loading #{num.pluralize 'message body'}..." BufferManager.say(message) do |sid| t.each_with_index do |(m, *_), i| next unless m BufferManager.say "#{message} (#{i}/#{num})", sid if t.size > 1 m.load_from_source! end end mode = ThreadViewMode.new t, @hidden_labels, self BufferManager.spawn t.subj, mode BufferManager.draw_screen mode.jump_to_first_open if $config[:jump_to_open_message] BufferManager.draw_screen # lame TODO: make this unnecessary ## the first draw_screen is needed before topline and botline ## are set, and the second to show the cursor having moved t.remove_label :unread Index.save_thread t update_text_for_line curpos UpdateManager.relay self, :read, t.first when_done.call if when_done end end
ruby
{ "resource": "" }
q15269
Redwood.ThreadIndexMode.multi_toggle_spam
train
def multi_toggle_spam threads undos = threads.map { |t| actually_toggle_spammed t } threads.each { |t| HookManager.run("mark-as-spam", :thread => t) } UndoManager.register "marking/unmarking #{threads.size.pluralize 'thread'} as spam", undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } } regen_text threads.each { |t| Index.save_thread t } end
ruby
{ "resource": "" }
q15270
Redwood.ThreadIndexMode.multi_toggle_deleted
train
def multi_toggle_deleted threads undos = threads.map { |t| actually_toggle_deleted t } UndoManager.register "deleting/undeleting #{threads.size.pluralize 'thread'}", undos, lambda { regen_text }, lambda { threads.each { |t| Index.save_thread t } } regen_text threads.each { |t| Index.save_thread t } end
ruby
{ "resource": "" }
q15271
Redwood.ThreadIndexMode.multi_kill
train
def multi_kill threads UndoManager.register "killing/unkilling #{threads.size.pluralize 'threads'}" do threads.each do |t| if t.toggle_label :killed add_or_unhide t.first else hide_thread t end end.each do |t| UpdateManager.relay self, :labeled, t.first Index.save_thread t end regen_text end threads.each do |t| if t.toggle_label :killed hide_thread t else add_or_unhide t.first end end.each do |t| # send 'labeled'... this might be more specific UpdateManager.relay self, :labeled, t.first Index.save_thread t end killed, unkilled = threads.partition { |t| t.has_label? :killed }.map(&:size) BufferManager.flash "#{killed.pluralize 'thread'} killed, #{unkilled} unkilled" regen_text end
ruby
{ "resource": "" }
q15272
Redwood.ThreadIndexMode.thread_matches?
train
def thread_matches? t, query t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query } end
ruby
{ "resource": "" }
q15273
Redwood.ThreadIndexMode.author_names_and_newness_for_thread
train
def author_names_and_newness_for_thread t, limit=nil new = {} seen = {} authors = t.map do |m, *o| next unless m && m.from new[m.from] ||= m.has_label?(:unread) next if seen[m.from] seen[m.from] = true m.from end.compact result = [] authors.each do |a| break if limit && result.size >= limit name = if AccountManager.is_account?(a) "me" elsif t.authors.size == 1 a.mediumname else a.shortname end result << [name, new[a]] end if result.size == 1 && (author_and_newness = result.assoc("me")) unless (recipients = t.participants - t.authors).empty? result = recipients.collect do |r| break if limit && result.size >= limit name = (recipients.size == 1) ? r.mediumname : r.shortname ["(#{name})", author_and_newness[1]] end end end result end
ruby
{ "resource": "" }
q15274
Redwood.Buffer.write
train
def write y, x, s, opts={} return if x >= @width || y >= @height @w.attrset Colormap.color_for(opts[:color] || :none, opts[:highlight]) s ||= "" maxl = @width - x # maximum display width width # fill up the line with blanks to overwrite old screen contents @w.mvaddstr y, x, " " * maxl unless opts[:no_fill] @w.mvaddstr y, x, s.slice_by_display_length(maxl) end
ruby
{ "resource": "" }
q15275
Redwood.BufferManager.roll_buffers
train
def roll_buffers bufs = rollable_buffers bufs.last.force_to_top = false raise_to_front bufs.first end
ruby
{ "resource": "" }
q15276
Redwood.BufferManager.ask_for_labels
train
def ask_for_labels domain, question, default_labels, forbidden_labels=[] default_labels = default_labels - forbidden_labels - LabelManager::RESERVED_LABELS default = default_labels.to_a.join(" ") default += " " unless default.empty? # here I would prefer to give more control and allow all_labels instead of # user_defined_labels only applyable_labels = (LabelManager.user_defined_labels - forbidden_labels).map { |l| LabelManager.string_for l }.sort_by { |s| s.downcase } answer = ask_many_with_completions domain, question, applyable_labels, default return unless answer user_labels = answer.to_set_of_symbols user_labels.each do |l| if forbidden_labels.include?(l) || LabelManager::RESERVED_LABELS.include?(l) BufferManager.flash "'#{l}' is a reserved label!" return end end user_labels end
ruby
{ "resource": "" }
q15277
Redwood.BufferManager.ask
train
def ask domain, question, default=nil, &block raise "impossible!" if @asking raise "Question too long" if Ncurses.cols <= question.length @asking = true @textfields[domain] ||= TextField.new tf = @textfields[domain] completion_buf = nil status, title = get_status_and_title @focus_buf Ncurses.sync do tf.activate Ncurses.stdscr, Ncurses.rows - 1, 0, Ncurses.cols, question, default, &block @dirty = true # for some reason that blanks the whole fucking screen draw_screen :sync => false, :status => status, :title => title tf.position_cursor Ncurses.refresh end while true c = Ncurses::CharCode.get next unless c.present? # getch timeout break unless tf.handle_input c # process keystroke if tf.new_completions? kill_buffer completion_buf if completion_buf shorts = tf.completions.map { |full, short| short } prefix_len = shorts.shared_prefix(caseless=true).length mode = CompletionMode.new shorts, :header => "Possible completions for \"#{tf.value}\": ", :prefix_len => prefix_len completion_buf = spawn "<completions>", mode, :height => 10 draw_screen :skip_minibuf => true tf.position_cursor elsif tf.roll_completions? completion_buf.mode.roll draw_screen :skip_minibuf => true tf.position_cursor end Ncurses.sync { Ncurses.refresh } end kill_buffer completion_buf if completion_buf @dirty = true @asking = false Ncurses.sync do tf.deactivate draw_screen :sync => false, :status => status, :title => title end tf.value.tap { |x| x } end
ruby
{ "resource": "" }
q15278
Redwood.ContactManager.drop_contact
train
def drop_contact person aalias = @p2a[person] @p2a.delete person @e2p.delete person.email @a2p.delete aalias if aalias end
ruby
{ "resource": "" }
q15279
Redwood.ThreadViewMode.regen_text
train
def regen_text @text = [] @chunk_lines = [] @message_lines = [] @person_lines = [] prevm = nil @thread.each do |m, depth, parent| unless m.is_a? Message # handle nil and :fake_root @text += chunk_to_lines m, nil, @text.length, depth, parent next end l = @layout[m] ## is this still necessary? next unless @layout[m].state # skip discarded drafts ## build the patina text = chunk_to_lines m, l.state, @text.length, depth, parent, l.color, l.star_color l.top = @text.length l.bot = @text.length + text.length # updated below l.prev = prevm l.next = nil l.depth = depth # l.state we preserve l.width = 0 # updated below @layout[l.prev].next = m if l.prev (0 ... text.length).each do |i| @chunk_lines[@text.length + i] = m @message_lines[@text.length + i] = m lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.display_length }.sum end @text += text prevm = m if l.state != :closed m.chunks.each do |c| cl = @chunk_layout[c] ## set the default state for chunks cl.state ||= if c.expandable? && c.respond_to?(:initial_state) c.initial_state else :closed end text = chunk_to_lines c, cl.state, @text.length, depth (0 ... text.length).each do |i| @chunk_lines[@text.length + i] = c @message_lines[@text.length + i] = m lw = text[i].flatten.select { |x| x.is_a? String }.map { |x| x.display_length }.sum - (depth * @indent_spaces) l.width = lw if lw > l.width end @text += text end @layout[m].bot = @text.length end end end
ruby
{ "resource": "" }
q15280
Redwood.Index.num_results_for
train
def num_results_for query={} xapian_query = build_xapian_query query matchset = run_query xapian_query, 0, 0, 100 matchset.matches_estimated end
ruby
{ "resource": "" }
q15281
Redwood.Index.build_message
train
def build_message id entry = synchronize { get_entry id } return unless entry locations = entry[:locations].map do |source_id,source_info| source = SourceManager[source_id] raise "invalid source #{source_id}" unless source Location.new source, source_info end m = Message.new :locations => locations, :labels => entry[:labels], :snippet => entry[:snippet] # Try to find person from contacts before falling back to # generating it from the address. mk_person = lambda { |x| Person.from_name_and_email(*x.reverse!) } entry[:from] = mk_person[entry[:from]] entry[:to].map!(&mk_person) entry[:cc].map!(&mk_person) entry[:bcc].map!(&mk_person) m.load_from_index! entry m end
ruby
{ "resource": "" }
q15282
Redwood.Index.load_contacts
train
def load_contacts email_addresses, opts={} contacts = Set.new num = opts[:num] || 20 each_id_by_date :participants => email_addresses do |id,b| break if contacts.size >= num m = b.call ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] } end contacts.to_a.compact[0...num].map { |n,e| Person.from_name_and_email n, e } end
ruby
{ "resource": "" }
q15283
Redwood.Index.index_message_static
train
def index_message_static m, doc, entry # Person names are indexed with several prefixes person_termer = lambda do |d| lambda do |p| doc.index_text p.name, PREFIX["#{d}_name"][:prefix] if p.name doc.index_text p.email, PREFIX['email_text'][:prefix] doc.add_term mkterm(:email, d, p.email) end end person_termer[:from][m.from] if m.from (m.to+m.cc+m.bcc).each(&(person_termer[:to])) # Full text search content subject_text = m.indexable_subject body_text = m.indexable_body doc.index_text subject_text, PREFIX['subject'][:prefix] doc.index_text body_text, PREFIX['body'][:prefix] m.attachments.each { |a| doc.index_text a, PREFIX['attachment'][:prefix] } # Miscellaneous terms doc.add_term mkterm(:date, m.date) if m.date doc.add_term mkterm(:type, 'mail') doc.add_term mkterm(:msgid, m.id) m.attachments.each do |a| a =~ /\.(\w+)$/ or next doc.add_term mkterm(:attachment_extension, $1) end # Date value for range queries date_value = begin Xapian.sortable_serialise m.date.to_i rescue TypeError Xapian.sortable_serialise 0 end doc.add_value MSGID_VALUENO, m.id doc.add_value DATE_VALUENO, date_value end
ruby
{ "resource": "" }
q15284
Redwood.Index.mkterm
train
def mkterm type, *args case type when :label PREFIX['label'][:prefix] + args[0].to_s.downcase when :type PREFIX['type'][:prefix] + args[0].to_s.downcase when :date PREFIX['date'][:prefix] + args[0].getutc.strftime("%Y%m%d%H%M%S") when :email case args[0] when :from then PREFIX['from_email'][:prefix] when :to then PREFIX['to_email'][:prefix] else raise "Invalid email term type #{args[0]}" end + args[1].to_s.downcase when :source_id PREFIX['source_id'][:prefix] + args[0].to_s.downcase when :location PREFIX['location'][:prefix] + [args[0]].pack('n') + args[1].to_s when :attachment_extension PREFIX['attachment_extension'][:prefix] + args[0].to_s.downcase when :msgid, :ref, :thread PREFIX[type.to_s][:prefix] + args[0][0...(MAX_TERM_LENGTH-1)] else raise "Invalid term type #{type}" end end
ruby
{ "resource": "" }
q15285
Redwood.ThreadSet.link
train
def link p, c, overwrite=false if p == c || p.descendant_of?(c) || c.descendant_of?(p) # would create a loop #puts "*** linking parent #{p.id} and child #{c.id} would create a loop" return end #puts "in link for #{p.id} to #{c.id}, perform? #{c.parent.nil?} || #{overwrite}" return unless c.parent.nil? || overwrite remove_container c p.children << c c.parent = p ## if the child was previously a top-level container, it now ain't, ## so ditch our thread and kill it if necessary prune_thread_of c end
ruby
{ "resource": "" }
q15286
Redwood.ThreadSet.load_thread_for_message
train
def load_thread_for_message m, opts={} good = @index.each_message_in_thread_for m, opts do |mid, builder| next if contains_id? mid add_message builder.call end add_message m if good end
ruby
{ "resource": "" }
q15287
Redwood.ThreadSet.add_thread
train
def add_thread t raise "duplicate" if @threads.values.member? t t.each { |m, *o| add_message m } end
ruby
{ "resource": "" }
q15288
Redwood.ThreadSet.join_threads
train
def join_threads threads return if threads.size < 2 containers = threads.map do |t| c = @messages.member?(t.first.id) ? @messages[t.first.id] : nil raise "not in threadset: #{t.first.id}" unless c && c.message c end ## use subject headers heuristically parent = containers.find { |c| !c.is_reply? } ## no thread was rooted by a non-reply, so make a fake parent parent ||= @messages["joining-ref-" + containers.map { |c| c.id }.join("-")] containers.each do |c| next if c == parent c.message.add_ref parent.id link parent, c end true end
ruby
{ "resource": "" }
q15289
Redwood.ThreadSet.add_message
train
def add_message message el = @messages[message.id] return if el.message # we've seen it before #puts "adding: #{message.id}, refs #{message.refs.inspect}" el.message = message oldroot = el.root ## link via references: (message.refs + [el.id]).inject(nil) do |prev, ref_id| ref = @messages[ref_id] link prev, ref if prev ref end ## link via in-reply-to: message.replytos.each do |ref_id| ref = @messages[ref_id] link ref, el, true break # only do the first one end root = el.root key = if thread_by_subj? Message.normalize_subj root.subj else root.id end ## check to see if the subject is still the same (in the case ## that we first added a child message with a different ## subject) if root.thread if @threads.member?(key) && @threads[key] != root.thread @threads.delete key end else thread = @threads[key] thread << root root.thread = thread end ## last bit @num_messages += 1 end
ruby
{ "resource": "" }
q15290
Redwood.Message.load_from_source!
train
def load_from_source! @chunks ||= begin ## we need to re-read the header because it contains information ## that we don't store in the index. actually i think it's just ## the mailing list address (if any), so this is kinda overkill. ## i could just store that in the index, but i think there might ## be other things like that in the future, and i'd rather not ## bloat the index. ## actually, it's also the differentiation between to/cc/bcc, ## so i will keep this. rmsg = location.parsed_message parse_header rmsg.header message_to_chunks rmsg rescue SourceError, SocketError, RMail::EncodingUnsupportedError => e warn_with_location "problem reading message #{id}" debug "could not load message: #{location.inspect}, exception: #{e.inspect}" [Chunk::Text.new(error_message.split("\n"))] rescue Exception => e warn_with_location "problem reading message #{id}" debug "could not load message: #{location.inspect}, exception: #{e.inspect}" raise e end end
ruby
{ "resource": "" }
q15291
Redwood.Message.indexable_content
train
def indexable_content load_from_source! [ from && from.indexable_content, to.map { |p| p.indexable_content }, cc.map { |p| p.indexable_content }, bcc.map { |p| p.indexable_content }, indexable_chunks.map { |c| c.lines.map { |l| l.fix_encoding! } }, indexable_subject, ].flatten.compact.join " " end
ruby
{ "resource": "" }
q15292
Redwood.Message.multipart_signed_to_chunks
train
def multipart_signed_to_chunks m if m.body.size != 2 warn_with_location "multipart/signed with #{m.body.size} parts (expecting 2)" return end payload, signature = m.body if signature.multipart? warn_with_location "multipart/signed with payload multipart #{payload.multipart?} and signature multipart #{signature.multipart?}" return end ## this probably will never happen if payload.header.content_type && payload.header.content_type.downcase == "application/pgp-signature" warn_with_location "multipart/signed with payload content type #{payload.header.content_type}" return end if signature.header.content_type && signature.header.content_type.downcase != "application/pgp-signature" ## unknown signature type; just ignore. #warn "multipart/signed with signature content type #{signature.header.content_type}" return end [CryptoManager.verify(payload, signature), message_to_chunks(payload)].flatten.compact end
ruby
{ "resource": "" }
q15293
Redwood.LabelManager.string_for
train
def string_for l if RESERVED_LABELS.include? l l.to_s.capitalize else l.to_s end end
ruby
{ "resource": "" }
q15294
Redwood.ScrollMode.search_goto_pos
train
def search_goto_pos line, leftcol, rightcol search_goto_line line if rightcol > self.rightcol # if it's occluded... jump_to_col [rightcol - buffer.content_width + 1, 0].max # move right end end
ruby
{ "resource": "" }
q15295
Redwood.ScrollMode.jump_to_line
train
def jump_to_line l l = l.clamp 0, lines - 1 return if @topline == l @topline = l @botline = [l + buffer.content_height, lines].min buffer.mark_dirty end
ruby
{ "resource": "" }
q15296
Redwood.LineCursorMode.page_down
train
def page_down ## if we're on the last page, and it's not a full page, just move ## the cursor down to the bottom and assume we can't load anything ## else via the callbacks. if topline > lines - buffer.content_height set_cursor_pos(lines - 1) ## if we're on the last page, and it's a full page, try and load ## more lines via the callbacks and then shift the page down elsif topline == lines - buffer.content_height call_load_more_callbacks buffer.content_height super ## otherwise, just move down else relpos = @curpos - topline super set_cursor_pos [topline + relpos, lines - 1].min end end
ruby
{ "resource": "" }
q15297
Redwood.TextField.get_cursed_value
train
def get_cursed_value return nil unless @field x = Ncurses.curx form_driver_key Ncurses::Form::REQ_VALIDATION v = @field.field_buffer(0).gsub(/^\s+|\s+$/, "") ## cursor <= end of text if x - @question.length - v.length <= 0 v else # trailing spaces v + (" " * (x - @question.length - v.length)) end # ncurses returns a ASCII-8BIT (binary) string, which # bytes presumably are of current charset encoding. we force_encoding # so that the char representation / string is tagged will be the # system locale and also hopefully the terminal/input encoding. an # incorrectly configured terminal encoding (not matching the system # encoding) will produce erronous results, but will also do that for # a lot of other programs since it is impossible to detect which is # which and what encoding the inputted byte chars are supposed to have. v.force_encoding($encoding).fix_encoding! end
ruby
{ "resource": "" }
q15298
WebsocketRails.BaseController.trigger_success
train
def trigger_success(data=nil) event.success = true event.data = data event.trigger end
ruby
{ "resource": "" }
q15299
WebsocketRails.BaseController.trigger_failure
train
def trigger_failure(data=nil) event.success = false event.data = data event.trigger end
ruby
{ "resource": "" }