def parse
      download_files

      parsing_clients = false
      parsing_prefile = false
      parsing_general = false
      parsing_servers = false
      parsing_voice_servers = false

      File.open(DATA_FILE_PATH, 'r:ascii-8bit').each { |line|

        if line.start_with? ";"
          parsing_clients = false
          parsing_prefile = false
          parsing_general = false
          parsing_servers = false
          parsing_voice_servers = false
        elsif parsing_clients
          clienttype = line.split(":")[3]
          if clienttype.eql? "PILOT"
            @pilots << Pilot.new(line)
          elsif clienttype.eql? "ATC"
            @atc << ATC.new(line)
          end
        elsif parsing_prefile
          @prefiles << Prefile.new(line)
        elsif parsing_general
          line_split = line.split("=")
          @general[line_split[0].strip.downcase.gsub(" ", "_")] = line_split[1].strip
        elsif parsing_servers
          @servers << Server.new(line)
        elsif parsing_voice_servers
          @voice_servers << VoiceServer.new(line) if line.length > 2 # ignore last, empty line for voice server that contains 2 characters
        end

        parsing_clients = true if line.start_with? "!CLIENTS:"
        parsing_prefile = true if line.start_with? "!PREFILE:"
        parsing_general = true if line.start_with? "!GENERAL:"
        parsing_servers = true if line.start_with? "!SERVERS:"
        parsing_voice_servers = true if line.start_with? "!VOICE SERVERS:"
      }
    end

Parse the vatsim data file and store output as necessary


def download_files
      if !File.exists?(STATUS_FILE_PATH) or File.mtime(STATUS_FILE_PATH) < Time.now - STATUS_DOWNLOAD_INTERVAL
       download_to_file STATUS_URL, STATUS_FILE_PATH
      end

      if !File.exists?(DATA_FILE_PATH) or File.mtime(DATA_FILE_PATH) < Time.now - DATA_DOWNLOAD_INTERVAL
        download_to_file random_data_url, DATA_FILE_PATH
      end
    end

def download_files if ! File . exists? ( STATUS_FILE_PATH ) or File . mtime ( STATUS_FILE_PATH ) < Time . now - STATUS_DOWNLOAD_INTERVAL download_to_file STATUS_URL , STATUS_FILE_PATH end if ! File . exists? ( DATA_FILE_PATH ) or File . mtime ( DATA_FILE_PATH ) < Time . now - DATA_DOWNLOAD_INTERVAL download_to_file random_data_url , DATA_FILE_PATH end end

Initialize the system by downloading status and vatsim data files


def download_to_file url, file
      url = URI.parse(URI.encode(url.strip))

      File.new(file, File::CREAT)

      Net::HTTP.start(url.host) { |http|
        resp = http.get(url.path)
        open(file, "wb") { |file|
          file.write(resp.body)
        }
      }
    end

def download_to_file url , file url = URI . parse ( URI . encode ( url . strip ) ) File . new ( file , File :: CREAT ) Net :: HTTP . start ( url . host ) { | http | resp = http . get ( url . path ) open ( file , "wb" ) { | file | file . write ( resp . body ) } } end


def random_data_url
      url0s = Array.new
      file = File.open(STATUS_FILE_PATH)
      file.each {|line|
        if line.start_with? "url0"
          url0s << line.split("=").last
        end
      }
      return url0s[rand(url0s.length)]
     end

def random_data_url url0s = Array . new file = File . open ( STATUS_FILE_PATH ) file . each { | line | if line . start_with? "url0" url0s << line . split ( "=" ) . last end } return url0s [ rand ( url0s . length ) ] end

Return random vatsim data url from status file


def cachier!(var = nil)
      if var && instance_variable_get("@#{var}")
        # => Clear the Single Variable
        remove_instance_variable("@#{var}")
      else
        # => Clear the Whole Damned Cache
        instance_variables.each { |x| remove_instance_variable(x) }
      end
    end

def
cachier!
(
var
=
)
if
var
&&
instance_variable_get
(
"@#{var}"
)
# => Clear the Single Variable
remove_instance_variable
(
"@#{var}"
)
else
# => Clear the Whole Damned Cache
instance_variables
.
each
{
|
x
|
remove_instance_variable
(
x
)
}
end
end


def write_json(file, object)
      return unless file && object
      begin
        File.open(file, 'w') { |f| f.write(JSON.pretty_generate(object)) }
      end
    end

def write_json ( file , object ) return unless file && object begin File . open ( file , 'w' ) { | f | f . write ( JSON . pretty_generate ( object ) ) } end end


def filestring(file, size = 8192)
      return unless file
      return file unless file.is_a?(String) && File.file?(file) && File.size(file) <= size
      File.read(file)
    end

def filestring ( file , size = 8192 ) return unless file return file unless file . is_a? ( String ) && File . file? ( file ) && File . size ( file ) <= size File . read ( file ) end

=> Check if a string is an existing file, and return it's content

= > Check if a string is an existing file and return it s content


def common_array(ary) # rubocop: disable AbcSize
      return ary unless ary.is_a? Array
      count = ary.count
      return ary if count.zero?
      return ary.flatten.uniq if count == 1
      common = ary[0] & ary[1]
      return common if count == 2
      (count - 2).times { |x| common &= ary[x + 2] } if count > 2
      common
    end

def
common_array
(
ary
)
# rubocop: disable AbcSize
return
ary
unless
ary
.
is_a?
Array
count
=
ary
.
count
return
ary
if
count
.
zero?
return
ary
.
flatten
.
uniq
if
count
==
1
common
=
ary
[
0
]
&
ary
[
1
]
return
common
if
count
==
2
(
count
2
)
.
times
{
|
x
|
common
&=
ary
[
x
+
2
]
}
if
count
>
2
common
end


def run
      bind_queues and return if test_env?
      start_shutdown_thread
      start_error_counter_thread
      client.on_exception do |e|
        count_error(e)
      end
      client.connect
      start_event_thread

      puts 'EventListener started. Hit Ctrl-C to exit'
      Thread.stop
      puts 'Main thread wakeup - exiting.'
      client.close
    end

Initialize a new EventListener daemon instance
 @param [Hash] options daemon options
 @option options [Integer] :error_limit (10) maximum number of errors that are allowed to occur within error_interval
   before the process terminates
 @option options [Integer] :error_interval (3600) time interval, in seconds, before the error counter is cleared
 @option options [String] :events_exchange ('events') name of AMQP exchange used for listening to event messages
 @option options [String] :models_exchange ('models') name of AMQP exchange used for listening to EventObserver
   instance create, update, and destroy messages
 @option options [String] :name ("#{Rails.application.class.parent_name.downcase}-listener") daemon instance name.
 Run the daemon process. This creates the event, error counter, and shutdown threads


def register_observer_class(observer_class)
      @observer_mutex.synchronize do
        return if @observed_models.include?(observer_class)
        @observed_models << observer_class
        log "EventListener: registering observer class #{observer_class}"
        observer_queue.bind(models_exchange, routing_key: "#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*")
      end
    end


def register_observer(observer)
      @observer_mutex.synchronize do
        log "EventListener: registering observer #{observer.class} #{observer.id}"
        @observers[observer_key_for(observer.class, observer.id)] = observer.observe_events(client)
      end
    end

Register an observer instance, and start listening for events on its associated queue.
 Also ensure that we are listening for observer class update events

Register an observer instance and start listening for events on its associated queue . Also ensure that we are listening for observer class update events


def unregister_observer(observer_class, observer_id)
      @observer_mutex.synchronize do
        log "EventListener: un-registering observer #{observer_class} #{observer_id}"
        if (consumer = @observers.delete(observer_key_for(observer_class, observer_id)))
          consumer.cancel
        end
      end
    end

Unregister an observer instance, and cancel consumption of messages. Any pre-fetched messages will be returned to the queue.

Unregister an observer instance and cancel consumption of messages . Any pre - fetched messages will be returned to the queue .


def observer_queue
      @observer_queue ||= client.create_queue([name, 'listener', Socket.gethostname, Process.pid].join('.'),
                                              models_exchange,
                                              queue_options:     {exclusive: true},
                                              subscribe_options: {manual_ack: true})
    end

def observer_queue @observer_queue ||= client . create_queue ( [ name , 'listener' , Socket . gethostname , Process . pid ] . join ( '.' ) , models_exchange , queue_options : { exclusive : true } , subscribe_options : { manual_ack : true } ) end

Create or return the observer queue which listens for ModelWatcher events


def as_json(options = {})
      session_id = parameters.delete(:session_id) || Thread.current[:keas_session_id]

      data = {type:          type,
              action:        action,
              user_id:       user_id,
              occurred_at:   occurred_at,
              eventful_type: eventful_type,
              eventful_id:   eventful_id,
              session_id:    session_id}
      unless options[:omit_parameters]
        data[:parameters] = parameters
        data[:attributes] = attributes
      end
      data
    end

def as_json ( options = { } ) session_id = parameters . delete ( :session_id ) || Thread . current [ :keas_session_id ] data = { type : type , action : action , user_id : user_id , occurred_at : occurred_at , eventful_type : eventful_type , eventful_id : eventful_id , session_id : session_id } unless options [ :omit_parameters ] data [ :parameters ] = parameters data [ :attributes ] = attributes end data end

Return hash of data to be serialized to JSON
 @option options [Boolean] :omit_parameters when set, do not include attributes or parameters in data
 @return [Hash] data to serialize


def do_create(action)
      options = do_creation_options
      options.title ||= @params.first

      @helper.send("#{action}_usage") unless options.title
      fn = @commands.send(action, options)
      puts "#{@src_dir}/#{fn}"
    end

def do_create ( action ) options = do_creation_options options . title ||= @params . first @helper . send ( "#{action}_usage" ) unless options . title fn = @commands . send ( action , options ) puts "#{@src_dir}/#{fn}" end

action is a string, either 'post' or 'draft'


def do_move(action)
      options = do_move_options(action)
      path = @params.first

      @helper.send("#{action}_usage") unless path
      fn = @commands.send(action, path, options)
      puts "#{@src_dir}/#{fn}"
    end

def do_move ( action ) options = do_move_options ( action ) path = @params . first @helper . send ( "#{action}_usage" ) unless path fn = @commands . send ( action , path , options ) puts "#{@src_dir}/#{fn}" end

action is a string, either 'publish' or 'unpublish'

action is a string either publish or unpublish


def do_move_options(type)
      options = OpenStruct.new
      opt_parser = OptionParser.new do |opts|
        if type == 'publish'
          opts.on('-d', '--keep-draft', "Keep draft post") do |d|
            options.keep_draft = d
          end
        else
          opts.on('-p', '--keep-post', "Do not delete post") do |p|
            options.keep_post = p
          end
        end

        opts.on('-t', '--keep-timestamp', "Keep existing timestamp") do |t|
          options.keep_timestamp = t
        end
      end

      opt_parser.parse! @params
      options
    end

def
do_move_options
(
type
)
options
=
OpenStruct
.
new
opt_parser
=
OptionParser
.
new
do
|
opts
|
if
type
==
'publish'
opts
.
on
(
'-d'
,
'--keep-draft'
,
"Keep draft post"
)
do
|
d
|
options
.
keep_draft
=
d
end
else
opts
.
on
(
'-p'
,
'--keep-post'
,
"Do not delete post"
)
do
|
p
|
options
.
keep_post
=
p
end
end
opts
.
on
(
'-t'
,
'--keep-timestamp'
,
"Keep existing timestamp"
)
do
|
t
|
options
.
keep_timestamp
=
t
end
end
opt_parser
.
parse!
@params
options
end

