def recolor(bg: '#000', fg: '#fff', bg_opacity: "1.0", fg_opacity: "1.0")
      OptionalDeps.require_nokogiri
      bg.prepend('#') unless bg.start_with? '#'
      fg.prepend('#') unless fg.start_with? '#'
      doc     = Nokogiri::XML(self.string)
      doc.css('path')[0]['fill'] = bg # dark backdrop
      doc.css('path')[1]['fill'] = fg # light drawing
      doc.css('path')[0]['fill-opacity'] = bg_opacity.to_s # dark backdrop
      doc.css('path')[1]['fill-opacity'] = fg_opacity.to_s # light drawing
      @svgstr = doc.to_xml
      self
    end

def recolor ( bg : '#000' , fg : '#fff' , bg_opacity : "1.0" , fg_opacity : "1.0" ) OptionalDeps . require_nokogiri bg . prepend ( '#' ) unless bg . start_with? '#' fg . prepend ( '#' ) unless fg . start_with? '#' doc = Nokogiri :: XML ( self . string ) doc . css ( 'path' ) [ 0 ] [ 'fill' ] = bg doc . css ( 'path' ) [ 1 ] [ 'fill' ] = fg doc . css ( 'path' ) [ 0 ] [ 'fill-opacity' ] = bg_opacity . to_s doc . css ( 'path' ) [ 1 ] [ 'fill-opacity' ] = fg_opacity . to_s @svgstr = doc . to_xml self end

Modify the background and foreground colors and their opacities


def compact_copy (target_path)

      @other_db = Cabinet.new(target_path)
      self.each { |k, v| @other_db[k] = v }
      @other_db.close
    end

def compact_copy ( target_path ) @other_db = Cabinet . new ( target_path ) self . each { | k , v | @other_db [ k ] = v } @other_db . close end

Copies the current cabinet to a new file.

 Does it by copying each entry afresh to the target file. Spares some
 space, hence the 'compact' label...

Copies the current cabinet to a new file .


def keys (options={})

      if @type == "tcf"
        min, max = "min", "max"
        l        = lib.tcfdbrange2( as_fixed, min, Rufus::Tokyo.blen(min),
                                              max, Rufus::Tokyo.blen(max), -1)
      else
        pre = options.fetch(:prefix, "")

        l = lib.abs_fwmkeys(
          @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)
      end

      l = Rufus::Tokyo::List.new(l)

      options[:native] ? l : l.release
    end

def keys ( options = { } ) if @type == "tcf" min , max = "min" , "max" l = lib . tcfdbrange2 ( as_fixed , min , Rufus :: Tokyo . blen ( min ) , max , Rufus :: Tokyo . blen ( max ) , - 1 ) else pre = options . fetch ( :prefix , "" ) l = lib . abs_fwmkeys ( @db , pre , Rufus :: Tokyo . blen ( pre ) , options [ :limit ] || - 1 ) end l = Rufus :: Tokyo :: List . new ( l ) options [ :native ] ? l : l . release end

Returns an array with all the keys in the databse

 With no options given, this method will return all the keys (strings)
 in a Ruby array.

   :prefix --> returns only the keys who match a given string prefix

   :limit --> returns a limited number of keys

   :native --> returns an instance of Rufus::Tokyo::List instead of
     a Ruby Hash, you have to call #free on that List when done with it !
     Else you're exposing yourself to a memory leak.


def get4 (k)

      l = lib.tcbdbget4(as_btree, k, Rufus::Tokyo.blen(k))
      Rufus::Tokyo::List.new(l).release
    end

def get4 ( k ) l = lib . tcbdbget4 ( as_btree , k , Rufus :: Tokyo . blen ( k ) ) Rufus :: Tokyo :: List . new ( l ) . release end

This is a B+ Tree method only, returns all the values for a given
 key.

This is a B + Tree method only returns all the values for a given key .


def []= (k, v)

      clib.tcmapput(pointer, k, Rufus::Tokyo::blen(k), v, Rufus::Tokyo::blen(v))

      v
    end

def []= ( k , v ) clib . tcmapput ( pointer , k , Rufus :: Tokyo :: blen ( k ) , v , Rufus :: Tokyo :: blen ( v ) ) v end

Creates an empty instance of a Tokyo Cabinet in-memory map

 (It's OK to pass the pointer of a C map directly, this is in fact
 used in rufus/tokyo/table when retrieving entries)

 Inserts key/value pair

Creates an empty instance of a Tokyo Cabinet in - memory map


def delete (k)

      v = self[k]
      return nil unless v

      clib.tcmapout(pointer_or_raise, k, Rufus::Tokyo::blen(k)) ||
        raise("failed to remove key '#{k}'")

      v
    end

def
delete
(
k
)
v
=
self
[
k
]
return
unless
v
clib
.
tcmapout
(
pointer_or_raise
,
k
,
Rufus
::
Tokyo
::
blen
(
k
)
)
||
raise
(
"failed to remove key '#{k}'"
)
v
end


def keys

      clib.tcmapiterinit(pointer_or_raise)
      a = []

      klen = FFI::MemoryPointer.new(:int)

      loop do
        k = clib.tcmapiternext(@pointer, klen)
        break if k.address == 0
        a << k.get_bytes(0, klen.get_int(0))
      end

      return a

    ensure

      klen.free
    end

def keys clib . tcmapiterinit ( pointer_or_raise ) a = [ ] klen = FFI :: MemoryPointer . new ( :int ) loop do k = clib . tcmapiternext ( @pointer , klen ) break if k . address == 0 a << k . get_bytes ( 0 , klen . get_int ( 0 ) ) end return a ensure klen . free end

Returns an array of all the keys in the map


def []= (a, b, c=nil)

      i, s = c.nil? ? [ a, b ] : [ [a, b], c ]

      range = if i.is_a?(Range)
        i
      elsif i.is_a?(Array)
        start, count = i
        (start..start + count - 1)
      else
        [ i ]
      end

      range = norm(range)

      values = s.is_a?(Array) ? s : [ s ]
      # not "values = Array(s)"

      range.each_with_index do |offset, index|
        val = values[index]
        if val
          clib.tclistover(@pointer, offset, val, Rufus::Tokyo.blen(val))
        else
          outlen_op(:tclistremove, values.size)
        end
      end

      self
    end

def []= ( a , b , c = nil ) i , s = c . nil? ? [ a , b ] : [ [ a , b ] , c ] range = if i . is_a? ( Range ) i elsif i . is_a? ( Array ) start , count = i ( start .. start + count - 1 ) else [ i ] end range = norm ( range ) values = s . is_a? ( Array ) ? s : [ s ] range . each_with_index do | offset , index | val = values [ index ] if val clib . tclistover ( @pointer , offset , val , Rufus :: Tokyo . blen ( val ) ) else outlen_op ( :tclistremove , values . size ) end end self end


def keys (options={})

      pre = options.fetch(:prefix, "")

      l = lib.tab_fwmkeys(
        @db, pre, Rufus::Tokyo.blen(pre), options[:limit] || -1)

      l = Rufus::Tokyo::List.new(l)

      options[:native] ? l : l.release
    end

def keys ( options = { } ) pre = options . fetch ( :prefix , "" ) l = lib . tab_fwmkeys ( @db , pre , Rufus :: Tokyo . blen ( pre ) , options [ :limit ] || - 1 ) l = Rufus :: Tokyo :: List . new ( l ) options [ :native ] ? l : l . release end

Returns an array of all the primary keys in the table

 With no options given, this method will return all the keys (strings)
 in a Ruby array.

   :prefix --> returns only the keys who match a given string prefix

   :limit --> returns a limited number of keys

   :native --> returns an instance of Rufus::Tokyo::List instead of
     a Ruby Hash, you have to call #free on that List when done with it !
     Else you're exposing yourself to a memory leak.


def lget (*keys)

      keys.flatten.inject({}) { |h, k|
        k = k.to_s
        v = self[k]
        h[k] = v if v
        h
      }
    end

def lget ( * keys ) keys . flatten . inject ( { } ) { | h , k | k = k . to_s v = self [ k ] h [ k ] = v if v h } end

No 'misc' methods for the table library, so this lget is equivalent
 to calling get for each key. Hoping later versions of TC will provide
 a mget method.

No misc methods for the table library so this lget is equivalent to calling get for each key . Hoping later versions of TC will provide a mget method .


def raise_error

      err_code = lib.tab_ecode(@db)
      err_msg = lib.tab_errmsg(err_code)

      raise TokyoError.new("(err #{err_code}) #{err_msg}")
    end

def
raise_error
err_code
=
lib
.
tab_ecode
(
@db
)
err_msg
=
lib
.
tab_errmsg
(
err_code
)
raise
TokyoError
.
new
(
"(err #{err_code}) #{err_msg}"
)
end

Obviously something got wrong, let's ask the db about it and raise
 a TokyoError

Obviously something got wrong let s ask the db about it and raise a TokyoError


def each

      (0..size-1).each do |i|
        pk = @list[i]
        if @opts[:pk_only]
          yield(pk)
        else
          val = @table[pk]
          val[:pk] = pk unless @opts[:no_pk]
          yield(val)
        end
      end
    end

def each ( 0 .. size - 1 ) . each do | i | pk = @list [ i ] if @opts [ :pk_only ] yield ( pk ) else val = @table [ pk ] val [ :pk ] = pk unless @opts [ :no_pk ] yield ( val ) end end end


def find(icon)
      str = icon.to_s.downcase
      file = DB.files[str] ||
               DB.files[str.sub(/\.svg$/,'')] ||
               not_found(str, icon)
      Icon.new(file)
    end

def find ( icon ) str = icon . to_s . downcase file = DB . files [ str ] || DB . files [ str . sub ( / \. / , '' ) ] || not_found ( str , icon ) Icon . new ( file ) end

Find the icon, possibly without the extension.
 @example Finder.new.find('glass-heart')
 Raises an error if the icon could not be found.

Find the icon possibly without the extension .


def get_columns(table_name)
			columns_arr = []
		    pst = @db.prepare "SELECT * FROM #{table_name} LIMIT 6"
		    pst.columns.each do |c|
		    	columns_arr.push(c)
		    end
		  columns_arr
		end

def
get_columns
(
table_name
)
columns_arr
=
[
]
pst
=
@db
.
prepare
"SELECT * FROM #{table_name} LIMIT 6"
pst
.
columns
.
each
do
|
c
|
columns_arr
.
push
(
c
)
end
columns_arr
end


def is_numeric(table_name, column_name)
			if @db.execute("SELECT #{column_name} from #{table_name} LIMIT 1").first.first.is_a? Numeric
				return true
			else
				return false
			end
		end

If the column type is nominal return true.

If the column type is nominal return true .


def deal_with_valid_option(temp_tables, temp_columns, temp_column_types, res)
			if !temp_tables.empty?
				check_given_tables_validity(temp_tables)
				temp_tables.each do |t|
					res << convert_table(t)
				end
			elsif !temp_columns.keys.empty?
				check_given_columns_validity(temp_columns)
				res << convert_from_columns_hash(temp_columns)
			elsif !temp_column_types.empty?
				check_given_columns_validity(temp_column_types)
				res << convert_from_column_types_hash(temp_column_types)
			end
		end

def deal_with_valid_option ( temp_tables , temp_columns , temp_column_types , res ) if ! temp_tables . empty? check_given_tables_validity ( temp_tables ) temp_tables . each do | t | res << convert_table ( t ) end elsif ! temp_columns . keys . empty? check_given_columns_validity ( temp_columns ) res << convert_from_columns_hash ( temp_columns ) elsif ! temp_column_types . empty? check_given_columns_validity ( temp_column_types ) res << convert_from_column_types_hash ( temp_column_types ) end end