pass a string, either publish or unpublish

pass a string either publish or unpublish


def resolve_links(text)
      html = Nokogiri::HTML.fragment(text)
      html.css("a[href]").each do |link|
        href = URI(link["href"])
        next unless href.relative? && markup_for_file(nil, href.path) == :markdown
        link.replace "{file:#{href} #{link.inner_html}}"
      end
      super(html.to_s)
    end

def
resolve_links
(
text
)
html
=
Nokogiri
::
HTML
.
fragment
(
text
)
html
.
css
(
"a[href]"
)
.
each
do
|
link
|
href
=
URI
(
link
[
"href"
]
)
next
unless
href
.
relative?
&&
markup_for_file
(
,
href
.
path
)
==
:markdown
link
.
replace
"{file:#{href} #{link.inner_html}}"
end
super
(
html
.
to_s
)
end

Resolves relative links to Markdown files.
 @param [String] text the HTML fragment in which to resolve links.
 @return [String] HTML with relative links to Markdown files converted to `{file:}` links.

Resolves relative links to Markdown files .


def nr_api
      # => Build the Faraday Connection
      @conn ||= Faraday::Connection.new('https://api.newrelic.com', conn_opts) do |client|
        client.use Faraday::Response::RaiseError
        client.use FaradayMiddleware::EncodeJson
        client.use FaradayMiddleware::ParseJson, content_type: /\bjson$/
        client.response :logger if Config.environment.to_s.casecmp('development').zero? # => Log Requests to STDOUT
        client.adapter Faraday.default_adapter #:net_http_persistent
      end
    end

def
nr_api
# => Build the Faraday Connection
@conn
||=
Faraday
::
Connection
.
new
(
'https://api.newrelic.com'
,
conn_opts
)
do
|
client
|
client
.
use
Faraday
::
Response
::
RaiseError
client
.
use
FaradayMiddleware
::
EncodeJson
client
.
use
FaradayMiddleware
::
ParseJson
,
content_type
:
/
\b
/
client
.
response
:logger
if
Config
.
environment
.
to_s
.
casecmp
(
'development'
)
.
zero?
# => Log Requests to STDOUT
client
.
adapter
Faraday
.
default_adapter
#:net_http_persistent
end
end


def alert_add_entity(entity_id, condition_id, entity_type = 'Server')
      nr_api.put do |req|
        req.url url('alerts_entity_conditions', entity_id)
        req.params['entity_type'] = entity_type
        req.params['condition_id'] = condition_id
      end
    end

def alert_add_entity ( entity_id , condition_id , entity_type = 'Server' ) nr_api . put do | req | req . url url ( 'alerts_entity_conditions' , entity_id ) req . params [ 'entity_type' ] = entity_type req . params [ 'condition_id' ] = condition_id end end

=> Add an Entitity to an Existing Alert Policy

= > Add an Entitity to an Existing Alert Policy


def alert_delete_entity(entity_id, condition_id, entity_type = 'Server')
      nr_api.delete do |req|
        req.url url('alerts_entity_conditions', entity_id)
        req.params['entity_type'] = entity_type
        req.params['condition_id'] = condition_id
      end
    end

def alert_delete_entity ( entity_id , condition_id , entity_type = 'Server' ) nr_api . delete do | req | req . url url ( 'alerts_entity_conditions' , entity_id ) req . params [ 'entity_type' ] = entity_type req . params [ 'condition_id' ] = condition_id end end

=> Delete an Entitity from an Existing Alert Policy

= > Delete an Entitity from an Existing Alert Policy


def get_server_id(server_id)
      return nil unless server_id =~ /^[0-9]+$/
      ret = nr_api.get(url('servers', server_id)).body
      ret['server']
    rescue Faraday::ResourceNotFound, NoMethodError
      nil
    end

def get_server_id ( server_id ) return nil unless server_id =~ / / ret = nr_api . get ( url ( 'servers' , server_id ) ) . body ret [ 'server' ] rescue Faraday :: ResourceNotFound , NoMethodError nil end


def get_server_name(server, exact = true)
      ret = nr_api.get(url('servers'), 'filter[name]' => server).body
      return ret['servers'] unless exact
      ret['servers'].find { |x| x['name'].casecmp(server).zero? }
    rescue NoMethodError
      nil
    end

def get_server_name ( server , exact = true ) ret = nr_api . get ( url ( 'servers' ) , 'filter[name]' => server ) . body return ret [ 'servers' ] unless exact ret [ 'servers' ] . find { | x | x [ 'name' ] . casecmp ( server ) . zero? } rescue NoMethodError nil end


def get_servers_labeled(labels)
      label_query = Array(labels).reject { |x| !x.include?(':') }.join(';')
      return [] unless label_query
      nr_api.get(url('servers'), 'filter[labels]' => label_query).body
    end

def get_servers_labeled ( labels ) label_query = Array ( labels ) . reject { | x | ! x . include? ( ':' ) } . join ( ';' ) return [ ] unless label_query nr_api . get ( url ( 'servers' ) , 'filter[labels]' => label_query ) . body end


def observe_events(client)
      return unless enable_listener?
      queue = create_queue(client)
      client.subscribe(queue) do |message|
        event = Event.parse(message)
        handle_event(event)
      end
    end

def observe_events ( client ) return unless enable_listener? queue = create_queue ( client ) client . subscribe ( queue ) do | message | event = Event . parse ( message ) handle_event ( event ) end end

Create or attach to a queue on the specified exchange. When an event message that matches the observer's routing keys
 is received, parse the event and call handle_event on same.
 @param [Isimud::Client] client client instance
 @return queue or consumer object
 @see BunnyClient#subscribe
 @see TestClient#subscribe

Create or attach to a queue on the specified exchange . When an event message that matches the observer s routing keys is received parse the event and call handle_event on same .


def bind(queue_name, exchange_name, *routing_keys, &block)
      queue = create_queue(queue_name, exchange_name,
                           queue_options: {durable: true},
                           routing_keys:  routing_keys)
      subscribe(queue, &block) if block_given?
    end

def bind ( queue_name , exchange_name , * routing_keys , & block ) queue = create_queue ( queue_name , exchange_name , queue_options : { durable : true } , routing_keys : routing_keys ) subscribe ( queue , block ) if block_given? end

Initialize a new BunnyClient instance. Note that a connection is not established until any other method is called

 @param [String, Hash] _url Server URL or options hash
 @param [Hash] _bunny_options optional Bunny connection options
 @see Bunny.new for connection options
 Convenience method that finds or creates a named queue, binds to an exchange, and subscribes to messages.
 If a block is provided, it will be called by the consumer each time a message is received.

 @param [String] queue_name name of the queue
 @param [String] exchange_name name of the AMQP exchange. Note that existing exchanges must be declared as Topic
   exchanges; otherwise, an error will occur
 @param [Array<String>] routing_keys list of routing keys to be bound to the queue for the specified exchange.
 @yieldparam [String] payload message text
 @return [Bunny::Consumer] Bunny consumer interface

Initialize a new BunnyClient instance . Note that a connection is not established until any other method is called


def create_queue(queue_name, exchange_name, options = {})
      queue_options = options[:queue_options] || {durable: true}
      routing_keys  = options[:routing_keys] || []
      log "Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}"
      queue = find_queue(queue_name, queue_options)
      bind_routing_keys(queue, exchange_name, routing_keys) if routing_keys.any?
      queue
    end

Find or create a named queue and bind it to the specified exchange

 @param [String] queue_name name of the queue
 @param [String] exchange_name name of the AMQP exchange. Note that pre-existing exchanges must be declared as Topic
   exchanges; otherwise, an error will occur
 @param [Hash] options queue declaration options
 @option options [Boolean] :queue_options ({durable: true}) queue declaration options -- @see Bunny::Channel#queue
 @option options [Array<String>] :routing_keys ([]) routing keys to be bound to the queue. Use "*" to match any 1 word
   in a route segment. Use "#" to match 0 or more words in a segment.
 @return [Bunny::Queue] Bunny queue


def subscribe(queue, options = {}, &block)
      queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload|
        current_channel = delivery_info.channel
        begin
          log "Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}", :debug
          Thread.current['isimud_queue_name']    = queue.name
          Thread.current['isimud_delivery_info'] = delivery_info
          Thread.current['isimud_properties']    = properties
          block.call(payload)
          if current_channel.open?
            log "Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging", :debug
            current_channel.ack(delivery_info.delivery_tag)
          else
            log "Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}", :warn
          end
        rescue => e
          log("Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\n  #{e.backtrace.join("\n  ")}", :warn)
          retry_status = run_exception_handlers(e)
          log "Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}", :warn
          current_channel.open? && current_channel.reject(delivery_info.delivery_tag, retry_status)
        end
      end
    end

Subscribe to messages on the Bunny queue. The provided block will be called each time a message is received.
   The message will be acknowledged and deleted from the queue unless an exception is raised from the block.
   In the case that an uncaught exception is raised, the message is rejected, and any declared exception handlers
   will be called.

 @param [Bunny::Queue] queue Bunny queue
 @param [Hash] options {} subscription options -- @see Bunny::Queue#subscribe
 @yieldparam [String] payload message text

Subscribe to messages on the Bunny queue . The provided block will be called each time a message is received . The message will be acknowledged and deleted from the queue unless an exception is raised from the block . In the case that an uncaught exception is raised the message is rejected and any declared exception handlers will be called .


def channel
      if (channel = Thread.current[CHANNEL_KEY]).try(:open?)
        channel
      else
        new_channel = connection.channel
        new_channel.confirm_select
        new_channel.prefetch(Isimud.prefetch_count) if Isimud.prefetch_count
        Thread.current[CHANNEL_KEY] = new_channel
      end
    end

def channel if ( channel = Thread . current [ CHANNEL_KEY ] ) . try ( :open? ) channel else new_channel = connection . channel new_channel . confirm_select new_channel . prefetch ( Isimud . prefetch_count ) if Isimud . prefetch_count Thread . current [ CHANNEL_KEY ] = new_channel end end

Open a new, thread-specific AMQP connection channel, or return the current channel for this thread if it exists
   and is currently open. New channels are created with publisher confirms enabled. Messages will be prefetched
   according to Isimud.prefetch_count when declared.
 @return [Bunny::Channel] channel instance.

Open a new thread - specific AMQP connection channel or return the current channel for this thread if it exists and is currently open . New channels are created with publisher confirms enabled . Messages will be prefetched according to Isimud . prefetch_count when declared .


def publish(exchange, routing_key, payload, options = {})
      log "Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}", :debug
      channel.topic(exchange, durable: true).publish(payload, options.merge(routing_key: routing_key, persistent: true))
    end

Publish a message to the specified exchange, which is declared as a durable, topic exchange. Note that message
   is always persisted.
 @param [String] exchange AMQP exchange name
 @param [String] routing_key message routing key. This should always be in the form of words separated by dots
   e.g. "user.goal.complete"
 @param [String] payload message payload
 @param [Hash] options additional message options
 @see Bunny::Exchange#publish
 @see http://rubybunny.info/articles/exchanges.html

Publish a message to the specified exchange which is declared as a durable topic exchange . Note that message is always persisted .


def post(opts)
      opts = @helper.ensure_open_struct(opts)
      date = @helper.get_date_stamp

      # still want to escape any garbage in the slug
      slug = if opts.slug.nil? || opts.slug.empty?
               opts.title
             else
               opts.slug
             end
      slug = @helper.get_slug_for(slug)

      # put the metadata into the layout header
      head, ext = @helper.get_layout(opts.layout)
      head.sub!(/^title:\s*$/, "title: #{opts.title}")
      head.sub!(/^date:\s*$/, "date: #{date}")
      ext ||= @ext

      path = File.join(POSTS_FOLDER, "#{date}-#{slug}.#{ext}")
      f = File.open(path, "w")
      f.write(head)
      f.close
      @helper.open_in_editor(path) # open file if config key set
      path    # return the path, in case we want to do anything useful
    end