If valid option was provided in convert method


def let_context(*args, &block)
      context_string, hash =
        case args.map(&:class)
        when [String, Hash] then ["#{args[0]} #{args[1]}", args[1]]
        when [Hash] then [args[0].inspect, args[0]]
        end

      context(context_string) do
        hash.each { |var, value| let(var) { value } }

        instance_eval(&block)
      end
    end

def
let_context
(
*
args
,
&
block
)
context_string
,
hash
=
case
args
.
map
(
&
:class
)
when
[
String
,
Hash
]
then
[
"#{args[0]} #{args[1]}"
,
args
[
1
]
]
when
[
Hash
]
then
[
args
[
0
]
.
inspect
,
args
[
0
]
]
end
context
(
context_string
)
do
hash
.
each
{
|
var
,
value
|
let
(
var
)
{
value
}
}
instance_eval
(
&
block
)
end
end

This allows us to simplify the case where we want to
 have a context which contains one or more `let` statements

 Supports giving either a Hash or a String and a Hash as arguments
 In both cases the Hash will be used to define `let` statements
 When a String is specified that becomes the context description
 If String isn't specified, Hash#inspect becomes the context description

 @example Defining a simple let variable
   # Before
   subject { a + 1 }
   context('a is 1') do
     let(:a) { 1 }
     it { should eq 2 }
   end

   # After
   subject { a + 1 }
   let_context(a: 1) { it { should eq 2 } }

 @example Giving a descriptive string
   subject { a + 1 }
   let_context('Negative number', a: -1) { it { should eq 0 } }

 @example Multiple variables
   subject { a + b }
   let_context(a: 1, b: 2) { it { should eq 3 } }

This allows us to simplify the case where we want to have a context which contains one or more let statements


def subject_should_raise(*args)
      error, message = args
      it_string = "subject should raise #{error}"
      it_string += " (#{message.inspect})" if message

      it it_string do
        expect { subject }.to raise_error error, message
      end
    end

def
subject_should_raise
(
*
args
)
error
,
message
=
args
it_string
=
"subject should raise #{error}"
it_string
+=
" (#{message.inspect})"
if
message
it
it_string
do
expect
{
subject
}
.
to
raise_error
error
,
message
end
end

Allows you to simply specify that the subject should raise an exception
 Takes no arguments or arguments of an exception class, a string, or both.

 As with RSpec's basic `to raise_error` matcher, if you don't give an error
 then the an unexpected error may cause your test to pass incorrectly

 @example Raising a string
   # Before
   subject { fail 'Test' }
   it "should raise 'Test'" do
     expect { subject }.to raise_error 'Test'
   end

   # After
   subject { fail 'Test' }
   subject_should_raise 'Test'

 @example Raising an exception class
   subject { fail ArgumentError }
   subject_should_raise ArgumentError

 @example Raising an exception class and string
   subject { fail ArgumentError, 'Test' }
   subject_should_raise ArgumentError, 'Test'

Allows you to simply specify that the subject should raise an exception Takes no arguments or arguments of an exception class a string or both .


def subject_should_not_raise(*args)
      error, message = args
      it_string = "subject should not raise #{error}"
      it_string += " (#{message.inspect})" if message

      it it_string do
        expect { subject }.not_to raise_error error, message
      end
    end

def
subject_should_not_raise
(
*
args
)
error
,
message
=
args
it_string
=
"subject should not raise #{error}"
it_string
+=
" (#{message.inspect})"
if
message
it
it_string
do
expect
{
subject
}
.
not_to
raise_error
error
,
message
end
end

Allows you to simply specify that the subject should not raise an exception.
 Takes no arguments or arguments of an exception class, a string, or both.

 As with RSpec's basic `not_to raise_error` matcher, if you give a specific error, other
 unexpected errors may be swallowed silently

 @example Subject does not raise an error
   # Before
   subject { 1 }
   it 'should not raise an exception' do
     expect { subject }.not_to raise_error
   end

   # After
   subject { 1 }
   subject_should_not_raise

Allows you to simply specify that the subject should not raise an exception . Takes no arguments or arguments of an exception class a string or both .


def login(user, options = {})
      options[:scope] ||= Janus.scope_for(user)
      set_user(user, options)
      Janus::Manager.run_callbacks(:login, user, self, options)
    end

def login ( user , options = { } ) options [ :scope ] ||= Janus . scope_for ( user ) set_user ( user , options ) Janus :: Manager . run_callbacks ( :login , user , self , options ) end

Logs a user in.

 FIXME: what should happen when a user signs in but a user is already signed in for the same scope?!


def logout(*scopes)
      scopes = janus_sessions.keys if scopes.empty?

      scopes.each do |scope|
        _user = user(scope)
        unset_user(scope)
        Janus::Manager.run_callbacks(:logout, _user, self, :scope => scope)
      end

      request.reset_session if janus_sessions.empty?
    end

def logout ( * scopes ) scopes = janus_sessions . keys if scopes . empty? scopes . each do | scope | _user = user ( scope ) unset_user ( scope ) Janus :: Manager . run_callbacks ( :logout , _user , self , :scope => scope ) end request . reset_session if janus_sessions . empty? end

Logs a user out from the given scopes or from all scopes at once
 if no scope is defined. If no scope is left after logout, then the
 whole session will be resetted.

Logs a user out from the given scopes or from all scopes at once if no scope is defined . If no scope is left after logout then the whole session will be resetted .


def set_user(user, options = {})
      scope = options[:scope] || Janus.scope_for(user)
      janus_sessions[scope.to_s] = { 'user_class' => user.class.name, 'user_id' => user.id }
    end

def set_user ( user , options = { } ) scope = options [ :scope ] || Janus . scope_for ( user ) janus_sessions [ scope . to_s ] = { 'user_class' => user . class . name , 'user_id' => user . id } end

Manually sets a user without going throught the whole login or
 authenticate process.

Manually sets a user without going throught the whole login or authenticate process .


def unset_user(scope)
      janus_sessions.delete(scope.to_s)
      @users.delete(scope.to_sym) unless @users.nil?
    end

def unset_user ( scope ) janus_sessions . delete ( scope . to_s ) @users . delete ( scope . to_sym ) unless @users . nil? end

Manually removes the user without going throught the whole logout process.

Manually removes the user without going throught the whole logout process .


def user(scope)
      scope = scope.to_sym
      @users ||= {}

      if authenticated?(scope)
        if @users[scope].nil?
          begin
          @users[scope] = user_class(scope).find(session(scope)['user_id'])
          rescue ActiveRecord::RecordNotFound
            unset_user(scope)
          else
            Janus::Manager.run_callbacks(:fetch, @users[scope], self, :scope => scope)
          end
        end

        @users[scope]
      end
    end

def user ( scope ) scope = scope . to_sym @users ||= { } if authenticated? ( scope ) if @users [ scope ] . nil? begin @users [ scope ] = user_class ( scope ) . find ( session ( scope ) [ 'user_id' ] ) rescue ActiveRecord :: RecordNotFound unset_user ( scope ) else Janus :: Manager . run_callbacks ( :fetch , @users [ scope ] , self , :scope => scope ) end end @users [ scope ] end end


def namespace
      return '#' if Tml.config.disabled?
      @namespace || Tml.config.cache[:namespace] || Tml.config.application[:key][0..5]
    end

def namespace return '#' if Tml . config . disabled? @namespace || Tml . config . cache [ :namespace ] || Tml . config . application [ :key ] [ 0 .. 5 ] end


def extract_version(app, version = nil)
      if version
        Tml.cache.version.set(version.to_s)
      else
        version_data = app.api_client.get_from_cdn('version', {t: Time.now.to_i}, {uncompressed: true})

        unless version_data
          Tml.logger.debug('No releases have been generated yet. Please visit your Dashboard and publish translations.')
          return
        end

        Tml.cache.version.set(version_data['version'])
      end
    end


def warmup(version = nil, cache_path = nil)
      if cache_path.nil?
        warmup_from_cdn(version)
      else
        warmup_from_files(version, cache_path)
      end
    end

def warmup ( version = nil , cache_path = nil ) if cache_path . nil? warmup_from_cdn ( version ) else warmup_from_files ( version , cache_path ) end end


def warmup_from_files(version = nil, cache_path = nil)
      t0 = Time.now
      Tml.logger = Logger.new(STDOUT)

      Tml.logger.debug('Starting cache warmup from local files...')
      version ||= Tml.config.cache[:version]
      cache_path ||= Tml.config.cache[:path]
      cache_path = "#{cache_path}/#{version}"

      Tml.cache.version.set(version.to_s)
      Tml.logger.debug("Warming Up Version: #{Tml.cache.version}")

      application = JSON.parse(File.read("#{cache_path}/application.json"))
      Tml.cache.store(Tml::Application.cache_key, application)

      sources = JSON.parse(File.read("#{cache_path}/sources.json"))

      application['languages'].each do |lang|
        locale = lang['locale']

        language = JSON.parse(File.read("#{cache_path}/#{locale}/language.json"))
        Tml.cache.store(Tml::Language.cache_key(locale), language)

        sources.each do |src|
          source = JSON.parse(File.read("#{cache_path}/#{locale}/sources/#{src}.json"))
          Tml.cache.store(Tml::Source.cache_key(locale, src), source)
        end
      end

      t1 = Time.now
      Tml.logger.debug("Cache warmup took #{t1-t0}s")
    end


def warmup_from_cdn(version = nil)
      t0 = Time.now
      Tml.logger = Logger.new(STDOUT)

      Tml.logger.debug('Starting cache warmup from CDN...')
      app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])
      extract_version(app, version)

      Tml.logger.debug("Warming Up Version: #{Tml.cache.version}")

      application = app.api_client.get_from_cdn('application', {t: Time.now.to_i})
      Tml.cache.store(Tml::Application.cache_key, application)

      sources = app.api_client.get_from_cdn('sources', {t: Time.now.to_i}, {uncompressed: true})

      application['languages'].each do |lang|
        locale = lang['locale']
        language = app.api_client.get_from_cdn("#{locale}/language", {t: Time.now.to_i})
        Tml.cache.store(Tml::Language.cache_key(locale), language)

        sources.each do |src|
          source = app.api_client.get_from_cdn("#{locale}/sources/#{src}", {t: Time.now.to_i})
          Tml.cache.store(Tml::Source.cache_key(locale, src), source)
        end
      end

      t1 = Time.now
      Tml.logger.debug("Cache warmup took #{t1-t0}s")
    end


def default_cache_path
      @cache_path ||= begin
        path = Tml.config.cache[:path]
        path ||= 'config/tml'
        FileUtils.mkdir_p(path)
        FileUtils.chmod(0777, path)
        path
      end
    end

def default_cache_path @cache_path ||= begin path = Tml . config . cache [ :path ] path ||= 'config/tml' FileUtils . mkdir_p ( path ) FileUtils . chmod ( 0777 , path ) path end end


def download(cache_path = default_cache_path, version = nil)
      t0 = Time.now
      Tml.logger = Logger.new(STDOUT)

      Tml.logger.debug('Starting cache download...')
      app = Tml::Application.new(key: Tml.config.application[:key], cdn_host: Tml.config.application[:cdn_host])
      extract_version(app, version)

      Tml.logger.debug("Downloading Version: #{Tml.cache.version}")

      archive_name = "#{Tml.cache.version}.tar.gz"
      path = "#{cache_path}/#{archive_name}"
      url = "#{app.cdn_host}/#{Tml.config.application[:key]}/#{archive_name}"

      Tml.logger.debug("Downloading cache file: #{url}")
      open(path, 'wb') do |file|
        file << open(url).read
      end

      Tml.logger.debug('Extracting cache file...')
      version_path = "#{cache_path}/#{Tml.cache.version}"
      Tml::Utils.untar(Tml::Utils.ungzip(File.new(path)), version_path)
      Tml.logger.debug("Cache has been stored in #{version_path}")

      File.unlink(path)

      begin
        current_path = 'current'
        FileUtils.chdir(cache_path)
        FileUtils.rm(current_path) if File.exist?(current_path)
        FileUtils.ln_s(Tml.cache.version.to_s, current_path)
        Tml.logger.debug("The new version #{Tml.cache.version} has been marked as current")
      rescue Exception => ex
        Tml.logger.debug("Could not generate current symlink to the cache path: #{ex.message}")
      end

      t1 = Time.now
      Tml.logger.debug("Cache download took #{t1-t0}s")
    end


def say(message, color=nil)
      @shell ||= Thor::Shell::Basic.new
      @shell.say message, color
    end

def say ( message , color = nil ) @shell ||= Thor :: Shell :: Basic . new @shell . say message , color end


def validate_cache_version(version)
      # if cache version is hardcoded, use it
      if Tml.config.cache[:version]
        return Tml.config.cache[:version]
      end

      return version unless version.is_a?(Hash)
      return 'undefined' unless version['t'].is_a?(Numeric)
      return version['version'] if cache.read_only?

      # if version check interval is disabled, don't try to check for the new
      # cache version on the CDN
      if version_check_interval == -1
        Tml.logger.debug('Cache version check is disabled')
        return version['version']
      end

      expires_at = version['t'] + version_check_interval
      if expires_at < Time.now.to_i
        Tml.logger.debug('Cache version is outdated, needs refresh')
        return 'undefined'
      end

      delta = expires_at - Time.now.to_i
      Tml.logger.debug("Cache version is up to date, expires in #{delta}s")
      version['version']
    end

validate that current cache version hasn't expired

validate that current cache version hasn t expired


def fetch
      self.version = begin
        ver = cache.fetch(CACHE_VERSION_KEY) do
          {'version' => Tml.config.cache[:version] || 'undefined', 't' => cache_timestamp}
        end
        validate_cache_version(ver)
      end
    end

def fetch self . version = begin ver = cache . fetch ( CACHE_VERSION_KEY ) do { 'version' => Tml . config . cache [ :version ] || 'undefined' , 't' => cache_timestamp } end validate_cache_version ( ver ) end end


def [] file, *ps, &exe
			opts = ::Hash === ps.last ? ps.pop : {}
			opts[:env] = self
			name, type, flg = ps[0] || opts[:name], ps[1] || opts[:type], ps[2] || opts[:flags]
			ps.push opts
			@dbs[ [file, name, flg | CREATE]] ||= (type || SBDB::Unknown).new file, *ps, &exe
		end

def [] file , * ps , & exe opts = :: Hash === ps . last ? ps . pop : { } opts [ :env ] = self name , type , flg = ps [ 0 ] || opts [ :name ] , ps [ 1 ] || opts [ :type ] , ps [ 2 ] || opts [ :flags ] ps . push opts @dbs [ [ file , name , flg | CREATE ] ] ||= ( type || SBDB :: Unknown ) . new file , * ps , & exe end

Returns the DB like open, but if it's already opened,
 it returns the old instance.
 If you use this, never use close. It's possible somebody else use it too.
 The Databases, which are opened, will close, if the Environment will close.

Returns the DB like open but if it s already opened it returns the old instance . If you use this never use close . It s possible somebody else use it too . The Databases which are opened will close if the Environment will close .


def run_strategies(scope)
      Janus::Manager.strategies.each { |name| break if run_strategy(name, scope) }
    end

def run_strategies ( scope ) Janus :: Manager . strategies . each { | name | break if run_strategy ( name , scope ) } end

Runs authentication strategies to log a user in.

Runs authentication strategies to log a user in .


def run_strategy(name, scope)
      strategy = "Janus::Strategies::#{name.to_s.camelize}".constantize.new(scope, self)

      if strategy.valid?
        strategy.authenticate!

        if strategy.success?
          send(strategy.auth_method, strategy.user, :scope => scope)
          Janus::Manager.run_callbacks(:authenticate, strategy.user, self, :scope => scope)
        end
      end

      strategy.success?
    end

Runs a given strategy and returns true if it succeeded.

Runs a given strategy and returns true if it succeeded .