def draft(opts)
      opts = @helper.ensure_open_struct(opts)

      # the drafts folder might not exist yet...create it just in case
      FileUtils.mkdir_p(DRAFTS_FOLDER)

      slug = if opts.slug.nil? || opts.slug.empty?
               opts.title
             else
               opts.slug
             end
      slug = @helper.get_slug_for(slug)

      # put the metadata into the layout header
      head, ext = @helper.get_layout(opts.layout)
      head.sub!(/^title:\s*$/, "title: #{opts.title}")
      head.sub!(/^date:\s*$/, "date: #{@helper.get_date_stamp}")
      ext ||= @ext

      path = File.join(DRAFTS_FOLDER, "#{slug}.#{ext}")
      f = File.open(path, "w")
      f.write(head)
      f.close
      @helper.open_in_editor(path) # open file if config key set
      path    # return the path, in case we want to do anything useful
    end


def publish(draftpath, opts={})
      opts = @helper.ensure_open_struct(opts)
      tail = File.basename(draftpath)

      begin
        infile = File.open(draftpath, "r")
      rescue Errno::ENOENT
        @helper.bad_path(draftpath)
      end

      date = @helper.get_date_stamp
      time = @helper.get_time_stamp

      outpath = File.join(POSTS_FOLDER, "#{date}-#{tail}")
      outfile = File.open(outpath, "w")

      infile.each_line do |line|
        line.sub!(/^date:.*$/, "date: #{date} #{time}\n") unless opts.keep_timestamp
        outfile.write(line)
      end

      infile.close
      outfile.close
      FileUtils.rm(draftpath) unless opts.keep_draft

      outpath
    end

def
publish
(
draftpath
,
opts
=
{
}
)
opts
=
@helper
.
ensure_open_struct
(
opts
)
tail
=
File
.
basename
(
draftpath
)
begin
infile
=
File
.
open
(
draftpath
,
"r"
)
rescue
Errno
::
ENOENT
@helper
.
bad_path
(
draftpath
)
end
date
=
@helper
.
get_date_stamp
time
=
@helper
.
get_time_stamp
outpath
=
File
.
join
(
POSTS_FOLDER
,
"#{date}-#{tail}"
)
outfile
=
File
.
open
(
outpath
,
"w"
)
infile
.
each_line
do
|
line
|
line
.
sub!
(
/
/
,
"date: #{date} #{time}\n"
)
unless
opts
.
keep_timestamp
outfile
.
write
(
line
)
end
infile
.
close
outfile
.
close
FileUtils
.
rm
(
draftpath
)
unless
opts
.
keep_draft
outpath
end

Todo make this take a path instead?

 @param draftpath [String] path to the draft, relative to source directory
 @option options :keep_draft [Boolean] if true, keep the draft file
 @option options :keep_timestamp [Boolean] if true, don't change the timestamp


def terminal_size
    rows, cols = 25, 80
    buf = [0, 0, 0, 0].pack("SSSS")
    if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then
      rows, cols, row_pixels, col_pixels = buf.unpack("SSSS")
    end
    return [rows, cols]
  end

def terminal_size rows , cols = 25 , 80 buf = [ 0 , 0 , 0 , 0 ] . pack ( "SSSS" ) if $stdout . ioctl ( TIOCGWINSZ , buf ) >= 0 then rows , cols , row_pixels , col_pixels = buf . unpack ( "SSSS" ) end return [ rows , cols ] end


def prepare_modes
    buf = [0, 0, 0, 0, 0, 0, ''].pack("IIIICCA*")
    $stdout.ioctl(TCGETS, buf)
    @old_modes = buf.unpack("IIIICCA*")
    new_modes = @old_modes.clone
    new_modes[3] &= ~ECHO # echo off
    new_modes[3] &= ~ICANON # one char @ a time
    $stdout.ioctl(TCSETS, new_modes.pack("IIIICCA*"))
    print "\e[2J" # clear screen
    print "\e[H" # go home
    print "\e[?47h" # kick xterm into the alt screen
    print "\e[?1000h" # kindly ask for mouse positions to make up for it
    self.cursor = false
    flush
  end


def extract_subjects(subject)
      return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance

      return subject[:any] if subject.is_a? Hash and subject.key? :any

      [subject]
    end

def extract_subjects ( subject ) return extract_subjects ( subject . to_permission_instance ) if subject . respond_to? :to_permission_instance return subject [ :any ] if subject . is_a? Hash and subject . key? :any [ subject ] end

Override functionality from CanCan to allow objects to masquerade as other objects


def daemon # rubocop: disable AbcSize, MethodLength
      # => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)
      ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ']

      scheduler = Rufus::Scheduler.new
      Notifier.msg('Daemonizing Process')

      # => Alerts Management
      alerts_interval = Config.alert_management_interval
      scheduler.every alerts_interval, overlap: false do
        Manager.manage_alerts
      end

      # => Cleanup Stale Servers
      if Config.cleanup
        cleanup_interval = Config.cleanup_interval
        cleanup_age = Config.cleanup_age

        scheduler.every cleanup_interval, overlap: false do
          Manager.remove_nonreporting_servers(cleanup_age)
        end
      end

      # => Join the Current Thread to the Scheduler Thread
      scheduler.join
    end

=> Daemonization for Periodic Management

= > Daemonization for Periodic Management


def run
      daemon if Config.daemonize

      # => Manage Alerts
      Manager.manage_alerts

      # => Manage
      Manager.remove_nonreporting_servers(Config.cleanup_age) if Config.cleanup
    end

def
run
daemon
if
Config
.
daemonize
# => Manage Alerts
Manager
.
manage_alerts
# => Manage
Manager
.
remove_nonreporting_servers
(
Config
.
cleanup_age
)
if
Config
.
cleanup
end


def ensure_jekyll_dir
      @orig_dir = Dir.pwd
      start_path = Pathname.new(@orig_dir)

      ok = File.exists?('./_posts')
      new_path = nil

      # if it doesn't exist, check for a custom source dir in _config.yml
      if !ok
        check_custom_src_dir!
        ok = File.exists?('./_posts')
        new_path = Pathname.new(Dir.pwd)
      end

      if ok
        return (new_path ? new_path.relative_path_from(start_path) : '.')
      else
        puts 'ERROR: Cannot locate _posts directory. Double check to make sure'
        puts '       that you are in a jekyll directory.'
        exit
      end
    end

'       that you are in a jekyll directory.'

Check for a _posts directory in current directory. If there's not one,
 check for a _config.yml and look for a custom src directory.  If we
 don't find one, puke an error message and die. If we do, return the name
 of the directory

Check for a _posts directory in current directory . If there s not one check for a _config . yml and look for a custom src directory . If we don t find one puke an error message and die . If we do return the name of the directory


def get_layout(layout_path)

      if layout_path.nil?
        contents  = "---\n"
        contents << "title:\n"
        contents << "layout: post\n"
        contents << "date:\n"
        contents << "---\n"
        ext = nil
      else
        begin
          contents = File.open(layout_path, "r").read()
          ext = layout_path.match(/\.(.*?)$/)[1]
        rescue Errno::ENOENT
          bad_path(layout_path)
        end
      end

      return contents, ext
    end

def
get_layout
(
layout_path
)
if
layout_path
.
nil?
contents
=
"---\n"
contents
<<
"title:\n"
contents
<<
"layout: post\n"
contents
<<
"date:\n"
contents
<<
"---\n"
ext
=
else
begin
contents
=
File
.
open
(
layout_path
,
"r"
)
.
read
(
)
ext
=
layout_path
.
match
(
/
\.
/
)
[
1
]
rescue
Errno
::
ENOENT
bad_path
(
layout_path
)
end
end
return
contents
,
ext
end

Get a layout as a string. If layout_path is non-nil,  will open that
 file and read it, otherwise will return a default one, and a file
 extension to use

Get a layout as a string . If layout_path is non - nil will open that file and read it otherwise will return a default one and a file extension to use


def gen_usage
      puts 'Usage:'
      puts '  poole [ACTION] [ARG]'
      puts ''
      puts 'Actions:'
      puts '  draft      Create a new draft in _drafts with title SLUG'
      puts '  post       Create a new timestamped post in _posts with title SLUG'
      puts '  publish    Publish the draft with SLUG, timestamping appropriately'
      puts '  unpublish  Move a post to _drafts, untimestamping appropriately'
      exit
    end


def msg(message, subtitle = message, title = 'NewRelic Management')
      # => Stdout Messages
      terminal_notification(message, subtitle)

      return if Config.silent

      # => Pretty GUI Messages
      osx_notification(message, subtitle, title) if OS.x?
    end

def
msg
(
message
,
subtitle
=
message
,
title
=
'NewRelic Management'
)
# => Stdout Messages
terminal_notification
(
message
,
subtitle
)
return
if
Config
.
silent
# => Pretty GUI Messages
osx_notification
(
message
,
subtitle
,
title
)
if
OS
.
x?
end

=> Primary Notification Message Controller

= > Primary Notification Message Controller


def osx_notification(message, subtitle, title)
      TerminalNotifier.notify(message, title: title, subtitle: subtitle)
    end

def osx_notification ( message , subtitle , title ) TerminalNotifier . notify ( message , title : title , subtitle : subtitle ) end


def analyze(string, options = {})
      x = []
      @fst._analyze(string) do |a|
        if options[:symbol_sequence]
          x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym : s }
        else
          x << a.join
        end
      end
      x
    end

def analyze ( string , options = { } ) x = [ ] @fst . _analyze ( string ) do | a | if options [ :symbol_sequence ] x << a . map { | s | s . match ( / / ) ? $1 . to_sym : s } else x << a . join end end x end

Analyses a string +string+. Returns an array of analysed
 strings if the string is accepted, or an empty array if not.

 ==== Options
 * +symbol_sequence+ - Return each analysis as a sequence of symbols.
   Multicharacter symbols will be strings on the form +<symbol>+.

Analyses a string + string + . Returns an array of analysed strings if the string is accepted or an empty array if not .


def generate(string)
      x = []
      @fst._generate(string) { |a| x << a.join }
      x
    end

def generate ( string ) x = [ ] @fst . _generate ( string ) { | a | x << a . join } x end

Generates a string +string+. Returns an array of generated
 strings if the string is accepted or an empty array if not.

Generates a string + string + . Returns an array of generated strings if the string is accepted or an empty array if not .


def configure(argv = ARGV)
      # => Parse CLI Configuration
      cli = Options.new
      cli.parse_options(argv)

      # => Parse JSON Config File (If Specified and Exists)
      json_config = Util.parse_json(cli.config[:config_file] || Config.config_file)

      # => Merge Configuration (CLI Wins)
      config = [json_config, cli.config].compact.reduce(:merge)

      # => Apply Configuration
      config.each { |k, v| Config.send("#{k}=", v) }
    end


def missing_specs_from_file(path)
      Spectro::Spec::Parser.parse(path).select do |spec|
        index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name]
        index_spec.nil? || index_spec['spec_md5'] != spec.md5
      end
    end

def missing_specs_from_file ( path ) Spectro :: Spec :: Parser . parse ( path ) . select do | spec | index_spec = Spectro :: Database . index [ path ] && Spectro :: Database . index [ path ] [ spec . signature . name ] index_spec . nil? || index_spec [ 'spec_md5' ] != spec . md5 end end