def perform(script)
      export_variables = @params.reverse_merge("PARADUCT_JOB_ID" => @job_id, "PARADUCT_JOB_NAME" => job_name)
      variable_string = export_variables.map { |key, value| %(export #{key}="#{value}";) }.join(" ")

      Array.wrap(script).inject("") do |stdout, command|
        stdout << run_command("#{variable_string} #{command}")
        stdout
      end
    end

def
perform
(
script
)
export_variables
=
@params
.
reverse_merge
(
"PARADUCT_JOB_ID"
=>
@job_id
,
"PARADUCT_JOB_NAME"
=>
job_name
)
variable_string
=
export_variables
.
map
{
|
key
,
value
|
%(export #{key}="#{value}";)
}
.
join
(
" "
)
Array
.
wrap
(
script
)
.
inject
(
""
)
do
|
stdout
,
command
|
stdout
<<
run_command
(
"#{variable_string} #{command}"
)
stdout
end
end

run script with params
 @param script [String, Array<String>] script file, script(s)
 @return [String] stdout
 @raise [Paraduct::Errors::ProcessError] command exited error status


def print_hex(data, chunk_index, cols=80)
      case hex_style
      when 'lower', 'lowercase'
        # encode to lowercase hex with no newlines
        print Sixword::Hex.encode(data)
      when 'finger', 'fingerprint'
        # encode to GPG fingerprint like hex with newlines
        newlines_every = cols / 5
        if chunk_index != 0
          if chunk_index % newlines_every == 0
            print "\n"
          else
            print ' '
          end
        end
        print Sixword::Hex.encode_fingerprint(data)
      when 'colon', 'colons'
        # encode to SSL/SSH fingerprint like hex with colons
        print ':' unless chunk_index == 0
        print Sixword::Hex.encode_colons(data)
      end
    end

def
print_hex
(
data
,
chunk_index
,
cols
=
80
)
case
hex_style
when
'lower'
,
'lowercase'
print
Sixword
::
Hex
.
encode
(
data
)
when
'finger'
,
'fingerprint'
newlines_every
=
cols
/
5
if
chunk_index
!=
0
if
chunk_index
%
newlines_every
==
0
print
"\n"
else
print
' '
end
end
print
Sixword
::
Hex
.
encode_fingerprint
(
data
)
when
'colon'
,
'colons'
print
':'
unless
chunk_index
==
0
print
Sixword
::
Hex
.
encode_colons
(
data
)
end
end


def read_input_by_6_words
      word_arr = []

      while true
        line = stream.gets
        if line.nil?
          break # EOF
        end

        line.scan(/\S+/) do |word|
          word_arr << word

          # return the array if we have accumulated 6 words
          if word_arr.length == 6
            yield word_arr
            word_arr.clear
          end
        end
      end

      # yield whatever we have left, if anything
      if !word_arr.empty?
        yield word_arr
      end
    end

def read_input_by_6_words word_arr = [ ] while true line = stream . gets if line . nil? break end line . scan ( / \S / ) do | word | word_arr << word if word_arr . length == 6 yield word_arr word_arr . clear end end end if ! word_arr . empty? yield word_arr end end


def select(query, filters)
      where, *bind_values = conditions(query, filters)
      [
        [
          from(filters),
          where,
          order_by(filters),
          limits(filters)
        ].join(" "),
        *bind_values
      ]
    end

def
select
(
query
,
filters
)
where
,
*
bind_values
=
conditions
(
query
,
filters
)
[
[
from
(
filters
)
,
where
,
order_by
(
filters
)
,
limits
(
filters
)
]
.
join
(
" "
)
,
*
bind_values
]
end

Initialize a new QueryBuilder for +index_name+.

 @param [Symbol] index_name
   the name of the index being queried
 Build a SphinxQL query for the fulltext search +query+ and filters in +filters+.

 @param [String] query
   the fulltext query to execute (may be empty)

 @param [Hash] filters
   additional attribute filters and other options

 @return [String]
   a SphinxQL query

Initialize a new QueryBuilder for + index_name + .


def update(id, attributes)
      set_attrs, *bind_values = update_attributes(attributes)
      [
        [
          "UPDATE #{@index_name} SET",
          set_attrs,
          "WHERE id = ?"
        ].join(" "),
        *bind_values.push(id)
      ]
    end

def
update
(
id
,
attributes
)
set_attrs
,
*
bind_values
=
update_attributes
(
attributes
)
[
[
"UPDATE #{@index_name} SET"
,
set_attrs
,
"WHERE id = ?"
]
.
join
(
" "
)
,
*
bind_values
.
push
(
id
)
]
end

Build a SphinxQL query to update the record identified by +id+ with the given attributes.

 @param [Fixnum] id
   the unique ID of the document to update

 @param [Hash] attributes
   a Hash of attributes

 @return [String]
   the SphinxQL to update the record

Build a SphinxQL query to update the record identified by + id + with the given attributes .


def query(sql, *bind_values)
      @pool.acquire { |conn| conn.query(sql, *bind_values).first }
    end

def query ( sql , * bind_values ) @pool . acquire { | conn | conn . query ( sql , * bind_values ) . first } end

Execute a single read query.

 @param [String] sql
   a single SphinxQL statement

 @param [Object...] bind_values
   values to be substituted in place of '?' in the query

 @return [Array]
   an array of Hashes containing the matched records

 Note that SphinxQL does not support prepared statements.


def method_missing(method, *args, &block)
      if method.to_s =~ /^asynch?_(.*)/
        if instance_methods(false).detect{|meth| meth.to_s == $1 }
          Woodhouse.dispatch(@worker_name, $1, args.first)
        else
          super
        end
      else
        super
      end
    end

def method_missing ( method , * args , & block ) if method . to_s =~ / / if instance_methods ( false ) . detect { | meth | meth . to_s == $1 } Woodhouse . dispatch ( @worker_name , $1 , args . first ) else super end else super end end

You can dispatch a job +baz+ on class +FooBar+ by calling FooBar.async_baz.

You can dispatch a job + baz + on class + FooBar + by calling FooBar . async_baz .


def add_node(node)
      if node.respond_to?(:to_sym)
        node = Woodhouse::Layout::Node.new(node.to_sym)
      end
      expect_arg :node, Woodhouse::Layout::Node, node
      @nodes << node
      node
    end

def add_node ( node ) if node . respond_to? ( :to_sym ) node = Woodhouse :: Layout :: Node . new ( node . to_sym ) end expect_arg :node , Woodhouse :: Layout :: Node , node @nodes << node node end

Adds a Node to this layout. If +node+ is a Symbol, a Node will be
 automatically created with that name.

   # Example:

   layout.add_node Woodhouse::Layout::Node.new(:isis)

   # Is equivalent to

   layout.add_node :isis

Adds a Node to this layout . If + node + is a Symbol a Node will be automatically created with that name .


def node(name)
      name = name.to_sym
      @nodes.detect{|node|
        node.name == name
      }
    end

def node ( name ) name = name . to_sym @nodes . detect { | node | node . name == name } end

Looks up a Node by name and returns it .


def canonical(attribute_list)
      case attribute_list
      when nil then {}
      when Hash then attribute_list
      when Array
        attribute_list.map do |attributes|
          case attributes
          when Symbol
            {attributes => AUTO}
          when Hash
            attributes
          else
            raise "Unexpected attributes #{attributes}"
          end
        end
        .inject({}, :merge)
      else
        raise "Unexpected attribute_list #{attribute_list}"
      end
    end

Converts an attribute_list to a single Hash;
 some of the values may be set to AUTO.

   canonical [:foo, {:bar => 42}]
    # => {:foo => AUTO, :bar => 42}

Converts an attribute_list to a single Hash ; some of the values may be set to AUTO .


def imagine(character_or_model, attributes = nil)
      character = to_character(character_or_model)
      prev, @building = @building, [] # because method might be re-entrant
      CharacterBuilder.new(character).build(attributes) do |ar|
        ar.save!
        # While errors on records associated with :has_many will prevent records
        # from being saved, they won't for :belongs_to, so:
        @building.each do |built|
          raise ActiveRecord::RecordInvalid, built unless built.persisted? || built.valid?
        end
        Scheherazade.log(:saving, character, ar)
        handle_callbacks(@building)
      end
    ensure
      @built.concat(@building)
      @building = prev
    end

def imagine ( character_or_model , attributes = nil ) character = to_character ( character_or_model ) prev , @building = @building , [ ] CharacterBuilder . new ( character ) . build ( attributes ) do | ar | ar . save! @building . each do | built | raise ActiveRecord :: RecordInvalid , built unless built . persisted? || built . valid? end Scheherazade . log ( :saving , character , ar ) handle_callbacks ( @building ) end ensure @built . concat ( @building ) @building = prev end

Creates a character with the given attributes

 A character can be designated either by the model (e.g. `User`), the corresponding
 symbol (`:user`) or the symbol for a specialized type of character, defined using +fill+
 (e.g. `:admin`).

 The attributes can be nil, a list of symbols, a hash or a combination of both
 These, along with attributes passed to +fill+ for the current stories
 and the mandatory attributes for the model will be provided.

 If some fields generate validation errors, they will be provided also.

 For associations, the values can also be a character (Symbol or Model),
 integers (meaning the default Model * that integer) or arrays of characters.

    imagine(:user, :account, :company => :fortune_500_company, :emails => 3)

 Similarly:

    User.imagine(...)
    :user.imagine(...)

 This record (and any other imagined through associations) will become the
 current character in the current story:

    story.current[User] # => nil
    story.tell do
      :admin.imagine # => A User record
      story.current[:admin] # => same
      story.current[User]   # => same
    end
    story.current[User] # => nil


def with(temp_current)
      keys = temp_current.keys.map{|k| to_character(k)}
      previous_values = current.values_at(*keys)
      current.merge!(Hash[keys.zip(temp_current.values)])
      yield
    ensure
      current.merge!(Hash[keys.zip(previous_values)])
    end

def with ( temp_current ) keys = temp_current . keys . map { | k | to_character ( k ) } previous_values = current . values_at ( * keys ) current . merge! ( Hash [ keys . zip ( temp_current . values ) ] ) yield ensure current . merge! ( Hash [ keys . zip ( previous_values ) ] ) end

Allows one to temporarily override the current characters while
 the given block executes


def failure(exception_class_or_message, message_or_nil = nil)
      blank.tap do |d|
        d.fail(
          case exception_class_or_message
          when Exception
            raise ArgumentError, "can't specify both exception and message" if message_or_nil
            exception_class_or_message
          when Class
            exception_class_or_message.new(message_or_nil)
          else
            RuntimeError.new(exception_class_or_message.to_s)
          end)
      end
    end

Return a Deferrable which immediately fails with an exception.

 @overload failure(message)
   Passes +RuntimeError.new(message)+ to errbacks.
 @overload failure(exception_class)
   Passes +exception_class.new+ to errbacks.
 @overload failure(exception_class, message)
   Passes +exception_class.new(message)+ to errbacks.
 @overload failure(exception)
   Passes +exception+ to errbacks.

Return a Deferrable which immediately fails with an exception .


def file_length
      if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE
        self.errors.add :audio, "It's length is excesive. #{MAX_FILE_SIZE} is the limit."
        return false
      end

      return true
    end

Function to check that the file size isn't excesive.

Function to check that the file size isn t excesive .


def api_call method, payload
      raise ArgumentError, "API method not specified." if method.blank?

      payload ||= {}

      res = @conn.post method.to_s, payload

      raise Faraday::Error, "Wrong response: #{res.inspect}" if (res.status != 200)

      return res
    end

def
api_call
method
,
payload
raise
ArgumentError
,
"API method not specified."
if
method
.
blank?
payload
||=
{
}
res
=
@conn
.
post
method
.
to_s
,
payload
raise
Faraday
::
Error
,
"Wrong response: #{res.inspect}"
if
(
res
.
status
!=
200
)
return
res
end


def multi_search(queries)
      unless queries.kind_of?(Hash)
        raise ArgumentError, "Argument must be a Hash of named queries (#{queries.class} given)"
      end

      stmts       = []
      bind_values = []

      queries.each do |key, args|
        str, *values = @builder.select(*extract_query_data(args))
        stmts.push(str, "SHOW META")
        bind_values.push(*values)
      end

      rs = @conn.multi_query(stmts.join(";\n"), *bind_values)

      Hash[].tap do |result|
        queries.keys.each do |key|
          records, meta = rs.shift, rs.shift
          result[key] = meta_to_hash(meta).tap do |r|
            r[:records] = records.map { |hash|
              hash.inject({}) { |o, (k, v)| o.merge!(k.to_sym => v) }
            }
          end
        end
      end
    end

Perform a a batch search on the index.

 A Hash of queries is passed, whose keys are used to collate the results in
 the return value.

 Each query may either by a string (fulltext search), a Hash (attribute search)
 or an array containing both.  In other words, the same arguments accepted by
 the #search method.

 @example
   index.multi_search(
     cat_results: ["cats", { author_id: 57 }],
     dog_results: ["dogs", { author_id: 57 }]
   )

 @param [Hash] queries
   a hash whose keys map to queries

 @return [Hash]
   a Hash whose keys map 1:1 with the input Hash, each element containing the
   same results as those returned by the #search method.


def has_whereabouts klass=:address, *args
      options = args.extract_options!
      # extend Address with class name if not defined.
      unless klass == :address || Object.const_defined?(klass.to_s.camelize)
        create_address_class(klass.to_s.camelize)
      end

      # Set the has_one relationship and accepts_nested_attributes_for.
      has_one klass, :as => :addressable, :dependent => :destroy
      accepts_nested_attributes_for klass

      # Define a singleton on the class that returns an array
      # that includes the address fields to validate presence of
      # or an empty array
      if options[:validate] && options[:validate].is_a?(Array)
        validators = options[:validate]
        set_validators(klass, validators)
      else
        validators = []
      end
      define_singleton_method validate_singleton_for(klass) do validators end

      # Check for geocode in options and confirm geocoder is defined.
      # Also defines a singleton to return a boolean about geocoding.
      if options[:geocode] && options[:geocode] == true && defined?(Geocoder)
        geocode = true
        set_geocoding(klass)
      else
        geocode = false
      end
      define_singleton_method geocode_singleton_for(klass) do geocode end
    end

def has_whereabouts klass = :address , * args options = args . extract_options! unless klass == :address || Object . const_defined? ( klass . to_s . camelize ) create_address_class ( klass . to_s . camelize ) end has_one klass , :as => :addressable , :dependent => :destroy accepts_nested_attributes_for klass if options [ :validate ] && options [ :validate ] . is_a? ( Array ) validators = options [ :validate ] set_validators ( klass , validators ) else validators = [ ] end define_singleton_method validate_singleton_for ( klass ) do validators end if options [ :geocode ] && options [ :geocode ] == true && defined? ( Geocoder ) geocode = true set_geocoding ( klass ) else geocode = false end define_singleton_method geocode_singleton_for ( klass ) do geocode end end

Accepts a symbol that will define the inherited
 type of Address.  Defaults to the parent class.

Accepts a symbol that will define the inherited type of Address . Defaults to the parent class .


def set_validators klass, fields=[]
      _single = validate_singleton_for(klass)
      klass.to_s.camelize.constantize.class_eval do
        fields.each do |f|
          validates_presence_of f,
            :if => lambda {|a| a.addressable_type.constantize.send(_single).include?(f)}
        end
      end
    end

def set_validators klass , fields = [ ] _single = validate_singleton_for ( klass ) klass . to_s . camelize . constantize . class_eval do fields . each do | f | validates_presence_of f , :if => lambda { | a | a . addressable_type . constantize . send ( _single ) . include? ( f ) } end end end

Sets validates_presence_of fields for the Address based on the
 singleton method created on the Address addressable_type class.

Sets validates_presence_of fields for the Address based on the singleton method created on the Address addressable_type class .


def create_address_class(class_name, &block)
      klass = Class.new Address, &block
      Object.const_set class_name, klass
    end

def create_address_class ( class_name , & block ) klass = Class . new Address , & block Object . const_set class_name , klass end

Generate a new class using Address as the superclass.
 Accepts a string defining the inherited type.

Generate a new class using Address as the superclass . Accepts a string defining the inherited type .


def event_loop
      Qwirk.logger.debug "#{self}: Starting receive loop"
      @start_worker_time = Time.now
      until @stopped || (config.stopped? && @impl.ready_to_stop?)
        Qwirk.logger.debug "#{self}: Waiting for read"
        @start_read_time = Time.now
        msg = @impl.receive_message
        if msg
          @start_processing_time = Time.now
          Qwirk.logger.debug {"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds"}
          delta = config.timer.measure do
            @processing_mutex.synchronize do
              on_message(msg)
              @impl.acknowledge_message(msg)
            end
          end
          Qwirk.logger.info {"#{self}::on_message (#{'%.1f' % delta}ms)"} if self.config.log_times
          Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)
        end
      end
      Qwirk.logger.info "#{self}: Exiting"
    rescue Exception => e
      @status = "Terminated: #{e.message}"
      Qwirk.logger.error "#{self}: Exception, thread terminating: #{e.message}\n\t#{e.backtrace.join("\n\t")}"
    ensure
      @status = 'Stopped'
      Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush)
      config.worker_stopped(self)
    end

Start the event loop for handling messages off the queue


def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
      attrs = {}
      attribute_names.each do |name|
        if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
          if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
            value = read_attribute(name)
            if self.class.columns_hash[name].type == :hstore && value && value.is_a?(Hash)
              value = value.to_hstore # Done!
            elsif value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time) || value.is_a?(Hash) || value.is_a?(Array))
              value = value.to_yaml
            end
            attrs[self.class.arel_table[name]] = value
          end
        end
      end
      attrs
    end

def arel_attributes_values ( include_primary_key = true , include_readonly_attributes = true , attribute_names = @attributes . keys ) attrs = { } attribute_names . each do | name | if ( column = column_for_attribute ( name ) ) && ( include_primary_key || ! column . primary ) if include_readonly_attributes || ( ! include_readonly_attributes && ! self . class . readonly_attributes . include? ( name ) ) value = read_attribute ( name ) if self . class . columns_hash [ name ] . type == :hstore && value && value . is_a? ( Hash ) value = value . to_hstore elsif value && self . class . serialized_attributes . has_key? ( name ) && ( value . acts_like? ( :date ) || value . acts_like? ( :time ) || value . is_a? ( Hash ) || value . is_a? ( Array ) ) value = value . to_yaml end attrs [ self . class . arel_table [ name ] ] = value end end end attrs end

This method is replaced for Rails 3 compatibility.
 All I do is add the condition when the field is a hash that converts the value
 to hstore format.
 IMHO this should be delegated to the column, so it won't be necessary to rewrite all
 this method.

This method is replaced for Rails 3 compatibility . All I do is add the condition when the field is a hash that converts the value to hstore format . IMHO this should be delegated to the column so it won t be necessary to rewrite all this method .


def requires_version(cmd, version_)
      v = check_version(version_)
      raise NoMethodError, format('%s is not supported in Bugzilla %s', cmd, v[1]) unless v[0]
    end

def
requires_version
(
cmd
,
version_
)
v
=
check_version
(
version_
)
raise
NoMethodError
,
format
(
'%s is not supported in Bugzilla %s'
,
cmd
,
v
[
1
]
)
unless
v
[
0
]
end

def check_version
 rdoc

 ==== Bugzilla::Bugzilla#requires_version(cmd, version_)

 Raise an exception if the Bugzilla doesn't satisfy
 the requirement of the _version_.


def run
      begin
        Clacks.logger.info "Clacks v#{Clacks::VERSION} started"
        if Clacks.config[:pop3]
          run_pop3
        elsif Clacks.config[:imap]
          run_imap
        else
          raise "Either a POP3 or an IMAP server must be configured"
        end
      rescue Exception => e
        fatal(e)
      end
    end


def imap_validate_options(options)
      options ||= {}
      options[:mailbox] ||= 'INBOX'
      options[:count]   ||= 5
      options[:order]   ||= :asc
      options[:what]    ||= :first
      options[:keys]    ||= 'ALL'
      options[:delete_after_find] ||= false
      options[:mailbox] = Net::IMAP.encode_utf7(options[:mailbox])
      if options[:archivebox]
        options[:archivebox] = Net::IMAP.encode_utf7(options[:archivebox])
      end
      options
    end

def imap_validate_options ( options ) options ||= { } options [ :mailbox ] ||= 'INBOX' options [ :count ] ||= 5 options [ :order ] ||= :asc options [ :what ] ||= :first options [ :keys ] ||= 'ALL' options [ :delete_after_find ] ||= false options [ :mailbox ] = Net :: IMAP . encode_utf7 ( options [ :mailbox ] ) if options [ :archivebox ] options [ :archivebox ] = Net :: IMAP . encode_utf7 ( options [ :archivebox ] ) end options end

Follows mostly the defaults from the Mail gem


def imap_find(imap)
      options = Clacks.config[:find_options]
      delete_after_find = options[:delete_after_find]
      begin
        break if stopping?
        uids = imap.uid_search(options[:keys] || 'ALL')
        uids.reverse! if options[:what].to_sym == :last
        uids = uids.first(options[:count]) if options[:count].is_a?(Integer)
        uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
                         (options[:what].to_sym != :last && options[:order].to_sym == :desc)
        processed = 0
        expunge = false
        uids.each do |uid|
          break if stopping?
          source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']
          mail = nil
          begin
            mail = Mail.new(source)
            mail.mark_for_delete = true if delete_after_find
            Clacks.config[:on_mail].call(mail)
          rescue StandardError => e
            Clacks.logger.error(e.message)
            Clacks.logger.error(e.backtrace)
          end
          begin
            imap.uid_copy(uid, options[:archivebox]) if options[:archivebox]
            if delete_after_find && (mail.nil? || mail.is_marked_for_delete?)
              expunge = true
              imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED])
            end
          rescue StandardError => e
            Clacks.logger.error(e.message)
          end
          processed += 1
        end
        imap.expunge if expunge
      end while uids.any? && processed == uids.length
    end

def imap_find ( imap ) options = Clacks . config [ :find_options ] delete_after_find = options [ :delete_after_find ] begin break if stopping? uids = imap . uid_search ( options [ :keys ] || 'ALL' ) uids . reverse! if options [ :what ] . to_sym == :last uids = uids . first ( options [ :count ] ) if options [ :count ] . is_a? ( Integer ) uids . reverse! if ( options [ :what ] . to_sym == :last && options [ :order ] . to_sym == :asc ) || ( options [ :what ] . to_sym != :last && options [ :order ] . to_sym == :desc ) processed = 0 expunge = false uids . each do | uid | break if stopping? source = imap . uid_fetch ( uid , [ 'RFC822' ] ) . first . attr [ 'RFC822' ] mail = nil begin mail = Mail . new ( source ) mail . mark_for_delete = true if delete_after_find Clacks . config [ :on_mail ] . call ( mail ) rescue StandardError => e Clacks . logger . error ( e . message ) Clacks . logger . error ( e . backtrace ) end begin imap . uid_copy ( uid , options [ :archivebox ] ) if options [ :archivebox ] if delete_after_find && ( mail . nil? || mail . is_marked_for_delete? ) expunge = true imap . uid_store ( uid , "+FLAGS" , [ Net :: IMAP :: DELETED ] ) end rescue StandardError => e Clacks . logger . error ( e . message ) end processed += 1 end imap . expunge if expunge end while uids . any? && processed == uids . length end

Keep processing emails until nothing is found anymore,
 or until a QUIT signal is received to stop the process.

Keep processing emails until nothing is found anymore or until a QUIT signal is received to stop the process .


def rainbow(str)
    i=0
    ret = ''
    str=str.to_s
    while(i < str.length)
      ch = str[i]
      palette = $color_db[0][i % $color_db[0].length ]
      ret << (colora(palette,str[i,1]))
      i += 1
    end
    ret
  end

def rainbow ( str ) i = 0 ret = '' str = str . to_s while ( i < str . length ) ch = str [ i ] palette = $color_db [ 0 ] [ i % $color_db [ 0 ] . length ] ret << ( colora ( palette , str [ i , 1 ] ) ) i += 1 end ret end


def large_enough_prime(input)
      standard_primes.each do |prime|
        return prime if prime > input
      end
      fail CannotFindLargeEnoughPrime, "Input too large"
    end

def
large_enough_prime
(
input
)
standard_primes
.
each
do
|
prime
|
return
prime
if
prime
>
input
end
fail
CannotFindLargeEnoughPrime
,
"Input too large"
end

Retrieves the next largest prime for the largest number in batch

 Example

   Prime.large_enough_prime 4
   # => 7

 @param input [Integer] the integer to find the next largest prime for
 @return [Integer] the next largest prime
 @raise [CannotFindLargeEnoughPrime] raised when input is too large and
   no large enough prime can be found


def enhance_content(value, separator = ', ')
      value.is_a?(Array) ? value.join(separator) : value
    end

def
enhance_content
(
value
,
separator
=
', '
)
value
.
is_a?
(
Array
)
value
.
join
(
separator
)
:
value
end

Combines array into a string with given separator


def i_to_s(input)
      if !input.is_a?(Integer) || input < 0
        fail NotPositiveInteger, "input must be a non-negative integer"
      end

      output = ""
      while input > 0
        input, codepoint = input.divmod(charset.length)
        output.prepend(codepoint_to_char(codepoint))
      end
      output
    end

def
i_to_s
(
input
)
if
!
input
.
is_a?
(
Integer
)
||
input
<
0
fail
NotPositiveInteger
,
"input must be a non-negative integer"
end
output
=
""
while
input
>
0
input
,
codepoint
=
input
.
divmod
(
charset
.
length
)
output
.
prepend
(
codepoint_to_char
(
codepoint
)
)
end
output
end

The "null-byte" character is prepended to be the first character in the
 charset to avoid loosing the first character of the charset when it is
 also the first character in a string to convert.

 Example

   SecretSharing::Charset::DynamicCharset.new ["a", "b", "c"] # =>
   #<SecretSharing::Charset::DynamicCharset @charset=[...]>

 @param charset [Array] array of characters to use for the charset.
 Calculate a string from an integer.

 Example

   charset = SecretSharing::Charset.by_charset_string "abc"
   charset.i_to_s 6
   # => "ab"

 @param input [Integer] integer to convert to string
 @return [String] converted string

The null - byte character is prepended to be the first character in the charset to avoid loosing the first character of the charset when it is also the first character in a string to convert .


def s_to_i(string)
      string.chars.reduce(0) do |output, char|
        output * charset.length + char_to_codepoint(char)
      end
    end

def s_to_i ( string ) string . chars . reduce ( 0 ) do | output , char | output * charset . length + char_to_codepoint ( char ) end end

Calculate an integer from a string.

 Example

   charset = SecretSharing::Charset.by_charset_string "abc"
   charset.s_to_i "ab"
   # => 6

 @param string [Integer] integer to convert to string
 @return [String] converted string


def char_to_codepoint(c)
      codepoint = charset.index c
      if codepoint.nil?
        fail NotInCharset, "Char \"#{c}\" not part of the supported charset"
      end
      codepoint
    end

Convert a single character into its integer representation according to
 the charset.

 Example

   charset = SecretSharing::Charset.by_charset_string "abc"
   charset.char_to_codepoint "a"
   # => 1

 @param c [String] Character to retrieve its codepoint in the charset
 @return [Integer] Codepoint within the charset

Convert a single character into its integer representation according to the charset .


def subset?(string)
      (Set.new(string.chars) - Set.new(charset)).empty?
    end

def subset? ( string ) ( Set . new ( string . chars ) - Set . new ( charset ) ) . empty? end

Check if the provided string can be represented by the charset.

 Example

   charset = SecretSharing::Charset.by_charset_string "abc"
   charset.subset? "d"
   # => false
   charset.subset? "a"
   # => true

 @param string [String] Character to retrieve the for codepoint
 @return [TrueClass|FalseClass]

Check if the provided string can be represented by the charset .


def points(num_points, prime)
      intercept = @coefficients[0] # the first coefficient is the intercept
      (1..num_points).map do |x|
        y = intercept
        (1...@coefficients.length).each do |i|
          y = (y + @coefficients[i] * x ** i) % prime
        end
        Point.new(x, y)
      end
    end

def points ( num_points , prime ) intercept = @coefficients [ 0 ] ( 1 .. num_points ) . map do | x | y = intercept ( 1 ... @coefficients . length ) . each do | i | y = ( y + @coefficients [ i ] * x ** i ) % prime end Point . new ( x , y ) end end