Parse the specs on the given file path and return those
 that have not been fulfilled or need to be updated.

 @param [String] path target file path
 @return [<Spectro::Spec>] collection of specs not fulfilled or out of date

Parse the specs on the given file path and return those that have not been fulfilled or need to be updated .


def remove_nonreporting_servers(keeptime = nil)
      list_nonreporting_servers.each do |server|
        next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)
        Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server')
        Client.delete_server(server[:id])
      end
    end

def
remove_nonreporting_servers
(
keeptime
=
)
list_nonreporting_servers
.
each
do
|
server
|
next
if
keeptime
&&
Time
.
parse
(
server
[
:last_reported_at
]
)
>=
Time
.
now
ChronicDuration
.
parse
(
keeptime
)
Notifier
.
msg
(
server
[
:name
]
,
'Removing Stale, Non-Reporting Server'
)
Client
.
delete_server
(
server
[
:id
]
)
end
end


def find_excluded(excluded)
      result = []
      Array(excluded).each do |exclude|
        if exclude.include?(':')
          find_labeled(exclude).each { |x| result << x }
          next
        end
        res = Client.get_server(exclude)
        result << res['id'] if res
      end
      result
    end

def find_excluded ( excluded ) result = [ ] Array ( excluded ) . each do | exclude | if exclude . include? ( ':' ) find_labeled ( exclude ) . each { | x | result << x } next end res = Client . get_server ( exclude ) result << res [ 'id' ] if res end result end

=> Find Servers which should be excluded from Management

= > Find Servers which should be excluded from Management


def send_sms_confirmation!
      return false if _TC_sms_blocked
      return true  if sms_confirmed?
      return false if _TC_phone_number.blank?

      format_phone_number
      confirmation_code = TwilioContactable.confirmation_code(self, :sms)

      # Use this class' confirmation_message method if it
      # exists, otherwise use the generic message
      message = (self.class.respond_to?(:confirmation_message) ?
                   self.class :
                   TwilioContactable).confirmation_message(confirmation_code)

      if message.to_s.size > 160
        raise ArgumentError, "SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text."
      end

      response = TwilioContactable::Gateway.deliver_sms(message, _TC_formatted_phone_number)

      if response.success?
        update_twilio_contactable_sms_confirmation confirmation_code
      end

      response
    end

Sends an SMS validation request through the gateway


def send_voice_confirmation!
      return false if _TC_voice_blocked
      return true  if voice_confirmed?
      return false if _TC_phone_number.blank?

      format_phone_number
      confirmation_code = TwilioContactable.confirmation_code(self, :voice)

      response = TwilioContactable::Gateway.initiate_voice_call(self, _TC_formatted_phone_number)

      if response.success?
        update_twilio_contactable_voice_confirmation confirmation_code
      end

      response
    end

Begins a phone call to the user where they'll need to type
 their confirmation code

Begins a phone call to the user where they ll need to type their confirmation code


def validate(value, format, raise_error=false)
      unless FORMATS.key?(format)
        raise FormatError, "Invalid data format: #{format}"
      end
      result = value =~ FORMATS[format] ? true : false
      if raise_error && !result
        raise ValidationError, "Invalid value \"#{value}\" for #{format}"
      end
      result
    end


def call(url, settings, &block)
      uri = URI.parse(url)
      klass = adapter_class(uri.scheme)
      session = klass.new(uri, settings.deep_dup)
      session.start(&block)
    end

def call ( url , settings , & block ) uri = URI . parse ( url ) klass = adapter_class ( uri . scheme ) session = klass . new ( uri , settings . deep_dup ) session . start ( block ) end

Initiates a new session
 @see XFTP::Validator::Settings


def all_fields(table, field_name, value)
      body = savon.
             call(:get_all_fields_records_given_a_field_name_and_value,
                  message: {
                    'strFeatureClassOrTableName' => table,
                    'strFieldNameToSearchOn' => field_name,
                    'strValueOfFieldToSearchOn' => value
                  }).
             body

      resp = body[:get_all_fields_records_given_a_field_name_and_value_response]
      rslt = resp[:get_all_fields_records_given_a_field_name_and_value_result]
      polys = rslt[:diffgram][:document_element][:municipality_poly]

      poly = if polys.is_a? Array
               polys.first
             elsif polys.is_a? Hash
               polys
             else
               fail "Unexpected polys #{polys.class.name}, wanted Array or Hash"
             end
    end

Performs a search for geo-attributes.

 @param [String] table the table to search
 @param [String] field_name the field/column to search in the given table
 @param [String] value string value to search in the given field and table
 @return [Hash] search results

Performs a search for geo - attributes .


def WHEN(condition, adjuster)
      unless Validation.conditionable? condition
        raise TypeError, 'wrong object for condition'
      end

      unless Validation.adjustable? adjuster
        raise TypeError, 'wrong object for adjuster'
      end

      ->v{_valid?(condition, v) ? adjuster.call(v) : v}
    end

def
WHEN
(
condition
,
adjuster
)
unless
Validation
.
conditionable?
condition
raise
TypeError
,
'wrong object for condition'
end
unless
Validation
.
adjustable?
adjuster
raise
TypeError
,
'wrong object for adjuster'
end
->
v
{
_valid?
(
condition
,
v
)
adjuster
.
call
(
v
)
:
v
}
end