Create a new instance of a Polynomial with n coefficients, when having
 the polynomial in standard polynomial form.

 Example

   For the polynomial f(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n the
   coefficients are [a0, a1, a2, ..., an]

   Polynomial.new [1, 2, 3]
   # => #<SecretSharing::Polynomial:0x0000000 @coefficients=[1, 2, 3]>

 @param coefficients [Array] an array of integers as the coefficients
 Generate points on the polynomial, that can be used to reconstruct the
 polynomial with.

 Example

   SecretSharing::Polynomial.new([1, 2, 3, 4]).points(3, 7)
   # => [#<Point: @x=1 @y=3>, #<Point: @x=2 @y=0>, #<Point: @x=3 @y=2>]

 @param num_points [Integer] number of points to generate
 @param prime [Integer] prime for calculation in finite field
 @return [Array] array of calculated points

Create a new instance of a Polynomial with n coefficients when having the polynomial in standard polynomial form .


def validate!
      files = Dir.glob(File.join(@directory, '*.xml')).sort
      threads = []
      files.map do |path|
        threads << Thread.new(path) do |path_t|
          eadid = File.basename(path_t, '.xml')
          begin
            ead = Mead::Ead.new({:file => File.open(path_t), :eadid => eadid})
          rescue => e
            record_invalid(eadid, ead, e)
            next
          end
          if ead.valid?
            @valid << eadid
          else
            record_invalid(eadid, ead)
          end
        end
      end
      threads.each { |thread|  thread.join }
      metadata
    end

def validate! files = Dir . glob ( File . join ( @directory , '*.xml' ) ) . sort threads = [ ] files . map do | path | threads << Thread . new ( path ) do | path_t | eadid = File . basename ( path_t , '.xml' ) begin ead = Mead :: Ead . new ( { :file => File . open ( path_t ) , :eadid => eadid } ) rescue => e record_invalid ( eadid , ead , e ) next end if ead . valid? @valid << eadid else record_invalid ( eadid , ead ) end end end threads . each { | thread | thread . join } metadata end

Creates a new EadValidator when given the path to a directory as a String


def notify_create
      self.ChannelPublications.each do |publication, options|
        if options[:actions].include? :create
          # Checks if records is within scope before broadcasting
          records = self.class.scoped_collection(options[:scope])

          if options[:scope]==:all or record_within_scope(records)
            ActionCable.server.broadcast publication,
              msg: 'create',
              id: self.id,
              data: self
          end
        end
      end
    end

def notify_create self . ChannelPublications . each do | publication , options | if options [ :actions ] . include? :create records = self . class . scoped_collection ( options [ :scope ] ) if options [ :scope ] == :all or record_within_scope ( records ) ActionCable . server . broadcast publication , msg : 'create' , id : self . id , data : self end end end end

Broadcast notifications when a new record is created


def notify_update
      # Get model changes
      if self.respond_to?(:saved_changes) # For Rails >= 5.1
        changes = self.saved_changes.transform_values(&:second)
      else # For Rails < 5.1
        changes = self.changes.transform_values(&:second)
      end

      # Checks if there are changes in the model
      if !changes.empty?
        self.ChannelPublications.each do |publication, options|
          if options[:actions].include? :update
            # Checks if previous record was within scope
            record = record_within_scope(options[:records])
            was_in_scope = record.present?

            options[:records].delete(record) if was_in_scope

            # Checks if current record is within scope
            if options[:track_scope_changes]==true
              is_in_scope = false
              if options[:scope]==:all
                record = self
                is_in_scope = true
              else
                record = record_within_scope(self.class.scoped_collection(options[:scope]))
                if record.present?
                  is_in_scope = true
                end
              end
            else
              is_in_scope = was_in_scope
            end

            # Broadcasts notifications about model changes
            if is_in_scope
              if was_in_scope
                # Get model changes and applies them to the scoped collection record
                changes.select!{|k,v| record.respond_to?(k)}

                if !changes.empty?
                  ActionCable.server.broadcast publication,
                    msg: 'update',
                    id: self.id,
                    data: changes
                end
              else
                ActionCable.server.broadcast publication,
                  msg: 'create',
                  id: record.id,
                  data: record
              end
            elsif was_in_scope # checks if needs to delete the record if its no longer in scope
              ActionCable.server.broadcast publication,
                msg: 'destroy',
                id: self.id
            end
          end
        end
      end
    end

def notify_update if self . respond_to? ( :saved_changes ) changes = self . saved_changes . transform_values ( & :second ) else changes = self . changes . transform_values ( & :second ) end if ! changes . empty? self . ChannelPublications . each do | publication , options | if options [ :actions ] . include? :update record = record_within_scope ( options [ :records ] ) was_in_scope = record . present? options [ :records ] . delete ( record ) if was_in_scope if options [ :track_scope_changes ] == true is_in_scope = false if options [ :scope ] == :all record = self is_in_scope = true else record = record_within_scope ( self . class . scoped_collection ( options [ :scope ] ) ) if record . present? is_in_scope = true end end else is_in_scope = was_in_scope end if is_in_scope if was_in_scope changes . select! { | k , v | record . respond_to? ( k ) } if ! changes . empty? ActionCable . server . broadcast publication , msg : 'update' , id : self . id , data : changes end else ActionCable . server . broadcast publication , msg : 'create' , id : record . id , data : record end elsif was_in_scope ActionCable . server . broadcast publication , msg : 'destroy' , id : self . id end end end end end

Broadcast notifications when a record is updated. Only changed fields will be sent
 if they are within configured scope

Broadcast notifications when a record is updated . Only changed fields will be sent if they are within configured scope


def notify_destroy
      self.ChannelPublications.each do |publication, options|
        if options[:scope]==:all or options[:actions].include? :destroy
          # Checks if record is within scope before broadcasting
          if options[:scope]==:all or record_within_scope(self.class.scoped_collection(options[:scope])).present?
            ActionCable.server.broadcast publication,
              msg: 'destroy',
              id: self.id
          end
        end
      end
    end

def notify_destroy self . ChannelPublications . each do | publication , options | if options [ :scope ] == :all or options [ :actions ] . include? :destroy if options [ :scope ] == :all or record_within_scope ( self . class . scoped_collection ( options [ :scope ] ) ) . present? ActionCable . server . broadcast publication , msg : 'destroy' , id : self . id end end end end

Broadcast notifications when a record is destroyed.

Broadcast notifications when a record is destroyed .


def logger(obj)
      %w(debug info warn error fatal level).each do |m|
        next if obj.respond_to?(m)
        raise ArgumentError, "logger #{obj} does not respond to method #{m}"
      end
      map[:logger] = obj
    end

Sets the Logger-like object.
 The default Logger will log its output to Rails.logger if
 you're running within a rails environment, otherwise it will
 output to the path specified by +stdout_path+.

Sets the Logger - like object . The default Logger will log its output to Rails . logger if you re running within a rails environment otherwise it will output to the path specified by + stdout_path + .


def fetch_rates
      if self.class.superclass.eql?(Object)
        raise Exception.new("This method should be invoked from CurrencySpy::Scraper sub class")
      else
        check_currency_code_validity
        rate_results = {}
        RATE_DATA.each do |rate|
          symbol = rate.to_sym
          if self.class.instance_methods.include?(symbol)
            value = self.send(symbol)
            rate_results[symbol] = value unless value.nil?
          end
        end
        rate_results
      end
    end

Method which calls all rate fetching methods from the sub class and returns
 a Hash with appropriate values.

Method which calls all rate fetching methods from the sub class and returns a Hash with appropriate values .


def parse(target)
      #Handle the width option if specified.
      if (width = fmt.width) > 0
        head, tail = src[0...width], src[width..-1] || ""
      else
        head, tail = src, ""
      end

      #Do the parse on the input string or regex.
      @prematch, @match, @postmatch = head.partition(target)

      #Analyze the results.
      if found?
        @src = @postmatch + tail
        @match
      else
        nil
      end
    end

def parse ( target ) if ( width = fmt . width ) > 0 head , tail = src [ 0 ... width ] , src [ width .. - 1 ] || "" else head , tail = src , "" end @prematch , @match , @postmatch = head . partition ( target ) if found? @src = @postmatch + tail @match else nil end end

Parse the source string for a target string or regex or return nil.

Parse the source string for a target string or regex or return nil .


def grab
      width = fmt.width

      if width > 0
        result, @src = src[0...width], src[width..-1] || ""
      elsif width == 0
        result, @src = src[0...1], src[1..-1] || ""
      elsif width == -1
        result, @src = src, ""
      else
        result, @src = src[0..width], src[(width+1)..-1] || ""
      end

      result
    end

def grab width = fmt . width if width > 0 result , @src = src [ 0 ... width ] , src [ width .. - 1 ] || "" elsif width == 0 result , @src = src [ 0 ... 1 ] , src [ 1 .. - 1 ] || "" elsif width == - 1 result , @src = src , "" else result , @src = src [ 0 .. width ] , src [ ( width + 1 ) .. - 1 ] || "" end result end


def get_comments(bugs)

      params = {}

      # TODO
      # this construction should be refactored to a method
      params['ids'] = case bugs
      when Array
        bugs
      when Integer || String
        [bugs]
      else
        raise ArgumentError, format('Unknown type of arguments: %s', bugs.class)
      end

      result = comments(params)

      # not supporting comment_ids. so drop "comments".
      ret = result['bugs']
      # creation_time was added in Bugzilla 4.4. copy the 'time' value to creation_time if not available for compatibility.
      unless check_version(4.4)[0]
        ret.each do |_id, o|
          o['comments'].each do |c|
            c['creation_time'] = c['time'] unless c.include?('creation_time')
          end
        end
      end

      ret
    end

def
get_comments
(
bugs
)
params
=
{
}
params
[
'ids'
]
=
case
bugs
when
Array
bugs
when
Integer
||
String
[
bugs
]
else
raise
ArgumentError
,
format
(
'Unknown type of arguments: %s'
,
bugs
.
class
)
end
result
=
comments
(
params
)
ret
=
result
[
'bugs'
]
unless
check_version
(
4.4
)
[
0
]
ret
.
each
do
|
_id
,
o
|
o
[
'comments'
]
.
each
do
|
c
|
c
[
'creation_time'
]
=
c
[
'time'
]
unless
c
.
include?
(
'creation_time'
)
end
end
end
ret
end

def get_bugs
 rdoc

 ==== Bugzilla::Bug#get_comments(bugs)


def save_persist_state
      return unless @persist_file
      new_persist_options = {}
      BaseWorker.worker_classes.each do |worker_class|
        worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options|
          static_options = default_options.merge(@worker_options[config_name] || {})
          worker_config = self[config_name]
          hash = {}
          # Only store off the config values that are specifically different from default values or values set in the workers.yml file
          # Then updates to these values will be allowed w/o being hardcoded to an old default value.
          worker_config.bean_get_attributes do |attribute_info|
            if attribute_info.attribute[:config_item] && attribute_info.ancestry.size == 1
              param_name = attribute_info.ancestry[0].to_sym
              value = attribute_info.value
              hash[param_name] = value if static_options[param_name] != value
            end
          end
          new_persist_options[config_name] = hash unless hash.empty?
        end
      end
      if new_persist_options != @persist_options
        @persist_options = new_persist_options
        File.open(@persist_file, 'w') do |out|
          YAML.dump(@persist_options, out )
        end
      end
    end

def save_persist_state return unless @persist_file new_persist_options = { } BaseWorker . worker_classes . each do | worker_class | worker_class . each_config ( @adapter_factory . worker_config_class ) do | config_name , ignored_extended_worker_config_class , default_options | static_options = default_options . merge ( @worker_options [ config_name ] || { } ) worker_config = self [ config_name ] hash = { } worker_config . bean_get_attributes do | attribute_info | if attribute_info . attribute [ :config_item ] && attribute_info . ancestry . size == 1 param_name = attribute_info . ancestry [ 0 ] . to_sym value = attribute_info . value hash [ param_name ] = value if static_options [ param_name ] != value end end new_persist_options [ config_name ] = hash unless hash . empty? end end if new_persist_options != @persist_options @persist_options = new_persist_options File . open ( @persist_file , 'w' ) do | out | YAML . dump ( @persist_options , out ) end end end

Store off any options that are no longer set to default


def read_pages
      # get all projects
      results_projects = database.query("SELECT id, identifier, name FROM projects;")
      results_projects.each do |row_project|
        #collect all namespaces
        namespaces << OpenStruct.new(identifier: row_project["identifier"], name: row_project["name"])
      end

      # get all wikis
      results_wikis = database.query("SELECT id, project_id FROM wikis;")

      # get all lemmas
      results_pages = database.query("SELECT id, title, wiki_id FROM wiki_pages;")
      results_pages.each do |row_page|
        results_contents = database.query("SELECT * FROM wiki_content_versions WHERE page_id='#{row_page["id"]}' ORDER BY updated_on;")

        # get wiki for page
        wiki_row = nil
        project_row = nil
        results_wikis.each do |wiki|
          wiki_row = wiki if wiki["id"] == row_page["wiki_id"]
        end

        if wiki_row
          # get project from wiki-id
          results_projects.each do |project|
            project_row = project if project["id"] == wiki_row["project_id"]
          end
        end

        project_identifier = project_row ? project_row["identifier"] + '/' : ""

        title = project_identifier + row_page["title"]
        titles << title

        @latest_revisions = {}
        results_contents.each do |row_content|
          author = authors[row_content["author_id"]] ? @authors[row_content["author_id"]] : nil
          page = Page.new({:id => row_content["id"],
                            :title => title,
                            :body => row_content["data"],
                            :markup => :textile,
                            :latest => false,
                            :time => row_content["updated_on"],
                            :message => row_content["comments"],
                            :author => author,
                            :author_name => author.name})
          revisions << page
          @latest_revisions[title] = page
        end
      end
      titles.uniq!
      @latest_revisions.each { |rev| rev[1].set_latest }
      revisions.sort! { |a,b| a.time <=> b.time }

      # TODO find latest revision for each limit

      revisions
    end

after calling this action, I expect the titles and revisions to be filled

after calling this action I expect the titles and revisions to be filled


def read_response(timeout, &block)
      raise "Invalid call to read_response for #{@producer}, not setup for responding" unless @producer.response_options
      # Creates a block for reading the responses for a given message_id (adapter_info).  The block will be passed an object
      # that responds to timeout_read(timeout) with a [original_message_id, response_message, worker_name] tri or nil if no message is read.
      # This is used in the RPC mechanism where a publish might wait for 1 or more workers to respond.
      @producer.impl.with_response(@adapter_info) do |consumer|
        if block_given?
          return read_multiple_response(consumer, timeout, &block)
        else
          tri = read_single_response(consumer, timeout)
          if tri
            response = tri[1]
            raise response if response.kind_of?(Qwirk::RemoteException)
            return response
          else
            @timeout = !tri
            return nil
          end
        end
      end
    end

Waits the given timeout for a response message on the queue.

 If called w/o a block:
   Returns the message
   Returns nil on timeout
   Raises RemoteException on a remote exception

 If called with a block, for instance:
   handle.read_response(timeout) do |response|
     response.on_message 'CharCount' do |hash|
       puts "CharCount returned #{hash.inspect}"
     end
     response.on_message 'Length', 'Reverse' do |val|
       puts "#{response.name} returned #{val}"
     end
     response.on_message 'ExceptionRaiser' do |val|
       puts "#{response.name} didn't raise an exception but returned #{val}"
     end
     response.on_timeout 'Reverse' do
       puts "Reverse has it's own timeout handler"
     end
     response.on_timeout do
       puts "#{response.name} did not respond in time"
     end
     response.on_remote_exception 'ExceptionRaiser' do
       puts "It figures that ExceptionRaiser would raise an exception"
     end
     response.on_remote_exception do |e|
       puts "#{response.name} raised an exception #{e.message}\n\t#{e.backtrace.join("\n\t")}"
     end
   end

 The specified blocks will be called for each response.  For instance, LengthWorker#request
 might return 4 and "Length returned 4" would be displayed.  If it failed to respond within the
 timeout, then "Length did no respond in time" would be displayed.
 For Workers that raise an exception, they will either be handled by their specific handler if it exists or
 the default exception handler.  If that doesn't exist either, then the RemoteException will be raised for the
 whole read_response call.  Timeouts will also be handled by the default timeout handler unless a specific one
 is specified.  All messages must have a specific handler specified because the call won't return until all
 specified handlers either return, timeout, or return an exception.

Waits the given timeout for a response message on the queue .


def add_filter(id, pattern, &block)
      filter = LineFilter.new(id, pattern, block)
      @filters << filter
    end

def add_filter ( id , pattern , & block ) filter = LineFilter . new ( id , pattern , block ) @filters << filter end

if a line doesn't match any of the patterns, then
 @param name a name used to identify the command in ouput
 add a new filter for output from this command
 @param id [Symbol] an identifier for the filter within the command
 @param pattern [RegEx] a regular expression which matches a pattern in a line
 @yield yields back an array of matches from the pattern.   The block should return
   a CommmandDefinition#result_... variant

if a line doesn t match any of the patterns then


def write(template = nil)
            if not template.nil? then
                template = template.to_mixml_template
            end

            each_node do |node|
                if template.nil? then
                    node.write_xml_to($stdout)
                    puts
                else
                    puts template.evaluate(node)
                end
            end
        end

def write ( template = nil ) if not template . nil? then template = template . to_mixml_template end each_node do | node | if template . nil? then node . write_xml_to ( $stdout ) puts else puts template . evaluate ( node ) end end end

Print selected nodes to stdout

 @param template [Template::Base] Template to evaluate and print


def replace(template)
            template = template.to_mixml_template

            each_node do |node|
                value = template.evaluate(node)
                node.replace(value)
            end
        end

def replace ( template ) template = template . to_mixml_template each_node do | node | value = template . evaluate ( node ) node . replace ( value ) end end

Replace selected nodes with a template

 @param template [Template::Base] Template to replace nodes with


def rename(template)
            template = template.to_mixml_template

            each_node do |node|
                value = template.evaluate(node)
                node.name = value
            end
        end

def rename ( template ) template = template . to_mixml_template each_node do | node | value = template . evaluate ( node ) node . name = value end end

Rename selected nodes with a template

 @param template [Template::Base] Template for new name


def commit_revision(page, markup)
      gollum_page = gollum.page(page.title)
      if gollum_page
        gollum.update_page(gollum_page, gollum_page.name, gollum_page.format, page.body, build_commit(page))
      else
        gollum.write_page(page.title, markup, page.body, build_commit(page))
      end
    end

def commit_revision ( page , markup ) gollum_page = gollum . page ( page . title ) if gollum_page gollum . update_page ( gollum_page , gollum_page . name , gollum_page . format , page . body , build_commit ( page ) ) else gollum . write_page ( page . title , markup , page . body , build_commit ( page ) ) end end

Commit the given page into the gollum-wiki-repository.
 Make sure the target markup is correct before calling this method.

Commit the given page into the gollum - wiki - repository . Make sure the target markup is correct before calling this method .


def commit_history(revisions, options = {}, &block)
      options[:markup] = :markdown if !options[:markup] # target markup
      revisions.each_with_index do |page, index|
        # call debug output from outside
        block.call(page, index) if block_given?
        commit_revision(page, options[:markup])
      end
    end

def commit_history ( revisions , options = { } , & block ) options [ :markup ] = :markdown if ! options [ :markup ] revisions . each_with_index do | page , index | block . call ( page , index ) if block_given? commit_revision ( page , options [ :markup ] ) end end

Commit all revisions of the given history into this gollum-wiki-repository.

Commit all revisions of the given history into this gollum - wiki - repository .


def scan_spec(fmt_string)
      until fmt_string.empty?
        if (match_data = PARSE_REGEX.match(fmt_string))
          mid = match_data.to_s
          pre = match_data.pre_match

          @specs << FormatLiteral.new(pre) unless pre.empty?
          @specs << case
                    when match_data[:var] then FormatVariable.new(mid)
                    when match_data[:set] then FormatSet.new(mid)
                    when match_data[:rgx] then FormatRgx.new(mid)
                    when match_data[:per] then FormatLiteral.new("\%")
                    else fail "Impossible case in scan_spec."
                    end
          fmt_string = match_data.post_match
        else
          @specs << FormatLiteral.new(fmt_string)
          fmt_string = ""
        end
      end
    end

def
scan_spec
(
fmt_string
)
until
fmt_string
.
empty?
if
(
match_data
=
PARSE_REGEX
.
match
(
fmt_string
)
)
mid
=
match_data
.
to_s
pre
=
match_data
.
pre_match
@specs
<<
FormatLiteral
.
new
(
pre
)
unless
pre
.
empty?
@specs
<<
case
when
match_data
[
:var
]
then
FormatVariable
.
new
(
mid
)
when
match_data
[
:set
]
then
FormatSet
.
new
(
mid
)
when
match_data
[
:rgx
]
then
FormatRgx
.
new
(
mid
)
when
match_data
[
:per
]
then
FormatLiteral
.
new
(
"\%"
)
else
fail
"Impossible case in scan_spec."
end
fmt_string
=
match_data
.
post_match
else
@specs
<<
FormatLiteral
.
new
(
fmt_string
)
fmt_string
=
""
end
end
end

Scan the format string extracting literals and variables.

Scan the format string extracting literals and variables .


take an input stream and convert all wikka syntax to markdown syntax
 taken from 'trac_wiki_to_textile' at

take an input stream and convert all wikka syntax to markdown syntax taken from trac_wiki_to_textile at


def debug2(s, opts = {} )
    out = opts.fetch(:out, $stdout)
    tag = opts.fetch(:tag, '_DFLT_')
    really_write = opts.fetch(:really_write, true) # you can prevent ANY debug setting this to false
    write_always = opts.fetch(:write_always, false)

    raise "ERROR: ':tags' must be an array in debug(), maybe you meant to use :tag?" if ( opts[:tags] && opts[:tags].class != Array )
    final_str = "#RDeb#{write_always ? '!' : ''}[#{opts[:tag] || '-'}] #{s}"
    final_str = "\033[1;30m" +final_str + "\033[0m" if opts.fetch(:coloured_debug, true) # color by gray by default
    if (debug_tags_enabled? ) # tags
      puts( final_str ) if debug_tag_include?( opts )
    else # normal behaviour: if NOT tag
      puts( final_str ) if ((really_write && $DEBUG) || write_always) && ! opts[:tag]
    end
  end


def exec(command, options={}, &block)
      raise ConnectionClosed.new('Connection is closed.') unless @channel

      options = {
          on_non_zero_exit_code: :default
      }.merge(options || {})

      options[:on_non_zero_exit_code] = @options[:on_non_zero_exit_code] if options[:on_non_zero_exit_code] == :default

      push_buffer # store the current buffer and start a fresh buffer

      # buffer while also passing data to the supplied block.
      if block_given?
        buffer_input( &block )
      end

      # send the command and wait for the prompt to return.
      @channel.send_data command + "\n"
      wait_for_prompt

      # return buffering to normal.
      if block_given?
        buffer_input
      end

      # get the output from the command, minus the trailing prompt.
      ret = command_output(command)

      # restore the original buffer and merge the output from the command.
      pop_merge_buffer

      if @options[:retrieve_exit_code]
        # get the exit code for the command.
        push_buffer
        retrieve_command = 'echo $?'
        @channel.send_data retrieve_command + "\n"
        wait_for_prompt
        @last_exit_code = command_output(retrieve_command).strip.to_i
        # restore the original buffer and discard the output from this command.
        pop_discard_buffer

        # if we are expected to raise an error, do so.
        if options[:on_non_zero_exit_code] == :raise_error
          raise NonZeroExitCode.new("Exit code was #{@last_exit_code}.") unless @last_exit_code == 0
        end
      end

      ret
    end

def
exec
(
command
,
options
=
{
}
,
&
block
)
raise
ConnectionClosed
.
new
(
'Connection is closed.'
)
unless
@channel
options
=
{
on_non_zero_exit_code
:
:default
}
.
merge
(
options
||
{
}
)
options
[
:on_non_zero_exit_code
]
=
@options
[
:on_non_zero_exit_code
]
if
options
[
:on_non_zero_exit_code
]
==
:default
push_buffer
if
block_given?
buffer_input
(
&
block
)
end
@channel
.
send_data
command
+
"\n"
wait_for_prompt
if
block_given?
buffer_input
end
ret
=
command_output
(
command
)
pop_merge_buffer
if
@options
[
:retrieve_exit_code
]
push_buffer
retrieve_command
=
'echo $?'
@channel
.
send_data
retrieve_command
+
"\n"
wait_for_prompt
@last_exit_code
=
command_output
(
retrieve_command
)
.
strip
.
to_i
pop_discard_buffer
if
options
[
:on_non_zero_exit_code
]
==
:raise_error
raise
NonZeroExitCode
.
new
(
"Exit code was #{@last_exit_code}."
)
unless
@last_exit_code
==
0
end
end
ret
end

Executes a command during the shell session.

 If called outside of the +new+ block, this will raise an error.

 The +command+ is the command to execute in the shell.

 The +options+ parameter can include the following keys.
 *  The :on_non_zero_exit_code option can be :default, :ignore, or :raise_error.

 If provided, the +block+ is a chunk of code that will be processed every time the
 shell receives output from the program.  If the block returns a string, the string
 will be sent to the shell.  This can be used to monitor processes or monitor and
 interact with processes.  The +block+ is optional.

   shell.exec('sudo -p "password:" nginx restart') do |data,type|
     return 'super-secret' if /password:$/.match(data)
     nil
   end

Executes a command during the shell session .


def upload(local_file, remote_file)
      raise ConnectionClosed.new('Connection is closed.') unless @ssh
      sftp.upload!(local_file, remote_file)
    end

def
upload
(
local_file
,
remote_file
)
raise
ConnectionClosed
.
new
(
'Connection is closed.'
)
unless
@ssh
sftp
.
upload!
(
local_file
,
remote_file
)
end

Uses SFTP to upload a single file to the host.

Uses SFTP to upload a single file to the host .


def download(remote_file, local_file)
      raise ConnectionClosed.new('Connection is closed.') unless @ssh
      sftp.download!(remote_file, local_file)
    end

def
download
(
remote_file
,
local_file
)
raise
ConnectionClosed
.
new
(
'Connection is closed.'
)
unless
@ssh
sftp
.
download!
(
remote_file
,
local_file
)
end

Uses SFTP to download a single file from the host.

Uses SFTP to download a single file from the host .


def write_file(remote_file, data)
      raise ConnectionClosed.new('Connection is closed.') unless @ssh
      sftp.file.open(remote_file, 'w') do |f|
        f.write data
      end
    end

def
write_file
(
remote_file
,
data
)
raise
ConnectionClosed
.
new
(
'Connection is closed.'
)
unless
@ssh
sftp
.
file
.
open
(
remote_file
,
'w'
)
do
|
f
|
f
.
write
data
end
end

Uses SFTP to write data to a single file.

Uses SFTP to write data to a single file .


def distance(other)
			unless other.is_a? Point
				raise ArgumentError.new 'other must be a Point.'
			end

			dlng = GpsUtils::to_radians(other.lng - @lng)
			dlat = GpsUtils::to_radians(other.lat - @lat)

			x = dlng * Math.cos(dlat / 2)
			y = GpsUtils::to_radians(other.lat - @lat)

			Math.sqrt(x**2 + y**2) * GpsUtils::R
		end

def
distance
(
other
)
unless
other
.
is_a?
Point
raise
ArgumentError
.
new
'other must be a Point.'
end
dlng
=
GpsUtils
::
to_radians
(
other
.
lng
@lng
)
dlat
=
GpsUtils
::
to_radians
(
other
.
lat
@lat
)
x
=
dlng
*
Math
.
cos
(
dlat
/
2
)
y
=
GpsUtils
::
to_radians
(
other
.
lat
@lat
)
Math
.
sqrt
(
x
**
2
+
y
**
2
)
*
GpsUtils
::
R
end

Measure the distance between this point and another.

 Distance is calculated using equirectangular projection.
 @see https://en.wikipedia.org/wiki/Equirectangular_projection

 @param other [Point]
 @return [Float]
 @raise [ArgumentError] if other is not a Point

Measure the distance between this point and another .


def cover?(point)
			p = [point.lat - @nw.lat, point.lng - @se.lng]

			p21x = p[0] * @p21
			p41x = p[1] * @p41

			0 < p21x and p21x < @p21ms and 0 <= p41x and p41x <= @p41ms
		end

def cover? ( point ) p = [ point . lat - @nw . lat , point . lng - @se . lng ] p21x = p [ 0 ] * @p21 p41x = p [ 1 ] * @p41 0 < p21x and p21x < @p21ms and 0 <= p41x and p41x <= @p41ms end

Initialize BoundingBox.

 @param nw_point [Point] North-West corner
 @param se_point [Point] South-East corner
 Determine whether point is inside bounding box.

 @param point [Point]


def send(method, *args, &block)
      if respond_to?(method)
        super
      else
        subject.send(method, *args, &block)
      end
    end

def send ( method , * args , & block ) if respond_to? ( method ) super else subject . send ( method , * args , & block ) end end


def output(elapsed)
      case @result
      when MATCH_SUCCESS
        color = :green
        header = 'OK'
      when MATCH_FAILURE
        color = :red
        header = 'FAIL'
      when MATCH_WARNING
        color = :light_red
        header = 'WARN'
      end
      header = header.ljust(12).colorize(color)
      str_elapsed = "#{elapsed.round(2)}s"
      name = @name.to_s[0..17]
      puts "#{header}   #{name.ljust(20)}   #{str_elapsed.ljust(9)} #{@message}"
    end

Called to output the result to the console.
 @param elapsed the time running the command so far
 rubocop:disable MethodLength

Called to output the result to the console .


def get_userinfo(user)
      p = {}
      ids = []
      names = []

      if user.is_a?(Array)
        user.each do |u|
          names << u if u.is_a?(String)
          id << u if u.is_a?(Integer)
        end
      elsif user.is_a?(String)
        names << user
      elsif user.is_a?(Integer)
        ids << user
      else
        raise ArgumentError, format('Unknown type of arguments: %s', user.class)
      end

      result = get('ids' => ids, 'names' => names)

      result['users']
    end

def
get_userinfo
(
user
)
p
=
{
}
ids
=
[
]
names
=
[
]
if
user
.
is_a?
(
Array
)
user
.
each
do
|
u
|
names
<<
u
if
u
.
is_a?
(
String
)
id
<<
u
if
u
.
is_a?
(
Integer
)
end
elsif
user
.
is_a?
(
String
)
names
<<
user
elsif
user
.
is_a?
(
Integer
)
ids
<<
user
else
raise
ArgumentError
,
format
(
'Unknown type of arguments: %s'
,
user
.
class
)
end
result
=
get
(
'ids'
=>
ids
,
'names'
=>
names
)
result
[
'users'
]
end

def session
 rdoc

 ==== Bugzilla::User#get_userinfo(params)


def options &block
      options = Options.new
      options.instance_eval(&block)

      @options = options.to_hash
    end

def options & block options = Options . new options . instance_eval ( & block ) @options = options . to_hash end

define a DSL for options
 any string is processed as an option and it ends up in the
 @options hash


def column name, &block
      column = Column.new
      column.instance_eval(&block)

      @colspec << column.to_hash.merge({name: name})
    end

def column name , & block column = Column . new column . instance_eval ( & block ) @colspec << column . to_hash . merge ( { name : name } ) end

define a DSL for column specification
 - `name` is the name of the column
 - `block` contains two declarations, `process` and `check`, which are
   used, respectively, to make a cell into the desired data and to check
   whether the desired data is ok

define a DSL for column specification - name is the name of the column - block contains two declarations process and check which are used respectively to make a cell into the desired data and to check whether the desired data is ok


def bulk_declare hash, &block
      hash.keys.each do |key|
        column = Column.new
        column.colref hash[key]
        if block
          column.instance_eval(&block)
        end
        @colspec << column.to_hash.merge({name: key})
      end
    end

def bulk_declare hash , & block hash . keys . each do | key | column = Column . new column . colref hash [ key ] if block column . instance_eval ( & block ) end @colspec << column . to_hash . merge ( { name : key } ) end end

bulk declare columns we intend to read

 - hash is a hash in the form { symbolic_name: colref }

 i.bulk_declare {name: 'B', age: 'C'} is equivalent to:

 i.column :name do
   colref 'B'
 end
 i.column :age do
   colref 'C'
 end

 i.bulk_declare {name: 'B', age: 'C'} do
   process do |cell|
     cell.strip
   end
 end

 is equivalent to:

 i.column :name do
   colref 'B'
   process do |cell|
     cell.strip
   end
 end
 i.column :age do
   colref 'C'
   process do |cell|
     cell.strip
   end
 end


def read args = {}
      if args.class == Hash
        hash = @options.merge(args)
      else
        puts "dreader error at #{__callee__}: this function takes a Hash as input"
        exit
      end

      spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename])
      sheet = spreadsheet.sheet(hash[:sheet] || 0)

      @table = Array.new
      @errors = Array.new

      first_row = hash[:first_row] || 1
      last_row = hash[:last_row] || sheet.last_row

      (first_row..last_row).each do |row_number|
        r = Hash.new
        @colspec.each_with_index do |colspec, index|
          cell = sheet.cell(row_number, colspec[:colref])

          colname = colspec[:name]

          r[colname] = Hash.new
          r[colname][:row_number] = row_number
          r[colname][:col_number] = colspec[:colref]

          begin
            r[colname][:value] = value = colspec[:process] ? colspec[:process].call(cell) : cell
          rescue => e
            puts "dreader error at #{__callee__}: 'process' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})"
            raise e
          end

          begin
            if colspec[:check] and not colspec[:check].call(value) then
              r[colname][:error] = true
              @errors << "dreader error at #{__callee__}: value \"#{cell}\" for #{colname} at row #{row_number} (col #{index + 1}) does not pass the check function"
            else
              r[colname][:error] = false
            end
          rescue => e
            puts "dreader error at #{__callee__}: 'check' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})"
            raise e
          end
        end

        @table << r
      end

      @table
    end

read a file and store it internally

 @param hash, a hash, possibly overriding any of the parameters
              set in the initial options.  This allows you, for
              instance, to apply the same column specification to
              different files and different sheets

 @return the data read from filename, in the form of an array of
         hashes


def backtrace_lineno_for_config(file_path, exception)
      # For a SyntaxError, we really need to grep it from the
      # exception message, it really appears to be nowhere else. Ugh.
      if exception.kind_of? SyntaxError
        if m = /:(\d+):/.match(exception.message)
          return m[1].to_i
        end
      end

      # Otherwise we try to fish it out of the backtrace, first
      # line matching the config file path.

      # exception.backtrace_locations exists in MRI 2.1+, which makes
      # our task a lot easier. But not yet in JRuby 1.7.x, so we got to
      # handle the old way of having to parse the strings in backtrace too.
      if (exception.respond_to?(:backtrace_locations) &&
          exception.backtrace_locations &&
          exception.backtrace_locations.length > 0)
        location = exception.backtrace_locations.find do |bt|
          bt.path == file_path
        end
        return location ? location.lineno : nil
      else # have to parse string backtrace
        exception.backtrace.each do |line|
          if line.start_with?(file_path)
            if m = /\A.*\:(\d+)\:in/.match(line)
              return m[1].to_i
              break
            end
          end
        end
        # if we got here, we have nothing
        return nil
      end
    end

def backtrace_lineno_for_config ( file_path , exception ) if exception . kind_of? SyntaxError if m = / \d / . match ( exception . message ) return m [ 1 ] . to_i end end if ( exception . respond_to? ( :backtrace_locations ) && exception . backtrace_locations && exception . backtrace_locations . length > 0 ) location = exception . backtrace_locations . find do | bt | bt . path == file_path end return location ? location . lineno : nil else exception . backtrace . each do | line | if line . start_with? ( file_path ) if m = / \A \: \d \: / . match ( line ) return m [ 1 ] . to_i break end end end return nil end end

Provide a config source file path, and an exception.

 Returns the line number from the first line in the stack
 trace of the exception that matches your file path.
 of the first line in the backtrace matching that file_path.

 Returns `nil` if no suitable backtrace line can be found.

 Has special logic to try and grep the info out of a SyntaxError, bah.

Provide a config source file path and an exception .