Adjuster Builders
 Apply adjuster when passed condition.
 @param condition [Proc, Method, #===]
 @param adjuster [Proc, #to_proc]
 @return [lambda]

Adjuster Builders Apply adjuster when passed condition .


def INJECT(adjuster1, adjuster2, *adjusters)
      adjusters = [adjuster1, adjuster2, *adjusters]

      unless adjusters.all?{|f|adjustable? f}
        raise TypeError, 'wrong object for adjuster'
      end

      ->v{
        adjusters.reduce(v){|ret, adjuster|adjuster.call ret}
      }
    end

def
INJECT
(
adjuster1
,
adjuster2
,
*
adjusters
)
adjusters
=
[
adjuster1
,
adjuster2
,
adjusters
]
unless
adjusters
.
all?
{
|
f
|
adjustable?
f
}
raise
TypeError
,
'wrong object for adjuster'
end
->
v
{
adjusters
.
reduce
(
v
)
{
|
ret
,
adjuster
|
adjuster
.
call
ret
}
}
end

Sequencial apply all adjusters.
 @param adjuster1 [Proc, #to_proc]
 @param adjuster2 [Proc, #to_proc]
 @param adjusters [Proc, #to_proc]
 @return [lambda]


def PARSE(parser)
      if !::Integer.equal?(parser) and !parser.respond_to?(:parse)
        raise TypeError, 'wrong object for parser'
      end

      ->v{
        if ::Integer.equal? parser
          ::Kernel.Integer v
        else
          parser.parse(
            case v
            when String
              v
            when ->_{v.respond_to? :to_str}
              v.to_str
            when ->_{v.respond_to? :read}
              v.read
            else
              raise TypeError, 'wrong object for parsing source'
            end
          )
        end
      }
    end

def
PARSE
(
parser
)
if
!
::
Integer
.
equal?
(
parser
)
and
!
parser
.
respond_to?
(
:parse
)
raise
TypeError
,
'wrong object for parser'
end
->
v
{
if
::
Integer
.
equal?
parser
::
Kernel
.
Integer
v
else
parser
.
parse
(
case
v
when
String
v
when
->
_
{
v
.
respond_to?
:to_str
}
v
.
to_str
when
->
_
{
v
.
respond_to?
:read
}
v
.
read
else
raise
TypeError
,
'wrong object for parsing source'
end
)
end
}
end

Accept any parser when that resopond to parse method.
 @param parser [#parse]
 @return [lambda]

Accept any parser when that resopond to parse method .


def get_class(name)
      @class_list = get_class_list
      @class_list.select {|x| x.include?(name)}.collect{|y| y.strip}
    end

def get_class ( name ) @class_list = get_class_list @class_list . select { | x | x . include? ( name ) } . collect { | y | y . strip } end


def connection
      @options[:path] =API_REST + @options[:path]
      @options[:headers] = HEADERS.merge({
        'X-Megam-Date' =>  Time.now.strftime("%Y-%m-%d %H:%M")
      }).merge(@options[:headers])

      text.info("HTTP Request Data:")
      text.msg("> HTTP #{@options[:scheme]}://#{@options[:host]}")
      @options.each do |key, value|
        text.msg("> #{key}: #{value}")
      end
      text.info("End HTTP Request Data.")
      http = Net::HTTP.new(@options[:host], @options[:port])
      http
    end


def wake_deadline(start_time, timeout)
      timeout = process_timeout(timeout)
      deadline = start_time + timeout if timeout
    end

def wake_deadline ( start_time , timeout ) timeout = process_timeout ( timeout ) deadline = start_time + timeout if timeout end

Calculate the desired time to wake up.
 @api private
 @param start_time [nil,Time] time when the thread is put to sleep
 @param timeout [Numeric] desired time to sleep in seconds, +nil+ for forever
 @raise [TypeError] if +start_time+ is not +nil+ or a +Numeric+
 @raise [ArgumentError] if +start_time+ is negative
 @return [Time]


def crud_links(model, instance_name, actions, args={})
      _html = ""
      _options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"

      if use_crud_icons
        if actions.include?(:show)
          _html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}")
        end
        if actions.include?(:edit)
          _html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}")
        end
        if actions.include?(:delete)
          _html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}")
        end
      else
        if actions.include?(:show)
          _html << eval("link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}")
        end
        if actions.include?(:edit)
          _html << eval("link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}")
        end
        if actions.include?(:delete)
          _html << eval("link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}")
        end
      end
      _html
    end

Display CRUD icons or links, according to setting in use_crud_icons method.

 In application_helper.rb:

   def use_crud_icons
     true
   end

 Then use in index views like this:

 <%= crud_links(my_model, 'my_model', [:show, :edit, :delete]) -%>

Display CRUD icons or links according to setting in use_crud_icons method .


def obfuscated_link_to(path, image, label, args={})
      _html = %{<form action="#{path}" method="get" class="obfuscated_link">}
      _html << %{ <fieldset><input alt="#{label}" src="#{image}" type="image" /></fieldset>}
      args.each{ |k,v| _html << %{
<input id="#{k.to_s}" name="#{k}" type="hidden" value="#{v}" />
} }
      _html << %{</form>}
      _html
    end

Create a link that is opaque to search engine spiders.

Create a link that is opaque to search engine spiders .


def required_field_helper( model, element, html )
      if model && ! model.errors.empty? && element.is_required
        return content_tag( :div, html, :class => 'fieldWithErrors' )
      else
        return html
      end
    end

def required_field_helper ( model , element , html ) if model && ! model . errors . empty? && element . is_required return content_tag ( :div , html , :class => 'fieldWithErrors' ) else return html end end

Wraps the given HTML in Rails' default style to highlight validation errors, if any.

Wraps the given HTML in Rails default style to highlight validation errors if any .


def select_tag_for_filter(model, nvpairs, params)
      return unless model && nvpairs && ! nvpairs.empty?
      options = { :query => params[:query] }
      _url = url_for(eval("#{model}_url(options)"))
      _html = %{Show:
}
      _html << %{<select name="show" id="show" onchange="window.location='#{_url}' + '?show=' + this.value">}
      nvpairs.each do |pair|
        _html << %{<option value="#{pair[:scope]}"}
        if params[:show] == pair[:scope] || ((params[:show].nil? || params[:show].empty?) && pair[:scope] == "all")
          _html << %{ selected="selected"}
        end
        _html << %{>#{pair[:label]}}
        _html << %{</option>}
      end
      _html << %{</select>}
    end

Use on index pages to create dropdown list of filtering criteria.
 Populate the filter list using a constant in the model corresponding to named scopes.

 Usage:

 - item.rb:

     scope :active,   :conditions => { :is_active => true }
     scope :inactive, :conditions => { :is_active => false }

     FILTERS = [
       {:scope => "all",       :label => "All"},
       {:scope => "active",    :label => "Active Only"},
       {:scope => "inactive",  :label => "Inactive Only"}
     ]

 - items/index.html.erb:

     <%= select_tag_for_filter("items", @filters, params) -%>

 - items_controller.rb:

     def index
       @filters = Item::FILTERS
       if params[:show] && params[:show] != "all" && @filters.collect{|f| f[:scope]}.include?(params[:show])
         @items = eval("@items.#{params[:show]}.order_by(params[:by], params[:dir])")
       else
         @items = @items.order_by(params[:by], params[:dir])
       end
       ...
     end

Use on index pages to create dropdown list of filtering criteria . Populate the filter list using a constant in the model corresponding to named scopes .


def sort_link(model, field, params, html_options={})
      if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC"
        classname = "arrow-asc"
        dir = "DESC"
      elsif (field.to_sym == params[:by] || field == params[:by])
        classname = "arrow-desc"
        dir = "ASC"
      else
        dir = "ASC"
      end

      options = {
        :anchor => html_options[:anchor] || nil,
        :by => field,
        :dir => dir,
        :query => params[:query],
        :show => params[:show]
      }

      options[:show] = params[:show] unless params[:show].blank? || params[:show] == 'all'

      html_options = {
        :class => "#{classname} #{html_options[:class]}",
        :style => "color: white; font-weight: #{params[:by] == field ? "bold" : "normal"}; #{html_options[:style]}",
        :title => "Sort by this field"
      }

      field_name = params[:labels] && params[:labels][field] ? params[:labels][field] : field.titleize

      _link = model.is_a?(Symbol) ? eval("#{model}_url(options)") : "/#{model}?#{options.to_params}"
      link_to(field_name, _link, html_options)
    end

Returns a link_to tag with sorting parameters that can be used with ActiveRecord.order_by.

 To use standard resources, specify the resources as a plural symbol:
   sort_link(:users, 'email', params)

 To use resources aliased with :as (in routes.rb), specify the aliased route as a string.
   sort_link('users_admin', 'email', params)

 You can override the link's label by adding a labels hash to your params in the controller:
   params[:labels] = {'user_id' => 'User'}

Returns a link_to tag with sorting parameters that can be used with ActiveRecord . order_by .


def tag_for_label_with_inline_help( label_text, field_id, help_text )
      _html = ""
      _html << %{#{label_text}}
      _html << %{}
      _html << %{
}
      _html << %{
}
      _html << %{
#{help_text}
}
      _html << %{
}
      _html
    end

%{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />}

%{<div class="inline_help" id="#{field_id}_help" style="display: none;">}

Create a set of tags for displaying a field label with inline help.
 Field label text is appended with a ? icon, which responds to a click
 by showing or hiding the provided help text.

 Sample usage:

   <%= tag_for_label_with_inline_help 'Relative Frequency', 'rel_frequency', 'Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.' %>

 Yields:

   Relative Frequency: <%= image_tag "/images/help_icon.png", :onclick => "$('rel_frequency_help').toggle();", :class => 'inline_icon' %>

Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.

Create a set of tags for displaying a field label with inline help . Field label text is appended with a ? icon which responds to a click by showing or hiding the provided help text .


def key_press(keys)
      dump_caller_stack

      if keys =~ /^Ctrl\+([A-Z])$/
        filtered_keys = "^+#{$1}"
      elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/
        filtered_keys = "^+#{$1.downcase}"
      elsif keys =~ /^Alt+([A-Z])$/
        filtered_keys = "!+#{$1}"
      elsif keys =~ /^Alt\+Shift\+([a-z])$/
        filtered_keys = "!+#{$1.downcase}"
      else
        filtered_keys = keys
      end
      filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+")
      RFormSpec::Keyboard.press(filtered_keys)
      sleep 0.5
    end

def key_press ( keys ) dump_caller_stack if keys =~ / \+ / filtered_keys = "^+#{$1}" elsif keys =~ / \+ \+ / filtered_keys = "^+#{$1.downcase}" elsif keys =~ / / filtered_keys = "!+#{$1}" elsif keys =~ / \+ \+ / filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys . gsub ( "Alt+" , "!+" ) . gsub ( "Ctrl+" , "^+" ) RFormSpec :: Keyboard . press ( filtered_keys ) sleep 0.5 end


def open_file_dialog(title, filepath, text="")
      wait_and_focus_window(title)
      dialog = RFormSpec::OpenFileDialog.new(title, text)
      dialog.enter_filepath(filepath)
      sleep 1
      dialog.click_open
    end

def open_file_dialog ( title , filepath , text = "" ) wait_and_focus_window ( title ) dialog = RFormSpec :: OpenFileDialog . new ( title , text ) dialog . enter_filepath ( filepath ) sleep 1 dialog . click_open end


def parse(args)
      # The options specified on the command line will be collected in
      # *options*.
      @options = Options.new
      opt_parser = OptionParser.new do |parser|
        @options.define_options(parser)
      end
      opt_parser.parse!(args)

      @options
    end

Return a structure describing the options.

Return a structure describing the options .


def add(path)
      str = "#{path} filter=rgc diff=rgc"
      if content.include?(str)
        abort "`#{str}\n` is already included in #{@location}."
      end

      File.open(@location, 'a') do |f|
        f.write("#{str}\n")
      end
    rescue Errno::ENOENT
      abort "File #{@location} does not exists."
    rescue Errno::EACCES
      abort "File #{@location} is not accessible for writing."
    end


def run
      logger.info("#{self.class.to_s} is starting.")
      count_options = self.class.legacy_find_options.dup
      count_options.delete(:order)
      count_options.delete(:group)
      count_options.delete(:limit)
      count_options.delete(:offset)
      @num_of_records = self.class.legacy_model.count(count_options)
      if self.class.legacy_find_options[:limit] && (@num_of_records > self.class.legacy_find_options[:limit])
        run_in_batches @num_of_records
      else
        run_normal
      end
      logger.info("#{self.class.to_s} migrated all #{@num_of_records} records successfully.")
    end

Runs the migration.

   MyMigration.new.run


def parents
      page, parents = self, Array.new
      while page.parent
        page = page.parent
        parents << page
      end
      parents
    end

def parents page , parents = self , Array . new while page . parent page = page . parent parents << page end parents end

List parents, closest to furthest.

 This is a recursive, expensive call.


def extract_search_text(*attributes)
      Array(attributes).map { |meth|
        Nokogiri::HTML(self.send(meth)).xpath("//text()").
          map {|node| text = node.text; text.try(:strip!); text}.join(" ")
      }.reject(&:blank?).join("\n")
    end

def
extract_search_text
(
*
attributes
)
Array
(
attributes
)
.
map
{
|
meth
|
Nokogiri
::
HTML
(
self
.
send
(
meth
)
)
.
xpath
(
"//text()"
)
.
map
{
|
node
|
text
=
node
.
text
;
text
.
try
(
:strip!
)
;
text
}
.
join
(
" "
)
}
.
reject
(
:blank?
)
.
join
(
"\n"
)
end

Extract text out of HTML or plain strings. Basically removes html
 formatting.

 @param attributes [Symbol, String]
   variable list of attributes or methods to be extracted for search

 @return [String] content of each attribute separated by new lines

Extract text out of HTML or plain strings . Basically removes html formatting .


def set_query_attributes!
      attr_names = self.class.search_query_attributes.map(&:to_s)
      self.query = attr_names.inject({}) { |memo, attr|
        memo[attr] = self.send(attr)
        memo
      }
    end

def set_query_attributes! attr_names = self . class . search_query_attributes . map ( :to_s ) self . query = attr_names . inject ( { } ) { | memo , attr | memo [ attr ] = self . send ( attr ) memo } end

Build query attribute hash.

 Internally stored as JSONB.

 @return [Hash] to be set for query attribute


def manager_ws_uri
    # convert manager uri to websocket
    uri = URI.parse(manager_uri)
    uri.scheme = (uri.scheme == "https" ? "wss" : "ws")
    uri.path = "/wsapi"
    return uri.to_s
  end

def
manager_ws_uri
# convert manager uri to websocket
uri
=
URI
.
parse
(
manager_uri
)
uri
.
scheme
=
(
uri
.
scheme
==
"https"
"wss"
:
"ws"
)
uri
.
path
=
"/wsapi"
return
uri
.
to_s
end

Get the WebSocket API URI

 @return [String] uri


def parse_config(conffile = nil)
      conffile ||= Dir.glob([
	  "/etc/foreman_hooks-host_rename/settings.yaml",
	  "#{confdir}/settings.yaml"])[0]
      raise "Could not locate the configuration file" if conffile.nil?

      # Parse the configuration file
      config = {
          hook_user: 'foreman',
          database_path: '/var/tmp/foreman_hooks-host_rename.db',
          log_path: '/var/tmp/foreman_hooks-host_rename.log',
          log_level: 'warn',
          rename_hook_command: '/bin/true',
      }.merge(symbolize(YAML.load(File.read(conffile))))
      config.each do |k,v|
        instance_variable_set("@#{k}",v)
      end

      # Validate the schema
      document = Kwalify::Yaml.load_file(conffile)
      schema = Kwalify::Yaml.load_file("#{confdir}/schema.yaml")
      validator = Kwalify::Validator.new(schema)
      errors = validator.validate(document)
      if errors && !errors.empty?
        puts "WARNING: The following errors were found in #{conffile}:"
        for e in errors
          puts "[#{e.path}] #{e.message}"
        end
        raise "Errors in the configuration file"
      end

      check_script @rename_hook_command
    end


def check_script(path)
      binary=path.split(' ')[0]
      raise "#{path} does not exist" unless File.exist? binary
      raise "#{path} is not executable" unless File.executable? binary
      path
    end

def
check_script
(
path
)
binary
=
path
.
split
(
' '
)
[
0
]
raise
"#{path} does not exist"
unless
File
.
exist?
binary
raise
"#{path} is not executable"
unless
File
.
executable?
binary
path
end

Do additional sanity checking on a hook script


def sync_host_table
      uri = foreman_uri('/hosts?per_page=9999999')
      debug "Loading hosts from #{uri}"
      json = RestClient.get uri
      debug "Got JSON: #{json}"
      JSON.parse(json)['results'].each do |rec|
        @db.execute "insert into host (id,name) values ( ?, ? )",
                   rec['id'], rec['name']
      end
    end

Get all the host IDs and FQDNs and populate the host table


def initialize_database
      @db = SQLite3::Database.new @database_path
      File.chmod 0600, @database_path
      begin
        @db.execute 'drop table if exists host;'
        @db.execute <<-SQL
            create table host (
              id INT,
              name varchar(254)
            );
        SQL
        sync_host_table
      rescue
        File.unlink @database_path
        raise
      end
    end

def
initialize_database
@db
=
SQLite3
::
Database
.
new
@database_path
File
.
chmod
0600
,
@database_path
begin
@db
.
execute
'drop table if exists host;'
@db
.
execute
<<-SQL
SQL
sync_host_table
rescue
File
.
unlink
@database_path
raise
end
end


def execute_hook_action
      @rename = false
      name = @rec['host']['name']
      id = @rec['host']['id']

      case @action
      when 'create'
        sql = "insert into host (id, name) values (?, ?)"
        params = [id, name]
      when 'update'
        # Check if we are renaming the host
        @old_name = @db.get_first_row('select name from host where id = ?', id)
        @old_name = @old_name[0] unless @old_name.nil?
        if @old_name.nil?
          warn 'received an update for a non-existent host'
        else
          @rename = @old_name != name
        end
        debug "checking for a rename: old=#{@old_name} new=#{name} rename?=#{@rename}"

        sql = 'update host set name = ? where id = ?'
        params = [name, id]
      when 'destroy'
        sql = 'delete from host where id = ?'
        params = [id]
      else
        raise ArgumentError, "unsupported action: #{ARGV[0]}"
      end
      debug "updating database; id=#{id} name=#{name} sql=#{sql}"
      stm = @db.prepare sql
      stm.bind_params *params
      stm.execute
    end

Update the database based on the foreman_hook


def read_list(name)
      opts = self.class.persisted_attrs[name]

      if !lists[name] && opts[:default]
        opts[:default]
      else
        send("#{name}=", lists[name].value) if lists[name].is_a?(Redis::Future)
        lists[name]
      end
    end

def read_list ( name ) opts = self . class . persisted_attrs [ name ] if ! lists [ name ] && opts [ :default ] opts [ :default ] else send ( "#{name}=" , lists [ name ] . value ) if lists [ name ] . is_a? ( Redis :: Future ) lists [ name ] end end


def read_hash(name)
      opts = self.class.persisted_attrs[name]

      if !hashes[name] && opts[:default]
        opts[:default]
      else
        self.send("#{name}=", hashes[name].value) if hashes[name].is_a?(Redis::Future)
        hashes[name]
      end
    end

def read_hash ( name ) opts = self . class . persisted_attrs [ name ] if ! hashes [ name ] && opts [ :default ] opts [ :default ] else self . send ( "#{name}=" , hashes [ name ] . value ) if hashes [ name ] . is_a? ( Redis :: Future ) hashes [ name ] end end


def write_attribute(name, val)
      if attributes.is_a?(Redis::Future)
        value = attributes.value
        self.attributes = value ? Hash[*self.class.fields.keys.zip(value).flatten] : {}
      end

      attributes[name] = self.class.transform(:to, name, val)
    end

def write_attribute ( name , val ) if attributes . is_a? ( Redis :: Future ) value = attributes . value self . attributes = value ? Hash [ self . class . fields . keys . zip ( value ) . flatten ] : { } end attributes [ name ] = self . class . transform ( :to , name , val ) end

Transform and write a standard attribute value


def write_list(name, val)
      raise "RedisAssist: tried to store a #{val.class.name} as Array" unless val.is_a?(Array)
      lists[name] = val
    end


def write_hash(name, val)
      raise "RedisAssist: tried to store a #{val.class.name} as Hash" unless val.is_a?(Hash)
      hashes[name] = val
    end


def update_columns(attrs)
      redis.multi do
        attrs.each do |attr, value|
          if self.class.fields.has_key?(attr)
            write_attribute(attr, value)
            redis.hset(key_for(:attributes), attr, self.class.transform(:to, attr, value)) unless new_record?
          end

          if self.class.lists.has_key?(attr)
            write_list(attr, value)

            unless new_record?
              redis.del(key_for(attr))
              redis.rpush(key_for(attr), value) unless value.empty?
            end
          end

          if self.class.hashes.has_key?(attr)
            write_hash(attr, value)

            unless new_record?
              hash_as_args = hash_to_redis(value)
              redis.hmset(key_for(attr), *hash_as_args)
            end
          end
        end
      end
    end

def update_columns ( attrs ) redis . multi do attrs . each do | attr , value | if self . class . fields . has_key? ( attr ) write_attribute ( attr , value ) redis . hset ( key_for ( :attributes ) , attr , self . class . transform ( :to , attr , value ) ) unless new_record? end if self . class . lists . has_key? ( attr ) write_list ( attr , value ) unless new_record? redis . del ( key_for ( attr ) ) redis . rpush ( key_for ( attr ) , value ) unless value . empty? end end if self . class . hashes . has_key? ( attr ) write_hash ( attr , value ) unless new_record? hash_as_args = hash_to_redis ( value ) redis . hmset ( key_for ( attr ) , hash_as_args ) end end end end end

Update fields without hitting the callbacks


def filter_authorized!(method, objects, user = current_user)
      object_array = Array(objects)

      object_array.select do |object|
        policy = policy_for(object)
        policy.can?(method, user)
      end
    end

def filter_authorized! ( method , objects , user = current_user ) object_array = Array ( objects ) object_array . select do | object | policy = policy_for ( object ) policy . can? ( method , user ) end end

Controller helper method to filter out non-authorized
 objects from the passed in array

 @param method [Symbol] method to be called on each policy
 @param objects [Array] array of objects to filter
 @param user [User] The current user object to pass
 @return (Array)

 @visibility public

Controller helper method to filter out non - authorized objects from the passed in array


def can?(method, object, user = current_user)
      policy = policy_for(object)
      policy.can?(method, user)
    end

def can? ( method , object , user = current_user ) policy = policy_for ( object ) policy . can? ( method , user ) end

Helper method available in controllers and views
 that returns the value of the policy method

 @param (see #authorize!)
 @return (Boolean)

 @visibility public


def nethash interval = 500, start = 0, stop = false
      suffixe = stop ? "/#{stop}" : ''
      JSON.parse(call_blockchain_api("nethash/#{interval}/#{start}#{suffixe}?format=json"))
    end

shows statistics about difficulty and network power

 /nethash/INTERVAL/START/STOP
 Default INTERVAL=500, START=0, STOP=infinity.

 See http://dogechain.info/chain/Dogecoin/q/nethash


def last(limit=1, offset=0)
      from    = offset
      to      = from + limit - 1
      members = redis.zrange(index_key_for(:id), (to * -1) + -1, (from * -1) + -1).reverse

      find(limit > 1 ? members : members.first)
    end

def last ( limit = 1 , offset = 0 ) from = offset to = from + limit - 1 members = redis . zrange ( index_key_for ( :id ) , ( to * - 1 ) + - 1 , ( from * - 1 ) + - 1 ) . reverse find ( limit > 1 ? members : members . first ) end

Find the first saved record
 @note `last` uses a sorted set as an index of `ids` and finds the highest id.
 @param limit [Integer] returns one or many
 @param offset [Integer] from the end of the index, back
 @return [Base, Array]


def find(ids, opts={})
      ids.is_a?(Array) ? find_by_ids(ids, opts) : find_by_id(ids, opts)
    end

def find ( ids , opts = { } ) ids . is_a? ( Array ) ? find_by_ids ( ids , opts ) : find_by_id ( ids , opts ) end

Find a record by `id`
 @param ids [Integer, Array<Integer>] of the record(s) to lookup.
 @return [Base, Array] matching records


def find_in_batches(options={})
      start       = options[:start]      || 0
      marker      = start
      batch_size  = options[:batch_size] || 500
      record_ids  = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)

      while record_ids.length > 0
        records_count   = record_ids.length
        marker          += records_count
        records         = find(record_ids)

        yield records

        break if records_count < batch_size

        record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
      end
    end

def find_in_batches ( options = { } ) start = options [ :start ] || 0 marker = start batch_size = options [ :batch_size ] || 500 record_ids = redis . zrange ( index_key_for ( :id ) , marker , marker + batch_size - 1 ) while record_ids . length > 0 records_count = record_ids . length marker += records_count records = find ( record_ids ) yield records break if records_count < batch_size record_ids = redis . zrange ( index_key_for ( :id ) , marker , marker + batch_size - 1 ) end end

Iterate over all records in batches
 @param options [Hash] accepts options
   `:start` to offset from the beginning of index,
   `:batch_size` the size of the batch, default is 500.
 @param &block [Proc] passes each batch of articles to the Proc.


def load_keymap(map) #:nodoc:
      @maps ||= Hash.new
      if @maps[map].nil? && File.file?(File.join(self.storage_path, map.to_s + "_map.yml"))
        @maps[map] = YAML.load(File.open(File.join(self.storage_path, map.to_s + "_map.yml")))
        logger.debug("#{self.class.to_s} lazy loaded #{map} successfully.")
      end
    end


def mapped_key(map, key)
      load_keymap(map.to_s)
      @maps[map.to_s][handle_composite(key)]
    end

def mapped_key ( map , key ) load_keymap ( map . to_s ) @maps [ map . to_s ] [ handle_composite ( key ) ] end

Returns the deserialized mapped key when provided with the former key.

  mapped_key(:products, 2)

Returns the deserialized mapped key when provided with the former key .


def processor_count
      @processor_count ||= begin
        os_name = RbConfig::CONFIG["target_os"]
        if os_name =~ /mingw|mswin/
          require 'win32ole'
          result = WIN32OLE.connect("winmgmts://").ExecQuery(
            "select NumberOfLogicalProcessors from Win32_Processor")
          result.to_enum.collect(&:NumberOfLogicalProcessors).reduce(:+)
        elsif File.readable?("/proc/cpuinfo")
          IO.read("/proc/cpuinfo").scan(/^processor/).size
        elsif File.executable?("/usr/bin/hwprefs")
          IO.popen("/usr/bin/hwprefs thread_count").read.to_i
        elsif File.executable?("/usr/sbin/psrinfo")
          IO.popen("/usr/sbin/psrinfo").read.scan(/^.*on-*line/).size
        elsif File.executable?("/usr/sbin/ioscan")
          IO.popen("/usr/sbin/ioscan -kC processor") do |out|
            out.read.scan(/^.*processor/).size
          end
        elsif File.executable?("/usr/sbin/pmcycles")
          IO.popen("/usr/sbin/pmcycles -m").read.count("\n")
        elsif File.executable?("/usr/sbin/lsdev")
          IO.popen("/usr/sbin/lsdev -Cc processor -S 1").read.count("\n")
        elsif File.executable?("/usr/sbin/sysconf") and os_name =~ /irix/i
          IO.popen("/usr/sbin/sysconf NPROC_ONLN").read.to_i
        elsif File.executable?("/usr/sbin/sysctl")
          IO.popen("/usr/sbin/sysctl -n hw.ncpu").read.to_i
        elsif File.executable?("/sbin/sysctl")
          IO.popen("/sbin/sysctl -n hw.ncpu").read.to_i
        else
          $stderr.puts "Unknown platform: " + RbConfig::CONFIG["target_os"]
          $stderr.puts "Assuming 1 processor."
          1
        end
      end
    end

Number of processors seen by the OS and used for process scheduling.

 * AIX: /usr/sbin/pmcycles (AIX 5+), /usr/sbin/lsdev
 * BSD: /sbin/sysctl
 * Cygwin: /proc/cpuinfo
 * Darwin: /usr/bin/hwprefs, /usr/sbin/sysctl
 * HP-UX: /usr/sbin/ioscan
 * IRIX: /usr/sbin/sysconf
 * Linux: /proc/cpuinfo
 * Minix 3+: /proc/cpuinfo
 * Solaris: /usr/sbin/psrinfo
 * Tru64 UNIX: /usr/sbin/psrinfo
 * UnixWare: /usr/sbin/psrinfo

Number of processors seen by the OS and used for process scheduling .


def physical_processor_count
      @physical_processor_count ||= begin
        ppc = case RbConfig::CONFIG["target_os"]
        when /darwin1/
          IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i
        when /linux/
          cores = {}  # unique physical ID / core ID combinations
          phy = 0
          IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
            if ln.start_with?("physical")
              phy = ln[/\d+/]
            elsif ln.start_with?("core")
              cid = phy + ":" + ln[/\d+/]
              cores[cid] = true if not cores[cid]
            end
          end
          cores.count
        when /mswin|mingw/
          require 'win32ole'
          result_set = WIN32OLE.connect("winmgmts://").ExecQuery(
            "select NumberOfCores from Win32_Processor")
          result_set.to_enum.collect(&:NumberOfCores).reduce(:+)
        else
          processor_count
        end
        # fall back to logical count if physical info is invalid
        ppc > 0 ? ppc : processor_count
      end
    end

Number of physical processor cores on the current system.

Number of physical processor cores on the current system .


def valid?(options = {})
      options = {:input => {}}.merge(options)
      errors = []

      # initial sandbox
      sandbox = _source(options)

      # add in inputs
      sandbox[:inputs] = options[:input]

      validity = @filters.map do |filter_name, filter|

        # find input for given filter
        sandbox[:input] = options[:input][filter[:key]] if options[:input].is_a?(Hash)

        filter_validity = filter[:valid].nil? || sandbox.instance_eval(&filter[:valid])

        if filter_validity == false
          # Ignore an empty filter unless it's required
          if !sandbox[:input].to_s.blank?
            errors << "#{filter_name} is invalid."
            false
          else
            if sandbox[:input].to_s.blank? && !filter[:require].blank?
              errors << "#{filter_name} is required."
              false
            else
              true
            end
          end
        elsif filter_validity == true
          if sandbox[:input].to_s.blank? && !filter[:require].blank?
            errors << "#{filter_name} is required."
            false
          else
            true
          end
        elsif !filter_validity.nil? && !filter_validity[:status].nil? && filter_validity[:status] == false
          # Ignore an empty filter unless it's required or the error is forced.
          if !sandbox[:input].to_s.blank? || filter_validity[:force_error] == true
            errors << filter_validity[:errors]
            false
          else
            if sandbox[:input].to_s.blank? && !filter[:require].blank?
              errors << "#{filter_name} is required."
              false
            else
              true
            end
          end
        end
      end

      return {:status => !validity.include?(false), :errors => errors}

    end


def reload()
      self.clear
      self.concat File.read(event_file).split(/\r?\n/).map{|e| Event.new(e)}
    end

def reload ( ) self . clear self . concat File . read ( event_file ) . split ( / \r \n / ) . map { | e | Event . new ( e ) } end

Reload the events from the event file. Existing events are
 deleted first.

Reload the events from the event file . Existing events are deleted first .


def followee_of?(model)
      0 < self.followers.by_model(model).limit(1).count * model.followees.by_model(self).limit(1).count
    end

def followee_of? ( model ) 0 < self . followers . by_model ( model ) . limit ( 1 ) . count * model . followees . by_model ( self ) . limit ( 1 ) . count end

see if this model is followee of some model

 Example:
   >> @ruby.followee_of?(@jim)
   => true


def ever_followed
      follow = []
      self.followed_history.each do |h|
        follow << h.split('_')[0].constantize.find(h.split('_')[1])
      end
      follow
    end

def ever_followed follow = [ ] self . followed_history . each do | h | follow << h . split ( '_' ) [ 0 ] . constantize . find ( h . split ( '_' ) [ 1 ] ) end follow end

see model's followed history

 Example:
   >> @ruby.ever_followed
   => [@jim]


def wait(mutex, timeout = nil)
      validate_mutex(mutex)
      validate_timeout(timeout)
      waitable = waitable_for_current_thread
      @mutex.synchronize do
        @waitables.push(waitable)
        @waitables_to_resume.push(waitable)
      end
      waitable.wait(mutex, timeout)
      self
    end

def wait ( mutex , timeout = nil ) validate_mutex ( mutex ) validate_timeout ( timeout ) waitable = waitable_for_current_thread @mutex . synchronize do @waitables . push ( waitable ) @waitables_to_resume . push ( waitable ) end waitable . wait ( mutex , timeout ) self end

Puts this thread to sleep until another thread resumes it.
 Threads will be woken in the chronological order that this was called.
 @note Will block until resumed
 @param mutex [Mutex] mutex to be unlocked while this thread is sleeping
 @param timeout [nil,Numeric] maximum time to sleep in seconds, +nil+ for forever
 @raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
 @raise [ArgumentError] if +timeout+ is negative
 @raise [Exception] any exception raised by +::ConditionVariable#wait+ (eg. interrupts, +ThreadError+)
 @return [self]

Puts this thread to sleep until another thread resumes it . Threads will be woken in the chronological order that this was called .


def validate_timeout(timeout)
      unless timeout == nil
        raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
        raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
      end
    end

def
validate_timeout
(
timeout
)
unless
timeout
==
raise
TypeError
,
"'timeout' must be nil or a Numeric"
unless
timeout
.
is_a?
(
Numeric
)
raise
ArgumentError
,
"'timeout' must not be negative"
if
timeout
.
negative?
end
end

Validates a timeout value
 @api private
 @param timeout [nil,Numeric]
 @raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
 @raise [ArgumentError] if +timeout+ is negative
 @return [void]


def render(template_name, view_handler, locals, &content)
      self.erb_source.render(template_name, render_locals(view_handler, locals), &content)
    end

def render ( template_name , view_handler , locals , & content ) self . erb_source . render ( template_name , render_locals ( view_handler , locals ) , content ) end

render the template including the handler as a local


def run_entry
      entry = get_entry()
      output = '';
      @keys.keys.select { |k| @config['key_fields'][k] && @keys[k] }.each do |key|
        output += [ key, @keys[key] ].join(' ') + " "
      end

      unless entry
        $stderr.puts "#{ output } is not supported on #{ @page_name }" if @debug
        return
      end

      unless entry['ready'] == "1"
        $stderr.puts "#{ output } is not ready to run #{ @agent_name }" if @debug
        return false, entry
      end

      if entry['complete'] == "1"
        $stderr.puts "All goals are completed for #{ output }" if @debug
        return false, entry
      end

      if entry[@agent_name]
        (status, running_hostname) = entry[@agent_name].split(':')

        case status
        when 'r'
          $stderr.puts " #{ output } is already running #{ @agent_name } on #{ running_hostname }" if @debug
          return false, entry

        when "1"
          $stderr.puts " #{ output } has already run #{ @agent_name }" if @debug
          return false, entry

        when 'F'
          $stderr.puts " #{ output } has already Failed  #{ @agent_name }" if @debug
          return false, entry
        end
      end

      if @prerequisites
        @prerequisites.each do |prereq_field|
          unless entry[prereq_field] == "1"
            $stderr.puts " #{ output } has not finished #{ prereq_field }" if @debug
            return false, entry
          end
        end
      end

      # first attempt to set the hostname of the machine as the value of the agent
      hostname = Socket.gethostname;
      begin
        entry.update @agent_name => "r:#{ hostname }"
        @worksheet.save

      rescue GoogleDrive::Error
        # this is a collision, which is to be treated as if it is not runnable
        $stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
        return false, entry
      end

      sleep 3
      begin
        @worksheet.reload
      rescue GoogleDrive::Error
        # this is a collision, which is to be treated as if it is not runnable
        $stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
        return false, entry
      end

      check = entry[@agent_name]
      (status, running_hostname) = check.split(':')
      if hostname == running_hostname
        return true, entry
      end
      $stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
      return false, entry
    end

this call initiates a race resistant attempt to make sure that there is only 1
 clear 'winner' among N potential agents attempting to run the same goal on the
 same spreadsheet agent's cell

this call initiates a race resistant attempt to make sure that there is only 1 clear winner among N potential agents attempting to run the same goal on the same spreadsheet agent s cell


def pick(number, *cards)
      ordered = cards.flatten.map do |card|
        i = card_preference.map { |preference| card.type == preference }.index(true)
        {card: card, index: i}
      end
      ordered.sort_by { |h| h[:index] || 99 }.first(number).map {|h| h[:card] }
    end

def pick ( number , * cards ) ordered = cards . flatten . map do | card | i = card_preference . map { | preference | card . type == preference } . index ( true ) { card : card , index : i } end ordered . sort_by { | h | h [ :index ] || 99 } . first ( number ) . map { | h | h [ :card ] } end

you have the option of picking from many cards, pick the best one.

you have the option of picking from many cards pick the best one .


def discard
      ordered = player.hand.map do |card|
        i = card_preference.map { |preference| card.type == preference }.index(true)
        {card: card, index: i}
      end
      ordered.sort_by { |h| h[:index] || 99 }.last.try(:fetch, :card)
    end

def discard ordered = player . hand . map do | card | i = card_preference . map { | preference | card . type == preference } . index ( true ) { card : card , index : i } end ordered . sort_by { | h | h [ :index ] || 99 } . last . try ( :fetch , :card ) end

This method is called if your hand is over the hand limit, it returns the card that you would like to discard.
 Returning nil or a card you don't have is a very bad idea. Bad things will happen to you.

This method is called if your hand is over the hand limit it returns the card that you would like to discard . Returning nil or a card you don t have is a very bad idea . Bad things will happen to you .


def play
      bangs_played = 0
      while !player.hand.find_all(&:draws_cards?).empty?
        player.hand.find_all(&:draws_cards?).each {|card| player.play_card(card)}
      end
      play_guns
      player.hand.each do |card|
        target = find_target(card)
        next if skippable?(card, target, bangs_played)
        bangs_played += 1 if card.type == Card.bang_card
        player.play_card(card, target, :hand)
      end
    end

def play bangs_played = 0 while ! player . hand . find_all ( :draws_cards? ) . empty? player . hand . find_all ( :draws_cards? ) . each { | card | player . play_card ( card ) } end play_guns player . hand . each do | card | target = find_target ( card ) next if skippable? ( card , target , bangs_played ) bangs_played += 1 if card . type == Card . bang_card player . play_card ( card , target , :hand ) end end

This is the method that is called on your turn.

This is the method that is called on your turn .


def sleep(timeout = nil)
      validate_timeout(timeout)
      unlock do
        if timeout == nil || timeout == Float::INFINITY
          elapsed_time = (timer { Thread.stop }).round
        else
          elapsed_time = Kernel.sleep(timeout)
        end
      end
    end

def sleep ( timeout = nil ) validate_timeout ( timeout ) unlock do if timeout == nil || timeout == Float :: INFINITY elapsed_time = ( timer { Thread . stop } ) . round else elapsed_time = Kernel . sleep ( timeout ) end end end

Releases the lock and puts this thread to sleep.
 @param timeout [nil, Numeric] time to sleep in seconds or +nil+ to sleep forever
 @raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
 @raise [ArgumentError] if +timeout+ is not positive
 @return [Integer] elapsed time sleeping

Releases the lock and puts this thread to sleep .


def temporarily_release(&block)
      raise ArgumentError, 'no block given' unless block_given?
      unlock
      begin
        return_value = yield
        lock
      rescue Exception
        lock_immediately
        raise
      end
      return_value
    end

def
temporarily_release
(
&
block
)
raise
ArgumentError
,
'no block given'
unless
block_given?
unlock
begin
return_value
=
yield
lock
rescue
Exception
lock_immediately
raise
end
return_value
end

Temporarily unlocks it while a block is run.
 If an error is raised in the block the it will try to be immediately relocked
   before passing the error up. If unsuccessful, a +ThreadError+ will be raised to
   imitate the core's behavior.
 @api private
 @raise [ThreadError] if relock unsuccessful after an error
 @raise [ArgumentError] if no block given
 @return [void]

Temporarily unlocks it while a block is run . If an error is raised in the block the it will try to be immediately relocked before passing the error up . If unsuccessful a + ThreadError + will be raised to imitate the core s behavior .


def timer(&block)
      start_time = Time.now
      yield(start_time)
      time_elapsed = Time.now - start_time
    end

def timer ( & block ) start_time = Time . now yield ( start_time ) time_elapsed = Time . now - start_time end

Calculate time elapsed when running block.
 @api private
 @yield called while running timer
 @yieldparam start_time [Time]
 @raise [Exception] any exception raised in block
 @return [Float] time elapsed while running block

Calculate time elapsed when running block .


def wait
      continue = false
      trap "SIGINT" do
        puts "Continuing..."
        continue = true
      end
      puts "Waiting. Press ^C to continue test..."
      wait_until(3600) { continue }
      trap "SIGINT", "DEFAULT"
    end

def
wait
continue
=
false
trap
"SIGINT"
do
puts
"Continuing..."
continue
=
true
end
puts
"Waiting. Press ^C to continue test..."
wait_until
(
3600
)
{
continue
}
trap
"SIGINT"
,
"DEFAULT"
end

stalls test until ^C is hit
 useful for inspecting page state via firebug


def optional_args_block_call(block, args)
      if RUBY_VERSION >= "1.9.0"
        if block.arity == 0
          block.call
        else
          block.call(*args)
        end
      else
        block.call(*args)
      end
    end

def optional_args_block_call ( block , args ) if RUBY_VERSION >= "1.9.0" if block . arity == 0 block . call else block . call ( args ) end else block . call ( args ) end end

Makes a call to a block that accepts optional arguments


def extract_file_rdoc(file, from = nil, reverse = false)
      lines = File.readlines(file)
      if from.nil? and reverse
        lines = lines.reverse
      elsif !reverse
        lines = lines[(from || 0)..-1]
      else
        lines = lines[0...(from || -1)].reverse
      end

      doc, started = [], false
      lines.each{|line|
        if /^\s*[#]/ =~ line
          doc << line
          started = true
        elsif started
          break
        end
      }

      doc = reverse ? doc.reverse[0..-1] : doc[0..-1]
      doc = doc.join("\n")
      doc.gsub(/^\s*[#] ?/, "")
    end

def extract_file_rdoc ( file , from = nil , reverse = false ) lines = File . readlines ( file ) if from . nil? and reverse lines = lines . reverse elsif ! reverse lines = lines [ ( from || 0 ) .. - 1 ] else lines = lines [ 0 ... ( from || - 1 ) ] . reverse end doc , started = [ ] , false lines . each { | line | if / \s / =~ line doc << line started = true elsif started break end } doc = reverse ? doc . reverse [ 0 .. - 1 ] : doc [ 0 .. - 1 ] doc = doc . join ( "\n" ) doc . gsub ( / \s / , "" ) end

Extracts the rdoc of a given ruby file source.

Extracts the rdoc of a given ruby file source .


def select(fields)
      if (fields == []) || (fields.nil?)
        fields = [:_id]
      end
      clone.tap {|q| q.options[:fields] = fields}
    end

def select ( fields ) if ( fields == [ ] ) || ( fields . nil? ) fields = [ :_id ] end clone . tap { | q | q . options [ :fields ] = fields } end

Add select method to select the fields to return


def set_pagination_info(page_no, page_size, record_count)
      @current_page = page_no
      @per_page = page_size
      @total_count = record_count
      @total_pages = (record_count / page_size.to_f).ceil

      extend PaginationMethods

      self
    end


def echo_uploads_data=(data)
      parsed = JSON.parse Base64.decode64(data)
      # parsed will look like:
      # { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] }
      unless parsed.is_a? Hash
        raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
      end
      parsed.each do |attr, attr_data|
        # If the :map option was passed, there may be multiple variants of the uploaded
        # file. Even if not, attr_data is still a one-element array.
        unless attr_data.is_a? Array
          raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
        end
        attr_data.each do |variant_data|
          unless variant_data.is_a? Hash
            raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
          end
          if meta = ::EchoUploads::File.where(
            id: variant_data['id'], key: variant_data['key'], temporary: true
          ).first
            if send("#{attr}_tmp_metadata").nil?
              send "#{attr}_tmp_metadata=", []
            end
            send("#{attr}_tmp_metadata") << meta
          end
        end
      end
    end

Pass in a hash that's been encoded as JSON and then Base64.

Pass in a hash that s been encoded as JSON and then Base64 .


def follower_of?(model)
      0 < self.followees.by_model(model).limit(1).count * model.followers.by_model(self).limit(1).count
    end

def follower_of? ( model ) 0 < self . followees . by_model ( model ) . limit ( 1 ) . count * model . followers . by_model ( self ) . limit ( 1 ) . count end

see if this model is follower of some model

 Example:
   >> @jim.follower_of?(@ruby)
   => true


def follow(*models)
      models.each do |model|
        unless model == self or self.follower_of?(model) or model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
          model.followers.create!(:f_type => self.class.name, :f_id => self.id.to_s)
          model.followed_history << self.class.name + '_' + self.id.to_s
          model.save
          self.followees.create!(:f_type => model.class.name, :f_id => model.id.to_s)
          self.follow_history << model.class.name + '_' + model.id.to_s
          self.save
        end
      end
    end

def follow ( * models ) models . each do | model | unless model == self or self . follower_of? ( model ) or model . followee_of? ( self ) or self . cannot_follow . include? ( model . class . name ) or model . cannot_followed . include? ( self . class . name ) model . followers . create! ( :f_type => self . class . name , :f_id => self . id . to_s ) model . followed_history << self . class . name + '_' + self . id . to_s model . save self . followees . create! ( :f_type => model . class . name , :f_id => model . id . to_s ) self . follow_history << model . class . name + '_' + model . id . to_s self . save end end end


def unfollow(*models)
      models.each do |model|
        unless model == self or !self.follower_of?(model) or !model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
          model.followers.by_model(self).first.destroy
          self.followees.by_model(model).first.destroy
        end
      end
    end

def unfollow ( * models ) models . each do | model | unless model == self or ! self . follower_of? ( model ) or ! model . followee_of? ( self ) or self . cannot_follow . include? ( model . class . name ) or model . cannot_followed . include? ( self . class . name ) model . followers . by_model ( self ) . first . destroy self . followees . by_model ( model ) . first . destroy end end end


def ever_follow
      follow = []
      self.follow_history.each do |h|
        follow << h.split('_')[0].constantize.find(h.split('_')[1])
      end
      follow
    end

def ever_follow follow = [ ] self . follow_history . each do | h | follow << h . split ( '_' ) [ 0 ] . constantize . find ( h . split ( '_' ) [ 1 ] ) end follow end

see user's follow history

 Example:
   >> @jim.ever_follow
   => [@ruby]


def pop(non_block = false)
      @pop_mutex.lock do
        @mutex.synchronize do
          if empty?
            return if closed?
            raise ThreadError if non_block
            @mutex.unlock
            @waiter.wait
            @mutex.lock
            return if closed?
          end
          @items.shift
        end
      end
    end

def pop ( non_block = false ) @pop_mutex . lock do @mutex . synchronize do if empty? return if closed? raise ThreadError if non_block @mutex . unlock @waiter . wait @mutex . lock return if closed? end @items . shift end end end

Retrieves an item from it.
 @note If it is empty, the method will block until an item is available.
 If +non_block+ is +true+, a +ThreadError+ will be raised.
 @raise [ThreadError] if it is empty and +non_block+ is +true+
 @param non_block [Boolean]
 @return [Object]


def lookup(key, opts={}, &block)
      unless addr = cache.has?(key)
        addr = link.send('lookup', key, opts, &block)
        cache.save(key, addr)
      end
      yield addr if block_given?
      addr
    end

def lookup ( key , opts = { } , & block ) unless addr = cache . has? ( key ) addr = link . send ( 'lookup' , key , opts , block ) cache . save ( key , addr ) end yield addr if block_given? addr end

Initialize can accept custom configuration parameters
 Lookup for a specific service `key`
 passed block is called with the result values
 in case of `http` backend it return the result directly
 @param key [string] identifier of the service

Initialize can accept custom configuration parameters Lookup for a specific service key passed block is called with the result values in case of http backend it return the result directly


def announce(key, port, opts={}, &block)
      payload = [key,port]
      link.send 'announce', payload, opts, &block
      if config.auto_announce
        periodically(config.auto_announce_interval) do
          link.send 'announce', payload, opts, &block
        end
      end
    end

def announce ( key , port , opts = { } , & block ) payload = [ key , port ] link . send 'announce' , payload , opts , block if config . auto_announce periodically ( config . auto_announce_interval ) do link . send 'announce' , payload , opts , block end end end

Announce a specific service `key` available on specific `port`
 passed block is called when the announce is sent
 @param key [string] service identifier
 @param port [int] service port number
 @block callback

Announce a specific service key available on specific port passed block is called when the announce is sent


def _logical_operator(delegated, *conditions)
      unless conditions.all?{|c|conditionable? c}
        raise TypeError, 'wrong object for condition'
      end

      ->v{
        conditions.__send__(delegated) {|condition|
          _valid? condition, v
        }
      }
    end

def
_logical_operator
(
delegated
,
*
conditions
)
unless
conditions
.
all?
{
|
c
|
conditionable?
c
}
raise
TypeError
,
'wrong object for condition'
end
->
v
{
conditions
.
__send__
(
delegated
)
{
|
condition
|
_valid?
condition
,
v
}
}
end

Condition Builders
 A innner method for some condition builders.
 For build conditions AND, NAND, OR, NOR, XOR, XNOR.
 @param delegated [Symbol]
 @return [lambda]

Condition Builders A innner method for some condition builders . For build conditions AND NAND OR NOR XOR XNOR .


def post_with_signature(opts)
      path = opts.fetch(:path)
      payload = opts.fetch(:payload)
      secret = opts.fetch(:secret)

      post path, {payload: payload}, generate_secret_header(secret, URI.encode_www_form(payload: payload))
    end

def post_with_signature ( opts ) path = opts . fetch ( :path ) payload = opts . fetch ( :payload ) secret = opts . fetch ( :secret ) post path , { payload : payload } , generate_secret_header ( secret , URI . encode_www_form ( payload : payload ) ) end

Post to the given path, including the correct signature header based on the payload and secret.
 @param [Hash] opts The options to use when crafting the request.
 @option opts [String] :path The full path of the endpoint to which to post
 @option opts [String] :payload A JSON-parseable string containing a payload as described in http://developer.github.com/v3/activity/events/types/
 @option opts [String] :secret The secret to use when calculating the HMAC for the X-Hub-Signature header

Post to the given path including the correct signature header based on the payload and secret .


def get_height(img)
      new_height = (img.height / (img.width.to_f / self.width.to_f)).ceil
    end

def get_height ( img ) new_height = ( img . height / ( img . width . to_f / self . width . to_f ) ) . ceil end

Finds height of the image relative to provided width


def create_color_string
      (0...img.height).map do |y|
        (0...img.width).map do |x|
          pix = self.img[x,y]
          pix_vals = [r(pix), g(pix), b(pix)]
          find_closest_term_color(pix_vals)
        end
      end.join
    end

def create_color_string ( 0 ... img . height ) . map do | y | ( 0 ... img . width ) . map do | x | pix = self . img [ x , y ] pix_vals = [ r ( pix ) , g ( pix ) , b ( pix ) ] find_closest_term_color ( pix_vals ) end end . join end

Iterates over each pixel of resized image to find closest color