def rate(nper, pmt, pv, fv = 0, end_or_beginning = 0, rate_guess = 0.10)
      guess = rate_guess
      tolerancy = 1e-6
      close = false

      begin
        temp = newton_iter(guess, nper, pmt, pv, fv, end_or_beginning)
        next_guess = (guess - temp).round(20)
        diff = (next_guess - guess).abs
        close = diff < tolerancy
        guess = next_guess
      end while !close

      next_guess
    end

def rate ( nper , pmt , pv , fv = 0 , end_or_beginning = 0 , rate_guess = 0.10 ) guess = rate_guess tolerancy = 1e-6 close = false begin temp = newton_iter ( guess , nper , pmt , pv , fv , end_or_beginning ) next_guess = ( guess - temp ) . round ( 20 ) diff = ( next_guess - guess ) . abs close = diff < tolerancy guess = next_guess end while ! close next_guess end

Calculates the interest rate of an annuity investment based on
 constant-amount periodic payments and the assumption of a constant interest rate.

 @param nper [Integer] The number of payments to be made (number of periods)
 @param pmt [Float] The amount per period to be paid
 @param pv [Float] The present value
 @param fv [Float] The future value remaining after the final payment has been made
 @param end_or_begining [Integer] Whether payments are due at the end (0) or
   beggining (1) of each period
 @param rate_guess [Float] An estimate for what the interest rate will be

 @return [Float]

 @example
   Exonio.rate(12, 363.78, -3056.00) # ==> 0.05963422268883278

Calculates the interest rate of an annuity investment based on constant - amount periodic payments and the assumption of a constant interest rate .


def npv(discount, cashflows)
      total = 0

      cashflows.each_with_index do |cashflow, index|
        total += (cashflow.to_f / (1 + discount.to_f) ** (index + 1))
      end

      total
    end

def npv ( discount , cashflows ) total = 0 cashflows . each_with_index do | cashflow , index | total += ( cashflow . to_f / ( 1 + discount . to_f ) ** ( index + 1 ) ) end total end

Calculates the net present value of an investment based on a
 series of periodic cash flows and a discount rate.

 @param discount [Float] The discount rate of the investment over one period
 @param cashflows [Array] The first future cash flow + additional future cash flows

 @return [Float]

 @example
   Exonio.npv(0.281, [-100, 39, 59, 55, 20]) # ==> -0.00661872883563408

Calculates the net present value of an investment based on a series of periodic cash flows and a discount rate .


def irr(values)
      func = Helpers::IrrHelper.new(values)
      guess = [ func.eps ]
      nlsolve( func, guess)
      guess[0]
    end

def irr ( values ) func = Helpers :: IrrHelper . new ( values ) guess = [ func . eps ] nlsolve ( func , guess ) guess [ 0 ] end

Calculates the internal rate of return on an investment based on a
 series of periodic cash flows.

 @param cashflows [Array] An array containing the income or payments
 associated with the investment

 @return [Float]

 @example
   Exonio.irr([-100, 39, 59, 55, 20]) # ==> 0.28094842116...

Calculates the internal rate of return on an investment based on a series of periodic cash flows .


This method was borrowed from the NumPy rate formula
 which was generated by Sage


def event_summary(trim_at = 100)
      summary = @event['check']['notification'] || @event['check']['description']
      if summary.nil?
        source = @event['check']['source'] || @event['client']['name']
        event_context = [source, @event['check']['name']].join('/')
        output = @event['check']['output'].chomp
        output = output.length > trim_at ? output[0..trim_at] + '...' : output
        summary = [event_context, output].join(' : ')
      end
      summary
    end

def
event_summary
(
trim_at
=
100
)
summary
=
@event
[
'check'
]
[
'notification'
]
||
@event
[
'check'
]
[
'description'
]
if
summary
.
nil?
source
=
@event
[
'check'
]
[
'source'
]
||
@event
[
'client'
]
[
'name'
]
event_context
=
[
source
,
@event
[
'check'
]
[
'name'
]
]
.
join
(
'/'
)
output
=
@event
[
'check'
]
[
'output'
]
.
chomp
output
=
output
.
length
>
trim_at
output
[
0
..
trim_at
]
+
'...'
:
output
summary
=
[
event_context
,
output
]
.
join
(
' : '
)
end
summary
end


def load
			# we always read 512 for the header block. if the block size ends up being different,
			# what happens to the 109 fat entries. are there more/less entries?
			@io.rewind
			header_block = @io.read 512
			@header = Header.new header_block

			# create an empty bbat.
			@bbat = AllocationTable::Big.new self
			bbat_chain = header_block[Header::SIZE..-1].unpack 'V*'
			mbat_block = @header.mbat_start
			@header.num_mbat.times do
				blocks = @bbat.read([mbat_block]).unpack 'V*'
				mbat_block = blocks.pop
				bbat_chain += blocks
			end
			# am i using num_bat in the right way?
			@bbat.load @bbat.read(bbat_chain[0, @header.num_bat])

			# get block chain for directories, read it, then split it into chunks and load the
			# directory entries. semantics changed - used to cut at first dir where dir.type == 0
			@dirents = @bbat.read(@header.dirent_start).to_enum(:each_chunk, Dirent::SIZE).
				map { |str| Dirent.new self, str }

			# now reorder from flat into a tree
			# links are stored in some kind of balanced binary tree
			# check that everything is visited at least, and at most once
			# similarly with the blocks of the file.
			# was thinking of moving this to Dirent.to_tree instead.
			class << @dirents
				def to_tree idx=0
					return [] if idx == Dirent::EOT
					d = self[idx]
					to_tree(d.child).each { |child| d << child }
					raise FormatError, "directory #{d.inspect} used twice" if d.idx
					d.idx = idx
					to_tree(d.prev) + [d] + to_tree(d.next)
				end
			end

			@root = @dirents.to_tree.first
			@dirents.reject! { |d| d.type_id == 0 }
			# silence this warning by default, its not really important (issue #5).
			# fairly common one appears to be "R" (from office OS X?) which smells
			# like some kind of UTF16 snafu, but scottwillson also has had some kanji...
			#Log.warn "root name was #{@root.name.inspect}" unless @root.name == 'Root Entry'
			unused = @dirents.reject(&:idx).length
			Log.warn "#{unused} unused directories" if unused > 0

			# FIXME i don't currently use @header.num_sbat which i should
			# hmm. nor do i write it. it means what exactly again?
			# which mode to use here?
			@sb_file = RangesIOResizeable.new @bbat, :first_block => @root.first_block, :size => @root.size
			@sbat = AllocationTable::Small.new self
			@sbat.load @bbat.read(@header.sbat_start)
		end

load document from file.

 TODO: implement various allocationtable checks, maybe as a AllocationTable#fsck function :)

 1. reterminate any chain not ending in EOC.
    compare file size with actually allocated blocks per file.
 2. pass through all chain heads looking for collisions, and making sure nothing points to them
    (ie they are really heads). in both sbat and mbat
 3. we know the locations of the bbat data, and mbat data. ensure that there are placeholder blocks
    in the bat for them.
 4. maybe a check of excess data. if there is data outside the bbat.truncate.length + 1 * block_size,
    (eg what is used for truncate in #flush), then maybe add some sort of message about that. it
    will be automatically thrown away at close time.


def repack temp=:file
			case temp
			when :file
				Tempfile.open 'ole-repack' do |io|
					io.binmode
					repack_using_io io
				end
			when :mem;  StringIO.open(''.dup, &method(:repack_using_io))
			else raise ArgumentError, "unknown temp backing #{temp.inspect}"
			end
		end

def
repack
temp
=
:file
case
temp
when
:file
Tempfile
.
open
'ole-repack'
do
|
io
|
io
.
binmode
repack_using_io
io
end
when
:mem
;
StringIO
.
open
(
''
.
dup
,
method
(
:repack_using_io
)
)
else
raise
ArgumentError
,
"unknown temp backing #{temp.inspect}"
end
end

could be useful with mis-behaving ole documents. or to just clean them up.

could be useful with mis - behaving ole documents . or to just clean them up .


def load_relation(relationship, position = nil)
      if objects = @resource.dig("_embedded", relationship)
        location = position ? objects[position] : objects
        begin
          WpApiClient::Collection.new(location)
        rescue WpApiClient::ErrorResponse
          load_from_links(relationship, position)
        end
      else
        load_from_links(relationship, position)
      end
    end

def load_relation ( relationship , position = nil ) if objects = @resource . dig ( "_embedded" , relationship ) location = position ? objects [ position ] : objects begin WpApiClient :: Collection . new ( location ) rescue WpApiClient :: ErrorResponse load_from_links ( relationship , position ) end else load_from_links ( relationship , position ) end end

try to load an embedded object; call out to the API if not

try to load an embedded object ; call out to the API if not


def native_representation_of(response_body)
      # Do we have a collection of objects?
      if response_body.is_a? Array
        WpApiClient::Collection.new(response_body, @headers)
      else
        WpApiClient::Entities::Base.build(response_body)
      end
    end

def
native_representation_of
(
response_body
)
# Do we have a collection of objects?
if
response_body
.
is_a?
Array
WpApiClient
::
Collection
.
new
(
response_body
,
@headers
)
else
WpApiClient
::
Entities
::
Base
.
build
(
response_body
)
end
end

Take the API response and figure out what it is


def call_func(method:, params: [], tx: {}) # rubocop:disable Naming/UncommunicativeMethodParamName
      data, output_types = function_data_with_ot(method, *params)
      resp = @rpc.call_rpc(:call, params: [tx.merge(data: data, to: address), "latest"])
      result = resp["result"]

      data = [Utils.remove_hex_prefix(result)].pack("H*")
      return if data.nil?

      re = decode_abi output_types, data
      re.length == 1 ? re.first : re
    end

call contract functions by rpc `call` method

 @param method [Symbol | String] the method name you call
 @param params [Array] the method params you call
 @param tx [Hash] see rpc `call` doc for more info

 @return [any]

call contract functions by rpc call method


def send_func(tx:, private_key:, method:, params: []) # rubocop:disable Naming/UncommunicativeMethodParamName
      data, _output_types = function_data_with_ot(method, *params)
      transaction = if tx.is_a?(Hash)
                      Transaction.from_hash(tx)
                    else
                      tx
                    end
      transaction.data = data
      resp = @rpc.send_transaction(transaction, private_key)

      resp&.dig("result")
    end

call contract functions by sendRawTransaction

 @param tx [Hash | CITA::Transaction]
 @param private_key [String] hex string
 @param method [Symbol | String] method name you call
 @param *params [Array] your params

 @return [nil | Hash] {hash: "", status: ""}, sendRawTransactionResult


def parse_url
      uri = URI.parse(@url)
      @host = uri.host
      @port = uri.port
      @scheme = uri.scheme
    end

def parse_url uri = URI . parse ( @url ) @host = uri . host @port = uri . port @scheme = uri . scheme end


def call_rpc(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)
      conn.post("/", rpc_params(method, jsonrpc: jsonrpc, params: params, id: id))
    end

def call_rpc ( method , jsonrpc : DEFAULT_JSONRPC , params : DEFAULT_PARAMS , id : DEFAULT_ID ) conn . post ( "/" , rpc_params ( method , jsonrpc : jsonrpc , params : params , id : id ) ) end

wrapper for call rpc method

 @param method [String] method you want to call
 @param jsonrpc [String] jsonrpc version
 @param params [Array] rpc params
 @param id [Integer] jsonrpc id

 @return [Faraday::Response]


def rpc_params(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)
      {
        jsonrpc: jsonrpc,
        id: id,
        method: method,
        params: params
      }.to_json
    end

def rpc_params ( method , jsonrpc : DEFAULT_JSONRPC , params : DEFAULT_PARAMS , id : DEFAULT_ID ) { jsonrpc : jsonrpc , id : id , method : method , params : params } . to_json end

wrapper for rpc params

 @param method [String] method you want to call
 @param jsonrpc [String] jsonrpc version
 @param params [Array] rpc params
 @param id [Integer] jsonrpc id

 @return [String] json string


def conn
      Faraday.new(url: url) do |faraday|
        faraday.headers["Content-Type"] = "application/json"
        faraday.request  :url_encoded # form-encode POST params
        faraday.adapter  Faraday.default_adapter # make requests with Net::HTTP
      end
    end

def
conn
Faraday
.
new
(
url
:
url
)
do
|
faraday
|
faraday
.
headers
[
"Content-Type"
]
=
"application/json"
faraday
.
request
:url_encoded
# form-encode POST params
faraday
.
adapter
Faraday
.
default_adapter
# make requests with Net::HTTP
end
end

wrapper faraday object with CITA URL and Content-Type

 @return [Faraday]

wrapper faraday object with CITA URL and Content - Type


def transfer(to:, private_key:, value:, quota: 30_000)
      valid_until_block = block_number["result"].hex + 88
      meta_data = get_meta_data("latest")["result"]
      version = meta_data["version"]
      chain_id = if version.zero?
                   meta_data["chainId"]
                 elsif version == 1
                   meta_data["chainIdV1"]
                 end
      transaction = Transaction.new(nonce: Utils.nonce, valid_until_block: valid_until_block, chain_id: chain_id, to: to, value: value, quota: quota, version: version)
      send_transaction(transaction, private_key)
    end

def transfer ( to : , private_key : , value : , quota : 30_000 ) valid_until_block = block_number [ "result" ] . hex + 88 meta_data = get_meta_data ( "latest" ) [ "result" ] version = meta_data [ "version" ] chain_id = if version . zero? meta_data [ "chainId" ] elsif version == 1 meta_data [ "chainIdV1" ] end transaction = Transaction . new ( nonce : Utils . nonce , valid_until_block : valid_until_block , chain_id : chain_id , to : to , value : value , quota : quota , version : version ) send_transaction ( transaction , private_key ) end

easy to transfer tokens

 @param to [String] to address
 @param private_key [String]
 @param value [String | Integer] hex string or decimal integer
 @param quota [Integer] default to 30_000

 @return [Hash]


def replace(new)
    if String === new
      @data.replace(JSON.parse(new))
    else
      @data.replace(new)
    end
  end

def replace ( new ) if String === new @data . replace ( JSON . parse ( new ) ) else @data . replace ( new ) end end

Replace the current storage with the given one.

 @param new [Hash, String] if new is a {String} it will be parsed as JSON

Replace the current storage with the given one .


def to_json
    io = StringIO.new("{")

    io << JSON.create_id.to_json << ":" << self.class.name.to_json << ","

    @data.each {|key, value|
      io << key.to_json.to_s << ":" << value.to_json << ","
    }

    io.seek(-1, IO::SEEK_CUR)
    io << "}"

    io.string
  end

def to_json io = StringIO . new ( "{" ) io << JSON . create_id . to_json << ":" << self . class . name . to_json << "," @data . each { | key , value | io << key . to_json . to_s << ":" << value . to_json << "," } io . seek ( - 1 , IO :: SEEK_CUR ) io << "}" io . string end

Convert the storage to JSON.

 @return [String] the JSON representation


def time(label, &block)
    raise ArgumentError, "no block given" unless block

    `#@native.time(label)`

    begin
      if block.arity == 0
        instance_exec(&block)
      else
        block.call(self)
      end
    ensure
      `#@native.timeEnd()`
    end
  end

def
time
(
label
,
&
block
)
raise
ArgumentError
,
"no block given"
unless
block
`
`
begin
if
block
.
arity
==
0
instance_exec
(
block
)
else
block
.
call
(
self
)
end
ensure
`
`
end
end

Time the given block with the given label.

Time the given block with the given label .


def group(*args, &block)
    raise ArgumentError, "no block given" unless block

    `#@native.group.apply(#@native, args)`

    begin
      if block.arity == 0
        instance_exec(&block)
      else
        block.call(self)
      end
    ensure
      `#@native.groupEnd()`
    end
  end

def
group
(
*
args
,
&
block
)
raise
ArgumentError
,
"no block given"
unless
block
`
`
begin
if
block
.
arity
==
0
instance_exec
(
block
)
else
block
.
call
(
self
)
end
ensure
`
`
end
end


def group!(*args, &block)
    return unless block_given?

    `#@native.groupCollapsed.apply(#@native, args)`

    begin
      if block.arity == 0
        instance_exec(&block)
      else
        block.call(self)
      end
    ensure
      `#@native.groupEnd()`
    end
  end

def group! ( * args , & block ) return unless block_given? ` ` begin if block . arity == 0 instance_exec ( block ) else block . call ( self ) end ensure ` ` end end


def authenticate!
      options = authentication_handler.call(self, @options)
      @options.merge!(options)
      client.config.soap_header = soap_headers
    end

def authenticate! options = authentication_handler . call ( self , @options ) @options . merge! ( options ) client . config . soap_header = soap_headers end

Internal Calls the authentication handler, which should set @options to a new
 hash.

Internal Calls the authentication handler which should set


def new_with_uuid(klass, uuid)
      if klass.is_a?(String)
        klass = Object.const_get(klass)
      end
      object = klass.new(self, uuid)
      object.initialize_defaults
      object
    end

def new_with_uuid ( klass , uuid ) if klass . is_a? ( String ) klass = Object . const_get ( klass ) end object = klass . new ( self , uuid ) object . initialize_defaults object end

Creates a new object with given UUID.

 @param [String] uuid UUID of the object.


def new_reference_with_uuid(path, uuid, source_tree = :group)
      # customize `FileReferencesFactory.new_file_reference`
      path = Pathname.new(path)
      ref = self.project.new_with_uuid(PBXFileReference, uuid)
      self.children << ref
      GroupableHelper.set_path_with_source_tree(ref, path, source_tree)
      ref.set_last_known_file_type

      # customize `FileReferencesFactory.configure_defaults_for_file_reference`
      if ref.path.include?('/')
        ref.name = ref.path.split('/').last
      end
      if File.extname(ref.path).downcase == '.framework'
        ref.include_in_index = nil
      end

      ref
    end

Creates a file reference with given UUID.

 @param [String] uuid UUID of the object.

Creates a file reference with given UUID .


def add_file_reference_with_uuid(file_ref, uuid, avoid_duplicates = false)
      if avoid_duplicates && existing = build_file(file_ref)
        existing
      else
        build_file = project.new_with_uuid(PBXBuildFile, uuid)
        build_file.file_ref = file_ref
        files.insert(0, build_file)
        build_file
      end
    end

def add_file_reference_with_uuid ( file_ref , uuid , avoid_duplicates = false ) if avoid_duplicates && existing = build_file ( file_ref ) existing else build_file = project . new_with_uuid ( PBXBuildFile , uuid ) build_file . file_ref = file_ref files . insert ( 0 , build_file ) build_file end end

Adds the file reference with given UUID.

 @param [String] uuid UUID of the object.

Adds the file reference with given UUID .


def remove_seeds
      removings = self.locks.keys - self.seeds.keys
      removings.each do |name|
        say "Removing #{name} (#{self.locks[name].version})".red
        dirname = File.join(self.root_path, "Seeds", name)
        FileUtils.rm_rf(dirname)
      end
    end

Removes disused seeds.

 @!visibility private


def configure_phase
      self.project.targets.each do |target|
        begin
          phase = target.sources_build_phase
          # support resources phase
          resource_phase = target.resources_build_phase
          next unless phase
        rescue NoMethodError
          next
        end

        # remove zombie build files
        phase.files_references.each do |file|
          begin
            file.real_path
          rescue
            phase.files.each do |build_file|
              phase.files.delete(build_file) if build_file.file_ref == file
            end
          end
        end

        resource_phase.files_references.each do |file|
          begin
            file.real_path
          rescue
            resource_phase.files.each do |build_file|
              resource_phase.files.delete(build_file) if build_file.file_ref == file
            end
          end
        end

        removings = [] # name of seeds going to be removed from the target
        addings = [] # name of seeds going to be added to the target

        self.targets.keys.sort.each do |seed_name|
          target_names = self.targets[seed_name]
          if not target_names.include?(target.name)
            removings << seed_name if not removings.include?(seed_name)
          else
            addings << seed_name if not addings.include?(seed_name)
          end
        end

        self.file_references.each do |file|
          removings.each do |seed_names|
            next if not seed_names.include?(file.parent.name)
            phase.files.each do |build_file|
              phase.files.delete(build_file) if build_file.file_ref == file
            end
            resource_phase.files.each do |build_file|
              resource_phase.files.delete(build_file) if build_file.file_ref == file
            end
          end

          addings.each do |seed_names|
            next if file.name.end_with? ".h"
            next if not seed_names.include?(file.parent.name)
            uuid = Xcodeproj::uuid_with_name "#{target.name}:#{file.name}"
            # Treat a file as resource file unless confirm it can be compiled.
            if self.valid_source_file?(file)
              phase.add_file_reference_with_uuid(file, uuid, true)
            else
              resource_phase.add_file_reference_with_uuid(file, uuid, true)
            end

          end
        end
      end
    end

Adds file references to the 'Sources Build Phase'.

 @!visibility private

Adds file references to the Sources Build Phase .


def valid_source_file? filename
      suffixs = [".h", ".c", ".m", ".mm", ".swift", ".cpp"]
      suffixs.each do |suffix|
        return true if filename.name.end_with? suffix
      end
      return false
    end

def valid_source_file? filename suffixs = [ ".h" , ".c" , ".m" , ".mm" , ".swift" , ".cpp" ] suffixs . each do | suffix | return true if filename . name . end_with? suffix end return false end

Determines whether there's a source file.

 @!visibility private

Determines whether there s a source file .


def speller
      return @speller if @speller
      # raspell is an optional dependency, handle the missing case nicely
      begin
        require "raspell"
      rescue LoadError
        $stderr.puts "ERROR: Ruby gem \"raspell\" is not installed."
        exit 1
      end

      # initialize aspell
      @speller = Aspell.new("en_US")
      @speller.suggestion_mode = Aspell::NORMAL
      # ignore the HTML tags in the text
      @speller.set_option("mode", "html")

      @speller
    end

create an Aspell speller object
 @return [Aspell] the speller object


def files_to_check
      files = config["check"].reduce([]) { |a, e| a + Dir[e] }
      config["ignore"].reduce(files) { |a, e| a - Dir[e] }
    end

def files_to_check files = config [ "check" ] . reduce ( [ ] ) { | a , e | a + Dir [ e ] } config [ "ignore" ] . reduce ( files ) { | a , e | a - Dir [ e ] } end

evaluate the files to check
 @return [Array<String>] list of files


def read_spell_config(file)
      return {} unless File.exist?(file)

      puts "Loading config file (#{file})..." if verbose == true
      require "yaml"
      YAML.load_file(file)
    end

def
read_spell_config
(
file
)
return
{
}
unless
File
.
exist?
(
file
)
puts
"Loading config file (#{file})..."
if
verbose
==
true
require
"yaml"
YAML
.
load_file
(
file
)
end


def report_duplicates(dict1, dict2)
      duplicates = dict1 & dict2
      return if duplicates.empty?

      $stderr.puts "Warning: Found dictionary duplicates in the local dictionary " \
        "(#{CUSTOM_SPELL_CONFIG_FILE}):\n"
      duplicates.each { |duplicate| $stderr.puts "  #{duplicate}" }
      $stderr.puts
    end

print the duplicate dictionary entries
 @param dict1 [Array<String>] the first dictionary
 @param dict2 [Array<String>] the second dictionary


def config
      return @config if @config

      @config = read_spell_config(GLOBAL_SPELL_CONFIG_FILE)
      custom_config = read_spell_config(CUSTOM_SPELL_CONFIG_FILE)

      report_duplicates(config["dictionary"], custom_config["dictionary"].to_a)

      custom_config["dictionary"] = @config["dictionary"] + custom_config["dictionary"].to_a
      custom_config["dictionary"].uniq!

      # override the global values by the local if present
      @config.merge!(custom_config)

      @config
    end

return the merged global and the custom spell configs
 @return [Hash] the merged configuration to use


def check_file(file)
      puts "Checking #{file}..." if verbose == true
      # spell check each line separately so we can report error locations properly
      lines = File.read(file).split("\n")

      success = true
      lines.each_with_index do |text, index|
        misspelled = misspelled_on_line(text)
        next if misspelled.empty?

        success = false
        print_misspelled(misspelled, index, text)
      end

      success
    end

check the file using the spellchecker
 @param file [String] file name
 @return [Boolean] true on success (no spelling error found)


def check_writable(path)
      raise Error, "'#{path}' is not writable" if path.exist? && !path.writable? || !path.parent.writable?
    end

def
check_writable
(
path
)
raise
Error
,
"'#{path}' is not writable"
if
path
.
exist?
&&
!
path
.
writable?
||
!
path
.
parent
.
writable?
end

If the path does not exist, it will check for the parent
 directory write permission

 @param [ Pathname ] path

If the path does not exist it will check for the parent directory write permission


def check_option(opt)
      raise Error, "The option is not an OptBase, #{opt.class} supplied" unless opt.is_a?(OptBase)
      raise Error, "The option #{opt.to_sym} is already used !" if @symbols_used.include?(opt.to_sym)
    end

Ensures the opt given is valid

 @param [ OptBase ] opt

 @return [ void ]


def post_processing
      @opts.each do |opt|
        raise NoRequiredOption, "The option #{opt} is required" if opt.required? && !@results.key?(opt.to_sym)

        next if opt.required_unless.empty? || @results.key?(opt.to_sym)

        fail_msg = "One of the following options is required: #{opt}, #{opt.required_unless.join(', ')}"

        raise NoRequiredOption, fail_msg unless opt.required_unless.any? do |sym|
          @results.key?(sym)
        end
      end
    end

Ensure that all required options are supplied
 Should be overriden to modify the behavior

 @return [ Void ]


def subdir_entities(dir = @current_dir)
      Dir.glob(dir[:path].gsub(/[*?\\\[\]{}]/, '\\\\\0') + '/*').map!{|path| {path: path, time: File.mtime(path), name: File.basename(path)}}
    end

def subdir_entities ( dir = @current_dir ) Dir . glob ( dir [ :path ] . gsub ( / \\ \[ \] / , '\\\\\0' ) + '/*' ) . map! { | path | { path : path , time : File . mtime ( path ) , name : File . basename ( path ) } } end

Conversions
 Get entities of files in dir


def string_to_bytes(str)
      unless @e.nil? || @e == :utf8
        if @e == :shift_jis
          begin
            str = str.gsub /[\\:*?"<>|\uff5e]/, '？'
            str.encode! 'Shift_JIS', :invalid => :replace, :undef => :replace, :replace => '？'
          rescue => e
          end
        end
      end
      [str].pack('a*')
    end

def string_to_bytes ( str ) unless @e . nil? || @e == :utf8 if @e == :shift_jis begin str = str . gsub / \\ \uff5e / , '？' str . encode! 'Shift_JIS' , :invalid => :replace , :undef => :replace , :replace => '？' rescue => e end end end [ str ] . pack ( 'a*' ) end

Create ASCII-8bits string. Also convert encoding if needed.

Create ASCII - 8bits string . Also convert encoding if needed .


def pack(files)
      entities = Entity.entities_from files
      return if entities.empty?

      reset_state
      pack_entities entities
      while has_dir?
        cd next_dir
        pack_current_dir
      end
    end

def pack ( files ) entities = Entity . entities_from files return if entities . empty? reset_state pack_entities entities while has_dir? cd next_dir pack_current_dir end end

Compression operations
 Pack file and directory entities and output to stream.

Compression operations Pack file and directory entities and output to stream .


def pack_symlinks
      reset_state
      @l.each do |link|
        if @w.path_exists? Entity.linked_path(link[:abs_path], File.readlink(link[:path]))
          link[:name] = link[:abs_path]
          pack_symbolic_link_entity link
        end
      end
    end

def pack_symlinks reset_state @l . each do | link | if @w . path_exists? Entity . linked_path ( link [ :abs_path ] , File . readlink ( link [ :path ] ) ) link [ :name ] = link [ :abs_path ] pack_symbolic_link_entity link end end end

Pack symlinks if its link path exists in zip


def pack_entities(entities)
      entities.each do |entity|
        # ignore bad entities
        next unless entity.is_a?(Hash) && entity[:path]

        path = entity[:path]
        if File.symlink? path
          postpone_symlink entity
        elsif File.directory? path
          postpone_dir entity
        elsif File.file? path
          pack_file_entity entity
        end
      end
    end

def
pack_entities
(
entities
)
entities
.
each
do
|
entity
|
# ignore bad entities
next
unless
entity
.
is_a?
(
Hash
)
&&
entity
[
:path
]
path
=
entity
[
:path
]
if
File
.
symlink?
path
postpone_symlink
entity
elsif
File
.
directory?
path
postpone_dir
entity
elsif
File
.
file?
path
pack_file_entity
entity
end
end
end

Pack file entities. Directory entities are queued, not packed in this method.

Pack file entities . Directory entities are queued not packed in this method .


def header content = nil, options = nil, html_options = nil, &block
      @header = UiBibz::Ui::Core::Lists::Components::ListHeader.new content, options, html_options, &block
    end

def header content = nil , options = nil , html_options = nil , & block @header = UiBibz :: Ui :: Core :: Lists :: Components :: ListHeader . new content , options , html_options , block end


def body content = nil, options = nil, html_options = nil, &block
      @body = UiBibz::Ui::Core::Lists::Components::ListBody.new content, options, html_options, &block
    end

def body content = nil , options = nil , html_options = nil , & block @body = UiBibz :: Ui :: Core :: Lists :: Components :: ListBody . new content , options , html_options , block end


def td_content record, col
      content = col.count ? record.send(col.data_index).count : record.send(col.data_index)
      unless content.nil?
        content = content.strftime(col.date_format)                    unless col.date_format.nil?
        content = link_to content, action.inject_url(col.link, record) unless col.link.nil?
        content = col.format.call(@store.records, record)              unless col.format.nil?
      end
      content = As.new(col, record, content, @options).render unless col.as.nil?
      content
    end

def td_content record , col content = col . count ? record . send ( col . data_index ) . count : record . send ( col . data_index ) unless content . nil? content = content . strftime ( col . date_format ) unless col . date_format . nil? content = link_to content , action . inject_url ( col . link , record ) unless col . link . nil? content = col . format . call ( @store . records , record ) unless col . format . nil? end content = As . new ( col , record , content , @options ) . render unless col . as . nil? content end


def body content = nil, options = nil, html_options = nil, &block
      options, content = inherit_options(content, options, block)
      if is_tap(content, options)
        content = (content || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )
        @items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options).tap(&block).render
      else
        options = (options || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )
        @items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options, &block).render
      end
    end

def body content = nil , options = nil , html_options = nil , & block options , content = inherit_options ( content , options , block ) if is_tap ( content , options ) content = ( content || { } ) . merge ( collapse : options . try ( :[] , :collapse ) , parent_collapse : @options [ :parent_collapse ] ) @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardBody . new ( content , options , html_options ) . tap ( block ) . render else options = ( options || { } ) . merge ( collapse : options . try ( :[] , :collapse ) , parent_collapse : @options [ :parent_collapse ] ) @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardBody . new ( content , options , html_options , block ) . render end end


def footer content = nil, options = nil, html_options = nil, &block
      options, content = inherit_options(content, options, block)
      @footer = UiBibz::Ui::Core::Boxes::Components::CardFooter.new(content, options, html_options, &block).render
    end

def footer content = nil , options = nil , html_options = nil , & block options , content = inherit_options ( content , options , block ) @footer = UiBibz :: Ui :: Core :: Boxes :: Components :: CardFooter . new ( content , options , html_options , block ) . render end


def list_group content = nil, options = nil, html_options = nil, &block
      @items << UiBibz::Ui::Core::Boxes::Components::CardListGroup.new(content, options, html_options).tap(&block).render
    end

def list_group content = nil , options = nil , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardListGroup . new ( content , options , html_options ) . tap ( block ) . render end


def image content = nil, options = nil, html_options = nil, &block
      @items << UiBibz::Ui::Core::Boxes::Components::CardImage.new(content, options, html_options, &block).render
    end

def image content = nil , options = nil , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Boxes :: Components :: CardImage . new ( content , options , html_options , block ) . render end


def html content = nil, &block
      if !block.nil?
        context  = eval("self", block.binding)
        @items << context.capture(&block)
      else
        @items << content
      end
    end

def html content = nil , & block if ! block . nil? context = eval ( "self" , block . binding ) @items << context . capture ( block ) else @items << content end end


def component_html_options
      super.merge({
        multiple:      options[:multiple],
        disabled:      options[:state] == :disabled,
        include_blank: options[:include_blank],
        prompt:        options[:prompt]
      })
    end

def component_html_options super . merge ( { multiple : options [ :multiple ] , disabled : options [ :state ] == :disabled , include_blank : options [ :include_blank ] , prompt : options [ :prompt ] } ) end


def nav content = nil, options = {}, html_options = nil, &block
      @items << UiBibz::Ui::Core::Component.new(Nav.new(content, options).tap(&block).render, {}, html_options)
    end

def nav content = nil , options = { } , html_options = nil , & block @items << UiBibz :: Ui :: Core :: Component . new ( Nav . new ( content , options ) . tap ( block ) . render , { } , html_options ) end


def body content = nil, options = nil, html_options = nil, &block
      @body = UiBibz::Ui::Core::Notifications::Components::AlertBody.new(content, options, html_options, &block).render
    end

def body content = nil , options = nil , html_options = nil , & block @body = UiBibz :: Ui :: Core :: Notifications :: Components :: AlertBody . new ( content , options , html_options , block ) . render end


def is_tap content, options
      (content[:tap] if content.kind_of?(Hash)) || (options[:tap] unless options.nil?)
    end

def is_tap content , options ( content [ :tap ] if content . kind_of? ( Hash ) ) || ( options [ :tap ] unless options . nil? ) end


def component_html_data
      # To stimulusjs
      data_target = html_options.try(:[], :data).try(:[], :target) || options.try(:delete, :target)
      add_html_data(:target, data_target) unless data_target.nil?

      data_controller = html_options.try(:[], :data).try(:[], :controller) || options.try(:delete, :controller)
      add_html_data(:controller, data_controller) unless data_controller.nil?

      data_action = html_options.try(:[], :data).try(:[], :action) || options.try(:delete, :action)
      add_html_data(:action, data_action) unless data_action.nil?

      # To turbolinks
      data_turbolinks = html_options.try(:[], :data).try(:[], :turbolinks) || options.try(:delete, :turbolinks)
      add_html_data(:turbolinks, data_turbolinks) unless data_turbolinks.nil?
    end

def
component_html_data
# To stimulusjs
data_target
=
html_options
.
try
(
:[]
,
:data
)
.
try
(
:[]
,
:target
)
||
options
.
try
(
:delete
,
:target
)
add_html_data
(
:target
,
data_target
)
unless
data_target
.
nil?
data_controller
=
html_options
.
try
(
:[]
,
:data
)
.
try
(
:[]
,
:controller
)
||
options
.
try
(
:delete
,
:controller
)
add_html_data
(
:controller
,
data_controller
)
unless
data_controller
.
nil?
data_action
=
html_options
.
try
(
:[]
,
:data
)
.
try
(
:[]
,
:action
)
||
options
.
try
(
:delete
,
:action
)
add_html_data
(
:action
,
data_action
)
unless
data_action
.
nil?
# To turbolinks
data_turbolinks
=
html_options
.
try
(
:[]
,
:data
)
.
try
(
:[]
,
:turbolinks
)
||
options
.
try
(
:delete
,
:turbolinks
)
add_html_data
(
:turbolinks
,
data_turbolinks
)
unless
data_turbolinks
.
nil?
end


def add_html_data name, value = true
      html_options[:data] = {} if html_options[:data].nil?
      value = value.kind_of?(String) ? value.strip : value
      html_options[:data].update(Hash[name, value])
    end

def add_html_data name , value = true html_options [ :data ] = { } if html_options [ :data ] . nil? value = value . kind_of? ( String ) ? value . strip : value html_options [ :data ] . update ( Hash [ name , value ] ) end


def header column, name = nil
      @column  = column
      defaults = [translate_headers_by_defaults, translate_headers_by_defaults_active_record, translate_headers_by_active_record, header_name(name)]
      @name    = UiBibz::Utils::Internationalization.new(translate_headers_by_model, default: defaults).translate
      sortable? ? sortable_link : title
    end


def column data_index = nil, options = nil, html_options = nil, &block
      @columns << Column.new(data_index, options, html_options, &block)
    end

def column data_index = nil , options = nil , html_options = nil , & block @columns << Column . new ( data_index , options , html_options , block ) end


def link content = nil, options = nil, html_options = nil, &block
      @actions << UiBibz::Ui::Core::Forms::Dropdowns::Components::DropdownLink.new(content, options, html_options, &block).render
    end

def link content = nil , options = nil , html_options = nil , & block @actions << UiBibz :: Ui :: Core :: Forms :: Dropdowns :: Components :: DropdownLink . new ( content , options , html_options , block ) . render end


def engine_scaffold
      FileUtils.mkdir_p(@gem_temp)
      Dir.chdir(@gem_temp) do
        response = Open3.capture3("rails plugin new #{gem} --mountable --dummy-path=site --skip-test-unit")
        if !response[1].empty?
          puts response[1]
          abort "FAILED: Please be sure you have the rails gem installed with `gem install rails`"
        end

        # Remove files and directories that are unnecessary for the
        # light-weight Rails documentation site
        remove = %w(mailers models assets channels jobs views).map{ |f| File.join('app', f) }
        remove.concat %w(cable.yml storage.yml database.yml).map{ |f| File.join('config', f) }

        remove.each { |f| FileUtils.rm_rf File.join(@gem, 'site', f), secure: true }
      end

      engine_copy
    end

Create an Rails plugin engine for documentation site


def engine_copy
      site_path = File.join path, 'site'
      FileUtils.mkdir_p site_path

      ## Copy Rails plugin files
      Dir.chdir "#{@gem_temp}/#{gem}/site" do
        %w(app config bin config.ru Rakefile public log).each do |item|
          target = File.join site_path, item

          FileUtils.cp_r item, target

          action_log "create", target.sub(@cwd+'/','')
        end

      end

      # Remove temp dir
      FileUtils.rm_rf @gem_temp
    end

def
engine_copy
site_path
=
File
.
join
path
,
'site'
FileUtils
.
mkdir_p
site_path
## Copy Rails plugin files
Dir
.
chdir
"#{@gem_temp}/#{gem}/site"
do
%w(
app
config
bin
config.ru
Rakefile
public
log
)
.
each
do
|
item
|
target
=
File
.
join
site_path
,
item
FileUtils
.
cp_r
item
,
target
action_log
"create"
,
target
.
sub
(
@cwd
+
'/'
,
''
)
end
end
# Remove temp dir
FileUtils
.
rm_rf
@gem_temp
end

Copy parts of the engine scaffold into site directory


def make_map(item)
      '(' + item.map {|key, value| key.to_s + ':' + convert_to_sass_value(value) }.join(',') + ')'
    end

def make_map ( item ) '(' + item . map { | key , value | key . to_s + ':' + convert_to_sass_value ( value ) } . join ( ',' ) + ')' end


def add_files(klass)
      ext = asset_ext klass
      find_files(ext).map do |path|
        klass.new(self, path)
      end
    end

def add_files ( klass ) ext = asset_ext klass find_files ( ext ) . map do | path | klass . new ( self , path ) end end

Find files based on class type and
 return an array of Classes for each file


def find_files(ext)
      files = Dir[File.join(paths[ext.to_sym], asset_glob(ext))]

      # Filter out partials
      files.reject { |f| File.basename(f).start_with?('_') }
    end

def
find_files
(
ext
)
files
=
Dir
[
File
.
join
(
paths
[
ext
.
to_sym
]
,
asset_glob
(
ext
)
)
]
# Filter out partials
files
.
reject
{
|
f
|
File
.
basename
(
f
)
.
start_with?
(
'_'
)
}
end


def dispatch(command, *args)
      @threads = []
      send command, *args
      @threads.each { |thr| thr.join }
    end

def dispatch ( command , * args ) @threads = [ ] send command , args @threads . each { | thr | thr . join } end


def watch(options={})
      build(options)
      require 'listen'

      trap("SIGINT") {
        puts "\nspark_engine watcher stopped. Have a nice day!"
        exit!
      }

      @threads.concat SparkEngine.load_plugin.watch(options)
    end


def load_setup( name )
    reader = create_fixture_reader( name )

    reader.each do |fixture_name|
      load( fixture_name )
    end
  end

def load_setup ( name ) reader = create_fixture_reader ( name ) reader . each do | fixture_name | load ( fixture_name ) end end

lets us use match_teams_for_country etc.

lets us use match_teams_for_country etc .


def avoid_duplicate_image_names(content)

      nodes = content.xpath("//draw:frame[@draw:name]")

      nodes.each_with_index do |node, i|
        node.attribute('name').value = "pic_#{i}"
      end

    end

def avoid_duplicate_image_names ( content ) nodes = content . xpath ( "//draw:frame[@draw:name]" ) nodes . each_with_index do | node , i | node . attribute ( 'name' ) . value = "pic_#{i}" end end

replace_images
 newer versions of LibreOffice can't open files with duplicates image names

replace_images newer versions of LibreOffice can t open files with duplicates image names


def scope_params
        return {} if dynamic_scaffold.scope.nil?

        case dynamic_scaffold.scope
        when Array then
          dynamic_scaffold.scope.each_with_object({}) do |val, res|
            if val.is_a? Hash
              val.each {|k, v| res[k] = v }
            else
              res[val] = params[val]
            end
          end
        when Hash then
          dynamic_scaffold.scope
        end
      end

def scope_params return { } if dynamic_scaffold . scope . nil? case dynamic_scaffold . scope when Array then dynamic_scaffold . scope . each_with_object ( { } ) do | val , res | if val . is_a? Hash val . each { | k , v | res [ k ] = v } else res [ val ] = params [ val ] end end when Hash then dynamic_scaffold . scope end end

Get the hash of the key and value specified for the scope.

Get the hash of the key and value specified for the scope .


def pkey_string_to_hash(pkey)
        # https://github.com/gomo/dynamic_scaffold/pull/9/commits/ff5de0e38b3544347e82539c45ffd2efaf3410da
        # Stop support multiple pkey, on this commit.
        # Convert "key:1,code:foo" to {key: "1", code: "foo"}
        pkey.split(',').map {|v| v.split(':') }.each_with_object({}) {|v, res| res[v.first] = v.last }
      end


def update_values # rubocop:disable Metrics/AbcSize
        # set the parameters of carrierwave_image at the end for validates.
        permitting = []
        dynamic_scaffold.form.items.reject {|i| i.type?(:carrierwave_image) }.each do |item|
          item.extract_parameters(permitting)
        end
        permitting.concat(dynamic_scaffold.form.permit_params)
        dynamic_scaffold.form.items.select {|i| i.type?(:carrierwave_image) }.each do |item|
          item.extract_parameters(permitting)
        end

        values = params
                   .require(dynamic_scaffold.model.name.underscore)
                   .permit(*permitting)

        if dynamic_scaffold.scope && !valid_for_scope?(values)
          raise DynamicScaffold::Error::InvalidOperation, "You can update only to #{scope_params} on this scope"
        end

        values
      end


def valid_for_scope?(update_params)
        return true if dynamic_scaffold.scope_options[:changeable]

        result = true
        scope_params.each do |key, value|
          if update_params.key?(key) && update_params[key] != value
            result = false
            break
          end
        end
        result
      end

def valid_for_scope? ( update_params ) return true if dynamic_scaffold . scope_options [ :changeable ] result = true scope_params . each do | key , value | if update_params . key? ( key ) && update_params [ key ] != value result = false break end end result end

Check if there are inconsistent scopes in update parameters


def lock(timeout: nil, &block)
      ensure_exists_and_release_stale_locks!

      success = @redis.with do |conn|
        if timeout
          !conn.blpop(available_key, timeout.to_i).nil?
        else
          !conn.lpop(available_key).nil?
        end
      end

      return false unless success

      token = SecureRandom.hex(16)
      @tokens.push(token)
      @redis.with do |conn|
        conn.zadd(grabbed_key, epoch_f(conn), token)
      end

      return_or_yield(token, &block)
    end

def lock ( timeout : nil , & block ) ensure_exists_and_release_stale_locks! success = @redis . with do | conn | if timeout ! conn . blpop ( available_key , timeout . to_i ) . nil? else ! conn . lpop ( available_key ) . nil? end end return false unless success token = SecureRandom . hex ( 16 ) @tokens . push ( token ) @redis . with do | conn | conn . zadd ( grabbed_key , epoch_f ( conn ) , token ) end return_or_yield ( token , block ) end

Acquire a resource from the semaphore, if available. Returns false if no
 resources are available.

 `timeout` is how long to wait, blocking, until a resource is available.
 The default is nil, meaning don't block. A timeout of zero means block forever.
 (This is a bit weird, but corresponds to how blpop uses timeout values.)

 If passed a block, if a resource is available, runs the block and then
 unlocks.

 If called without a block, if a resource is available, returns a token.
 Caller is then responsible for unlocking the token.

 This isn't atomic--if the process dies, we could remove something from the
 available queue without adding it to the grabbed set--but that's ok, the
 semaphore will recover just as if this was a stale client that left its
 token in the grabbed set forever.

Acquire a resource from the semaphore if available . Returns false if no resources are available .


def unlock(token = @tokens.pop)
      return unless token

      removed = false

      @redis.with do |conn|
        removed = conn.zrem grabbed_key, token
        if removed
          conn.lpush available_key, 1
        end
      end

      removed
    end

def unlock ( token = @tokens . pop ) return unless token removed = false @redis . with do | conn | removed = conn . zrem grabbed_key , token if removed conn . lpush available_key , 1 end end removed end

Release a resource back to the semaphore. Should normally be called with an
 explicit token.

 This isn't atomic--if the process dies, we could remove something from the
 blocked set without adding it to the available queue--but that's ok, the
 semaphore will recover just as if this was a stale client that left its
 token in the grabbed set forever.

Release a resource back to the semaphore . Should normally be called with an explicit token .


def apply_options(options={})
      options.each { |key, value| send("#{key}=", value) if respond_to?(key) }
      yield(self) if block_given?
    end

def apply_options ( options = { } ) options . each { | key , value | send ( "#{key}=" , value ) if respond_to? ( key ) } yield ( self ) if block_given? end

Creates a notification object.

 @see Libnotify.new


def show!
      notify_init(app_name) or raise "notify_init failed"
      raw_ptr = notify_notification_new(summary, body, icon_path, nil)
      @notification = ::FFI::AutoPointer.new(raw_ptr, method(:g_object_unref))
      show
    end

def
show!
notify_init
(
app_name
)
or
raise
"notify_init failed"
raw_ptr
=
notify_notification_new
(
summary
,
body
,
icon_path
,
)
@notification
=
::
FFI
::
AutoPointer
.
new
(
raw_ptr
,
method
(
:g_object_unref
)
)
show
end

Shows a new notification.

 @see Libnotify.show


def update(options={}, &block)
      apply_options(options, &block)
      if @notification
        notify_notification_update(@notification, summary, body, icon_path, nil)
        show
      else
        show!
      end
    end

def update ( options = { } , & block ) apply_options ( options , block ) if @notification notify_notification_update ( @notification , summary , body , icon_path , nil ) show else show! end end

Updates a previously shown notification or creates a new one.

Updates a previously shown notification or creates a new one .


def download
      raise ArgumentError.new('url cannot be nil') if @url.nil?
      raise ArgumentError.new('url cannot be empty') if @url.empty?

      set_information_from_json(YoutubeDL::Runner.new(url, runner_options).run)
    end

def
download
raise
ArgumentError
.
new
(
'url cannot be nil'
)
if
@url
.
nil?
raise
ArgumentError
.
new
(
'url cannot be empty'
)
if
@url
.
empty?
set_information_from_json
(
YoutubeDL
::
Runner
.
new
(
url
,
runner_options
)
.
run
)
end

Instantiate new model

 @param url [String] URL to initialize with
 @param options [Hash] Options to populate the everything with
 Download the video.


def method_missing(method, *args, &block)
      value = information[method]

      if value.nil?
        super
      else
        value
      end
    end

def method_missing ( method , * args , & block ) value = information [ method ] if value . nil? super else value end end

Redirect methods for information getting

 @param method [Symbol] method name
 @param args [Array] method arguments
 @param block [Proc] explict block
 @return [Object] The value from @information


def options_to_commands
      commands = []
      @options.sanitize_keys.each_paramized_key do |key, paramized_key|
        if @options[key].to_s == 'true'
          commands.push "--#{paramized_key}"
        elsif @options[key].to_s == 'false'
          commands.push "--no-#{paramized_key}"
        else
          commands.push "--#{paramized_key} :#{key}"
        end
      end
      commands.push quoted(url)
      commands.join(' ')
    end

def
options_to_commands
commands
=
[
]
@options
.
sanitize_keys
.
each_paramized_key
do
|
key
,
paramized_key
|
if
@options
[
key
]
.
to_s
==
'true'
commands
.
push
"--#{paramized_key}"
elsif
@options
[
key
]
.
to_s
==
'false'
commands
.
push
"--no-#{paramized_key}"
else
commands
.
push
"--#{paramized_key} :#{key}"
end
end
commands
.
push
quoted
(
url
)
commands
.
join
(
' '
)
end

Parses options and converts them to Cocaine's syntax

 @return [String] commands ready to do cocaine

Parses options and converts them to Cocaine s syntax


def with(hash)
      merged = Options.new(@store.merge(hash.to_h))
      merged.banned_keys = @banned_keys
      merged.send(:remove_banned)
      merged
    end

def with ( hash ) merged = Options . new ( @store . merge ( hash . to_h ) ) merged . banned_keys = @banned_keys merged . send ( :remove_banned ) merged end

Merge options with given hash, removing banned keys, and returning a
 new instance of Options.

 @param hash [Hash] Hash to merge options with
 @return [YoutubeDL::Options] Merged Options instance

Merge options with given hash removing banned keys and returning a new instance of Options .


def method_missing(method, *args, &_block)
      remove_banned
      if method.to_s.include? '='
        method = method.to_s.tr('=', '').to_sym
        return nil if banned? method
        @store[method] = args.first
      else
        return nil if banned? method
        @store[method]
      end
    end

def method_missing ( method , * args , & _block ) remove_banned if method . to_s . include? '=' method = method . to_s . tr ( '=' , '' ) . to_sym return nil if banned? method @store [ method ] = args . first else return nil if banned? method @store [ method ] end end

Option getting and setting using ghost methods

 @param method [Symbol] method name
 @param args [Array] list of arguments passed
 @param block [Proc] implicit block given
 @return [Object] the value of method in the options store


def manipulate_keys!(&block)
      @store.keys.each do |old_name|
        new_name = block.call(old_name)
        unless new_name == old_name
          @store[new_name] = @store[old_name]
          @store.delete(old_name)
        end
      end
    end

def manipulate_keys! ( & block ) @store . keys . each do | old_name | new_name = block . call ( old_name ) unless new_name == old_name @store [ new_name ] = @store [ old_name ] @store . delete ( old_name ) end end end

Calls a block to do operations on keys
 See sanitize_keys! for examples

 @param block [Proc] Block with operations on keys
 @yieldparam key [Object] Original key
 @yieldreturn [Object] Manipulated key


def sanitize_keys!
      # Symbolize
      manipulate_keys! { |key_name| key_name.is_a?(Symbol) ? key_name : key_name.to_sym }

      # Underscoreize (because Cocaine doesn't like hyphens)
      manipulate_keys! { |key_name| key_name.to_s.tr('-', '_').to_sym }
    end

Symbolizes and sanitizes keys in the option store

 @return [Object] @store


def representer_for(format, model, options={})
      options.delete(:represent_with) || self.class.represents_options.for(format, model, controller_path)
    end

def representer_for ( format , model , options = { } ) options . delete ( :represent_with ) || self . class . represents_options . for ( format , model , controller_path ) end

Central entry-point for finding the appropriate representer.

Central entry - point for finding the appropriate representer .


def variable_text_field(x, y, params = {})
      x = 0 unless numeric?(x)
      y = 0 unless numeric?(y)
      options = { height: 0.1, width: 0.1 }.merge!(params)

      # update the variable field count
      self.variable_fields_count += 1

      label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +
                      Integer(y * printer_dpi).to_s)

      if params[:orientation] == :landscape
        label_data.push('^A0N,')
      else
        label_data.push('^A0B,')
      end

      label_data.push(Integer(options[:height] * printer_dpi).to_s + ',' +
                      Integer(options[:width] * printer_dpi).to_s +
                       '^FN' + variable_fields_count.to_s + '^FS')

      # return unless label_height > 0 && label_width > 0
      # pdf.text_box '{Variable Field ' + variable_fields_count.to_s + '}',
      #              at: [Integer(x * pdf_dpi), Integer(label_width * pdf_dpi) -
      #              Integer(y * pdf_dpi) -
      #              Integer(options[:height] / 10) * pdf_dpi],
      #              size: Integer(options[:height] * pdf_dpi) if label_height &&
      #              label_width
    end

Called when the new method is invoked
 Sets a variable field that can be recalled


def home_position(x, y)
      x = 0 unless numeric?(x)
      y = 0 unless numeric?(y)
      label_data.push('^LH' + x.to_s + ',' + y.to_s)
    end

def home_position ( x , y ) x = 0 unless numeric? ( x ) y = 0 unless numeric? ( y ) label_data . push ( '^LH' + x . to_s + ',' + y . to_s ) end

Set the home position of the label
 All other X and Y coordinates are
 relative to this


def draw_border(x, y, height, width)
      return unless numeric?(height) && numeric?(width)
      x = 0 unless numeric?(x)
      y = 0 unless numeric?(y)

      label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +
                      Integer(y * printer_dpi).to_s + '^GB' +
                      Integer(height * printer_dpi).to_s +
                      ',' + Integer(width * printer_dpi).to_s + ',1^FS')

      # draw_rectangle(x * pdf_dpi, y * pdf_dpi, height * pdf_dpi, width * pdf_dpi)
    end


def reset_barcode_fields_to_default
      label_data.push('^BY' + Integer(self.barcode_default_module_width).to_s + ',' +
                      Float(self.barcode_default_width_ratio).to_s + ',' +
                      Integer(self.barcode_default_height).to_s)
    end

def reset_barcode_fields_to_default label_data . push ( '^BY' + Integer ( self . barcode_default_module_width ) . to_s + ',' + Float ( self . barcode_default_width_ratio ) . to_s + ',' + Integer ( self . barcode_default_height ) . to_s ) end

Some barcodes, such as QR codes may change document defaults.  These may be reset
 to the document defaults.

Some barcodes such as QR codes may change document defaults . These may be reset to the document defaults .


def draw_bar_code_39(bar_code_string, x, y, height)
      return unless label_height > 0 && label_width > 0
      pdf.bounding_box [x, Integer(label_width) - y - (height * pdf_dpi)],
                       width: (height * pdf_dpi) do
        barcode = Barby::Code39.new(bar_code_string)
        barcode.annotate_pdf(pdf, height: (height * pdf_dpi))
      end
    end

def draw_bar_code_39 ( bar_code_string , x , y , height ) return unless label_height > 0 && label_width > 0 pdf . bounding_box [ x , Integer ( label_width ) - y - ( height * pdf_dpi ) ] , width : ( height * pdf_dpi ) do barcode = Barby :: Code39 . new ( bar_code_string ) barcode . annotate_pdf ( pdf , height : ( height * pdf_dpi ) ) end end


def add_field(value)
      return if value.nil?
      return if value.strip.empty?

      # Increment the variable field count
      self.variable_fields_count += 1

      # Add the field
      label_data.push('^FN' + variable_fields_count.to_s +
                      '^FD' + value + '^FS')
    end

def
add_field
(
value
)
return
if
value
.
nil?
return
if
value
.
strip
.
empty?
# Increment the variable field count
self
.
variable_fields_count
+=
1
# Add the field
label_data
.
push
(
'^FN'
+
variable_fields_count
.
to_s
+
'^FD'
+
value
+
'^FS'
)
end

Called when the new method is invoked
 Adds a variable that is to be applied to the saved template


def build_slug
      if localized?
        begin
          orig_locale = I18n.locale
          all_locales.each do |target_locale|
            I18n.locale = target_locale
            apply_slug
          end
        ensure
          I18n.locale = orig_locale
        end
      else
        apply_slug
      end
      true
    end

def build_slug if localized? begin orig_locale = I18n . locale all_locales . each do | target_locale | I18n . locale = target_locale apply_slug end ensure I18n . locale = orig_locale end else apply_slug end true end


def new_with_slugs?
      if localized?
        # We need to check if slugs are present for the locale without falling back
        # to a default
        new_record? && _slugs_translations.fetch(I18n.locale.to_s, []).any?
      else
        new_record? && _slugs.present?
      end
    end

Returns true if object is a new record and slugs are present


def persisted_with_slug_changes?
      if localized?
        changes = _slugs_change
        return (persisted? && false) if changes.nil?

        # ensure we check for changes only between the same locale
        original = changes.first.try(:fetch, I18n.locale.to_s, nil)
        compare = changes.last.try(:fetch, I18n.locale.to_s, nil)
        persisted? && original != compare
      else
        persisted? && _slugs_changed?
      end
    end

Returns true if object has been persisted and has changes in the slug


def distance_of_time_in_words(from_time, to_time=Time.now)
      from_time = from_time.to_time if from_time.respond_to?(:to_time)
      to_time = to_time.to_time if to_time.respond_to?(:to_time)
      seconds = (to_time - from_time).round
      distance_in_days = (seconds/(60*60*24)).round
      seconds = seconds % (60*60*24)
      distance_in_hours = (seconds/(60*60)).round
      seconds = seconds % (60*60)
      distance_in_minutes = (seconds/60).round
      seconds = seconds % 60
      distance_in_seconds = seconds

      s = ''
      s << "#{distance_in_days} days," if distance_in_days > 0
      s << "#{distance_in_hours} hours, " if distance_in_hours > 0
      s << "#{distance_in_minutes} minutes, " if distance_in_minutes > 0
      s << "#{distance_in_seconds} seconds"
      s
    end

def
distance_of_time_in_words
(
from_time
,
to_time
=
Time
.
now
)
from_time
=
from_time
.
to_time
if
from_time
.
respond_to?
(
:to_time
)
to_time
=
to_time
.
to_time
if
to_time
.
respond_to?
(
:to_time
)
seconds
=
(
to_time
from_time
)
.
round
distance_in_days
=
(
seconds
/
(
60
*
60
*
24
)
)
.
round
seconds
=
seconds
%
(
60
*
60
*
24
)
distance_in_hours
=
(
seconds
/
(
60
*
60
)
)
.
round
seconds
=
seconds
%
(
60
*
60
)
distance_in_minutes
=
(
seconds
/
60
)
.
round
seconds
=
seconds
%
60
distance_in_seconds
=
seconds
s
=
''
s
<<
"#{distance_in_days} days,"
if
distance_in_days
>
0
s
<<
"#{distance_in_hours} hours, "
if
distance_in_hours
>
0
s
<<
"#{distance_in_minutes} minutes, "
if
distance_in_minutes
>
0
s
<<
"#{distance_in_seconds} seconds"
s
end

Return the distance of time in words from the given from_time to the specified to_time. If to_time
 is not specified then Time.now is used. By default seconds are included...set the include_seconds
 argument to false to disable the seconds.

Return the distance of time in words from the given from_time to the specified to_time . If to_time is not specified then Time . now is used . By default seconds are included ... set the include_seconds argument to false to disable the seconds .


def approximate_distance_of_time_in_words(from_time, to_time=Time.now, include_seconds=true)
      from_time = from_time.to_time if from_time.respond_to?(:to_time)
      to_time = to_time.to_time if to_time.respond_to?(:to_time)
      distance_in_minutes = (((to_time - from_time).abs)/60).round
      distance_in_seconds = ((to_time - from_time).abs).round

      case distance_in_minutes
        when 0..1
          return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds
        case distance_in_seconds
          when 0..4   then 'less than 5 seconds'
          when 5..9   then 'less than 10 seconds'
          when 10..19 then 'less than 20 seconds'
          when 20..39 then 'half a minute'
          when 40..59 then 'less than a minute'
          else             '1 minute'
        end
        when 2..44           then "#{distance_in_minutes} minutes"
        when 45..89          then 'about 1 hour'
        when 90..1439        then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
        when 1440..2879      then '1 day'
        when 2880..43199     then "#{(distance_in_minutes / 1440).round} days"
        when 43200..86399    then 'about 1 month'
        when 86400..525959   then "#{(distance_in_minutes / 43200).round} months"
        when 525960..1051919 then 'about 1 year'
        else                      "over #{(distance_in_minutes / 525960).round} years"
      end
    end

Get the approximate disntance of time in words from the given from_time
 to the the given to_time. If to_time is not specified then it is set
 to Time.now. By default seconds are included...set the include_seconds
 argument to false to disable the seconds.

Get the approximate disntance of time in words from the given from_time to the the given to_time . If to_time is not specified then it is set to Time . now . By default seconds are included ... set the include_seconds argument to false to disable the seconds .


def track_error(control, msg)
      errors << msg
      control.error_handlers.each do |handler|
        handler.call(msg)
      end
    end

def track_error ( control , msg ) errors << msg control . error_handlers . each do | handler | handler . call ( msg ) end end

First attempt at centralizing error notifications


def process_batch(batch)
      batch = ETL::Batch::Batch.resolve(batch, self)
      say "Processing batch #{batch.file}"

      ETL::Engine.batch = ETL::Execution::Batch.create!(
        :batch_file => batch.file,
        :status => 'executing'
      )

      batch.execute

      ETL::Engine.batch.completed_at = Time.now
      ETL::Engine.batch.status = (errors.length > 0 ? 'completed with errors' : 'completed')
      ETL::Engine.batch.save!
    end

def
process_batch
(
batch
)
batch
=
ETL
::
Batch
::
Batch
.
resolve
(
batch
,
self
)
say
"Processing batch #{batch.file}"
ETL
::
Engine
.
batch
=
ETL
::
Execution
::
Batch
.
create!
(
:batch_file
=>
batch
.
file
,
:status
=>
'executing'
)
batch
.
execute
ETL
::
Engine
.
batch
.
completed_at
=
Time
.
now
ETL
::
Engine
.
batch
.
status
=
(
errors
.
length
>
0
'completed with errors'
:
'completed'
)
ETL
::
Engine
.
batch
.
save!
end


def pre_process(control)
      Engine.logger.debug "Pre-processing #{control.file}"
      control.pre_processors.each do |processor|
        processor.process
      end
      Engine.logger.debug "Pre-processing complete"
    end

def
pre_process
(
control
)
Engine
.
logger
.
debug
"Pre-processing #{control.file}"
control
.
pre_processors
.
each
do
|
processor
|
processor
.
process
end
Engine
.
logger
.
debug
"Pre-processing complete"
end


def post_process(control)
      say_on_own_line "Executing post processes"
      Engine.logger.debug "Post-processing #{control.file}"
      control.post_processors.each do |processor|
        processor.process
      end
      Engine.logger.debug "Post-processing complete"
      say "Post-processing complete"
    end

def
post_process
(
control
)
say_on_own_line
"Executing post processes"
Engine
.
logger
.
debug
"Post-processing #{control.file}"
control
.
post_processors
.
each
do
|
processor
|
processor
.
process
end
Engine
.
logger
.
debug
"Post-processing complete"
say
"Post-processing complete"
end


def execute_dependencies(control)
      Engine.logger.debug "Executing dependencies"
      control.dependencies.flatten.each do |dependency|
        case dependency
        when Symbol
          f = dependency.to_s + '.ctl'
          Engine.logger.debug "Executing dependency: #{f}"
          say "Executing dependency: #{f}"
          process(f)
        when String
          Engine.logger.debug "Executing dependency: #{f}"
          say "Executing dependency: #{f}"
          process(dependency)
        else
          raise "Invalid dependency type: #{dependency.class}"
        end
      end
    end


def execute_screens(control, timing = :before_post_process)
      screens = case timing
        when :after_post_process
          control.after_post_process_screens
        else # default to before post-process screens
          control.screens
        end
      [:fatal,:error,:warn].each do |type|
        screens[type].each do |block|
          begin
            block.call
          rescue => e
            case type
            when :fatal
              raise FatalScreenError, e
            when :error
              raise ScreenError, e
            when :warn
              say "Screen warning: #{e}"
            end
          end
        end
      end
    end


def redis_key *fields
      @redis_key_config = fields.flatten

      validate_redis_key

      #own specification of redis key - delete autoincrement
      remove_redis_autoincrement_key unless redis_user_field_config.include?(:id) || @redis_key_config.include?(:id)

      # automaticaly add all fields from key to validation
      # if any of fields in redis key is nil
      # then prevent to save it
      @redis_key_config.each do |field|
        validates field, :presence => :true if field != :id
      end
    end

set redis key which will be used for storing model


def redis_key_normalize *metrics
      @redis_key_normalize_conf ||= []
      metrics.each do |metric|
        raise ArgumentError, "Please provide valid normalization: #{VALID_NORMALIZATIONS.join(", ")}" unless VALID_NORMALIZATIONS.include?(metric)
        @redis_key_normalize_conf << metric
      end
    end


def redis_alias name, main_fields, name_of_field_for_order = nil, name_of_field_for_args = nil
      #set fields if they are not allready set!
      if name_of_field_for_order && name_of_field_for_args
        redis_field name_of_field_for_order, :array, [] unless redis_fields_config.has_key?(name_of_field_for_order)
        redis_field name_of_field_for_args, :hash, {} unless redis_fields_config.has_key?(name_of_field_for_args)
      end

      @redis_alias_config ||= {}
      #add specification of dynamic alias
      @redis_alias_config[name] = {
        main_fields: main_fields,
        order_field: name_of_field_for_order,
        args_field: name_of_field_for_args,
      }

      #create alias methods for find and get (find_by_name, get_by_name)
      create_class_alias_method(name)
    end


def store_redis_keys
      args = to_arg
      #store main key
      redis_old_keys[:key] = self.class.generate_key(args) #store main key

      #store alias keys
      redis_old_keys[:aliases] = []
      redis_alias_config.each do |alias_name, fields|
        redis_old_keys[:aliases] << redis_alias_key(alias_name) if valid_alias_key? alias_name
      end
    end

def
store_redis_keys
args
=
to_arg
#store main key
redis_old_keys
[
:key
]
=
self
.
class
.
generate_key
(
args
)
#store main key
#store alias keys
redis_old_keys
[
:aliases
]
=
[
]
redis_alias_config
.
each
do
|
alias_name
,
fields
|
redis_old_keys
[
:aliases
]
<<
redis_alias_key
(
alias_name
)
if
valid_alias_key?
alias_name
end
end


def conf
      fields = {}
      redis_fields_config.each do |key, type|
        fields[key] = TYPE_TRANSLATIONS[type] if TYPE_TRANSLATIONS.has_key?(type)
      end
      {
        fields: fields,
        required: @required_config.sort,
        redis_key: redis_key_config,
        redis_aliases: redis_alias_config.inject({}){|o,(k,v)| o[k] = v[:main_fields]; o},
        reject_nil_values: !redis_save_fields_with_nil_conf,
      }
    end

def conf fields = { } redis_fields_config . each do | key , type | fields [ key ] = TYPE_TRANSLATIONS [ type ] if TYPE_TRANSLATIONS . has_key? ( type ) end { fields : fields , required : @required_config . sort , redis_key : redis_key_config , redis_aliases : redis_alias_config . inject ( { } ) { | o , ( k , v ) | o [ k ] = v [ :main_fields ] ; o } , reject_nil_values : ! redis_save_fields_with_nil_conf , } end


def exists? args = {}
      RedisModelExtension::Database.redis.exists(self.name.constantize.generate_key(args))
    end

def exists? args = { } RedisModelExtension :: Database . redis . exists ( self . name . constantize . generate_key ( args ) ) end


def alias_exists? alias_name, args = {}
      RedisModelExtension::Database.redis.exists(self.name.constantize.generate_alias_key(alias_name, args))
    end

def alias_exists? alias_name , args = { } RedisModelExtension :: Database . redis . exists ( self . name . constantize . generate_alias_key ( alias_name , args ) ) end

Check if key by alias name and arguments exists in db


def valid_item_for_redis_key? args, key
      (args.has_key?(key) && !args[key].nil?) || redis_fields_config[key] == :autoincrement
    end

def valid_item_for_redis_key? args , key ( args . has_key? ( key ) && ! args [ key ] . nil? ) || redis_fields_config [ key ] == :autoincrement end


def validate_redis_key
      valid_fields = redis_fields_config.select{|k,v| v != :array && v != :hash  }.keys
      bad_fields = redis_key_config - valid_fields
      raise ArgumentError, "Sorry, but you cannot use as redis key [nonexisting | array | hash] fields: [#{bad_fields.join(",")}], availible are: #{valid_fields.join(", ")}" unless bad_fields.size == 0
    end

look for bad cofiguration in redis key and raise argument error


def to_arg
      redis_fields_config.inject({}) do |args, (key, type)|
        args[key] = self.send(key)
        args
      end
    end

def to_arg redis_fields_config . inject ( { } ) do | args , ( key , type ) | args [ key ] = self . send ( key ) args end end


def find_by_alias(alias_name, args = {})
      #check if asked dynamic alias exists
      raise ArgumentError, "Unknown dynamic alias: '#{alias_name}', use: #{redis_alias_config.keys.join(", ")} " unless redis_alias_config.has_key?(alias_name.to_sym)

      #normalize input hash of arguments
      args = HashWithIndifferentAccess.new(args)

      out = []
      klass = self.name.constantize
      search_key = klass.generate_alias_key(alias_name, args)
      #is key specified directly? -> no needs of looking for other keys! -> faster
      unless search_key =~ /\*/
        out = klass.get_by_alias(alias_name, args) if klass.alias_exists?(alias_name, args)
      else
        RedisModelExtension::Database.redis.keys(search_key).each do |key|
          out << klass.get_by_alias_key(key)
        end
      end
      out.flatten
    end


def get(args = {})
      # when argument is integer - search by id
      args = { id: args } if args.is_a?(Integer)

      #normalize input hash of arguments
      args = HashWithIndifferentAccess.new(args)

      klass = self.name.constantize
      if klass.valid_key?(args) && klass.exists?(args)
        klass.new_by_key(klass.generate_key(args))
      else
        nil
      end
    end

GET BY ARGUMENTS

fastest method to get object from redis by getting it by arguments
 * args (Integer) - search by id
 * args (Hash) - search by arguments in redis_key


def get_by_alias_key(alias_key)
      klass = self.name.constantize
      if RedisModelExtension::Database.redis.exists(alias_key)
        out = []
        RedisModelExtension::Database.redis.smembers(alias_key).each do |key|
          item = klass.new_by_key(key)
          out << item if item
        end
        return out
      end
      nil
    end

def get_by_alias_key ( alias_key ) klass = self . name . constantize if RedisModelExtension :: Database . redis . exists ( alias_key ) out = [ ] RedisModelExtension :: Database . redis . smembers ( alias_key ) . each do | key | item = klass . new_by_key ( key ) out << item if item end return out end nil end

fastest method to get object from redis by getting it by alias and arguments


def new_by_key(key)
      args = RedisModelExtension::Database.redis.hgetall(key)
      return nil unless args && args.any?
      args.symbolize_keys!

      new_instance = new(args)
      new_instance.store_keys

      return new_instance
    end

def new_by_key ( key ) args = RedisModelExtension :: Database . redis . hgetall ( key ) return nil unless args && args . any? args . symbolize_keys! new_instance = new ( args ) new_instance . store_keys return new_instance end

CREATE NEW OBJECT BY HASH VALUES

 read all data from redis and create new instance (used for Find & Get method)


def value_to_redis name, value
      if redis_fields_config.has_key?(name)
        value_transform value, redis_fields_config[name]
      else
        value
      end
    end

def value_to_redis name , value if redis_fields_config . has_key? ( name ) value_transform value , redis_fields_config [ name ] else value end end

choose right type of value and then transform it for redis


def value_transform value, type
      return nil if value.nil? || value.to_s.size == 0
      case type
      when :integer then value.to_i
      when :autoincrement then value.to_i
      when :string then value.to_s
      when :float then value.to_f
      when :bool then value.to_s
      when :symbol then value.to_s
      when :marshal then Marshal.dump(value)
      when :array then Yajl::Encoder.encode(value)
      when :hash then Yajl::Encoder.encode(value)
      when :time then Time.parse(value.to_s).strftime("%Y.%m.%d %H:%M:%S")
      when :date then Date.parse(value.to_s).strftime("%Y-%m-%d")
      else value
      end
    end

def
value_transform
value
,
type
return
if
value
.
nil?
||
value
.
to_s
.
size
==
0
case
type
when
:integer
then
value
.
to_i
when
:autoincrement
then
value
.
to_i
when
:string
then
value
.
to_s
when
:float
then
value
.
to_f
when
:bool
then
value
.
to_s
when
:symbol
then
value
.
to_s
when
:marshal
then
Marshal
.
dump
(
value
)
when
:array
then
Yajl
::
Encoder
.
encode
(
value
)
when
:hash
then
Yajl
::
Encoder
.
encode
(
value
)
when
:time
then
Time
.
parse
(
value
.
to_s
)
.
strftime
(
"%Y.%m.%d %H:%M:%S"
)
when
:date
then
Date
.
parse
(
value
.
to_s
)
.
strftime
(
"%Y-%m-%d"
)
else
value
end
end

convert value for valid format which can be saved in redis


def value_parse value, type
      return nil if value.nil? || value.to_s.size == 0
      case type
      when :integer then value.to_i
      when :autoincrement then value.to_i
      when :string then value.to_s
      when :float then value.to_f
      when :bool then value.to_s.to_bool
      when :symbol then value.to_s.to_sym
      when :marshal then value.is_a?(String) ? Marshal.load(value) : value
      when :array then value.is_a?(String) ? Yajl::Parser.parse(value) : value
      when :hash then value.is_a?(String) ? Hashr.new(Yajl::Parser.parse(value)) : Hashr.new(value)
      when :time then value.is_a?(String) ? Time.parse(value) : value
      when :date then value.is_a?(String) ? Date.parse(value) : value
      else value
      end
    end

def value_parse value , type return nil if value . nil? || value . to_s . size == 0 case type when :integer then value . to_i when :autoincrement then value . to_i when :string then value . to_s when :float then value . to_f when :bool then value . to_s . to_bool when :symbol then value . to_s . to_sym when :marshal then value . is_a? ( String ) ? Marshal . load ( value ) : value when :array then value . is_a? ( String ) ? Yajl :: Parser . parse ( value ) : value when :hash then value . is_a? ( String ) ? Hashr . new ( Yajl :: Parser . parse ( value ) ) : Hashr . new ( value ) when :time then value . is_a? ( String ) ? Time . parse ( value ) : value when :date then value . is_a? ( String ) ? Date . parse ( value ) : value else value end end

convert value from redis into valid format in ruby


def update args
      args.each do |key, value|
        method = "#{key}=".to_sym
        if self.respond_to? method
          self.send(method, value)
        end
      end
    end

def update args args . each do | key , value | method = "#{key}=" . to_sym if self . respond_to? method self . send ( method , value ) end end end


def destroy_aliases!
      #do it only if it is existing object!
      if redis_old_keys[:aliases].size > 0
        redis_old_keys[:aliases].each do |alias_key|
          RedisModelExtension::Database.redis.srem alias_key, redis_old_keys[:key]
          #delete alias with 0 keys
          RedisModelExtension::Database.redis.del(alias_key) if RedisModelExtension::Database.redis.scard(alias_key).to_i == 0
        end
      end
    end

def
destroy_aliases!
#do it only if it is existing object!
if
redis_old_keys
[
:aliases
]
.
size
>
0
redis_old_keys
[
:aliases
]
.
each
do
|
alias_key
|
RedisModelExtension
::
Database
.
redis
.
srem
alias_key
,
redis_old_keys
[
:key
]
#delete alias with 0 keys
RedisModelExtension
::
Database
.
redis
.
del
(
alias_key
)
if
RedisModelExtension
::
Database
.
redis
.
scard
(
alias_key
)
.
to_i
==
0
end
end
end


def add(username, token)
      Firim::AccountManager.new(
        user: username,
        token: token
      ).add_to_keychain
    end

def add ( username , token ) Firim :: AccountManager . new ( user : username , token : token ) . add_to_keychain end


def get_nsqds(lookupd, topic = nil)
      uri_scheme = 'http://' unless lookupd.match(%r(https?://))
      uri = URI.parse("#{uri_scheme}#{lookupd}")

      uri.query = "ts=#{Time.now.to_i}"
      if topic
        uri.path = '/lookup'
        uri.query += "&topic=#{URI.escape(topic)}"
      else
        uri.path = '/nodes'
      end

      begin
        body = Net::HTTP.get(uri)
        data = JSON.parse(body)
        producers = data['producers'] || # v1.0.0-compat
                      (data['data'] && data['data']['producers'])

        if producers
          producers.map do |producer|
            "#{producer['broadcast_address']}:#{producer['tcp_port']}"
          end
        else
          []
        end
      rescue Exception => e
        error "Error during discovery for #{lookupd}: #{e}"
        nil
      end
    end

Returns an array of nsqd addresses
 If there's an error, return nil

Returns an array of nsqd addresses If there s an error return nil


def discover_repeatedly(opts = {})
      @discovery_thread = Thread.new do

        @discovery = Discovery.new(opts[:nsqlookupds])

        loop do
          begin
            nsqds = nsqds_from_lookupd(opts[:topic])
            drop_and_add_connections(nsqds)
          rescue DiscoveryException
            # We can't connect to any nsqlookupds. That's okay, we'll just
            # leave our current nsqd connections alone and try again later.
            warn 'Could not connect to any nsqlookupd instances in discovery loop'
          end
          sleep opts[:interval]
        end

      end

      @discovery_thread.abort_on_exception = true
    end

discovers nsqds from an nsqlookupd repeatedly

   opts:
     nsqlookups: ['127.0.0.1:4161'],
     topic: 'topic-to-find-nsqds-for',
     interval: 60


def with_retries(&block)
      base_sleep_seconds = 0.5
      max_sleep_seconds = 300 # 5 minutes

      # Let's do this thing
      attempts = 0

      begin
        attempts += 1
        return block.call(attempts)

      rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH,
             Errno::ENETDOWN, Errno::ENETUNREACH, Errno::ETIMEDOUT, Timeout::Error => ex

        raise ex if attempts >= 100

        # The sleep time is an exponentially-increasing function of base_sleep_seconds.
        # But, it never exceeds max_sleep_seconds.
        sleep_seconds = [base_sleep_seconds * (2 ** (attempts - 1)), max_sleep_seconds].min
        # Randomize to a random value in the range sleep_seconds/2 .. sleep_seconds
        sleep_seconds = sleep_seconds * (0.5 * (1 + rand()))
        # But never sleep less than base_sleep_seconds
        sleep_seconds = [base_sleep_seconds, sleep_seconds].max

        warn "Failed to connect: #{ex}. Retrying in #{sleep_seconds.round(1)} seconds."

        snooze(sleep_seconds)

        retry
      end
    end

Retry the supplied block with exponential backoff.

 Borrowed liberally from:
 https://github.com/ooyala/retries/blob/master/lib/retries.rb

Retry the supplied block with exponential backoff .


def show(ind = '')
      count = 0
      self.to_a.each{|i|
        #puts "#{ind}#{i.name} #{i.object_id} #{i.super.object_id} [#{count}]: #{i.parsed_str} #{i.super.class}"
        puts "#{ind}#{i.name} [#{count}]: #{i.to_s.sub(/^(.{30})(.*?)(.{30})$/, '\1...\3')}"
        # Force parsing a segment
        if i.kind_of?(X12::Segment) && i.nodes[0]
          i.find_field(i.nodes[0].name)
        end
        i.nodes.each{|j|
          case
          when j.kind_of?(X12::Base)  then j.show(ind+'  ')
          when j.kind_of?(X12::Field) then puts "#{ind+'  '}#{j.name} -> '#{j.to_s}'"
          end
        }
        count += 1
      }
    end

Prints a tree-like representation of the element

Prints a tree - like representation of the element


def do_repeats(s)
      if self.repeats.end > 1
        possible_repeat = self.dup
        p_s = possible_repeat.parse(s)
        if p_s
          s = p_s
          self.next_repeat = possible_repeat
        end # if parsed
      end # more repeats
      s
    end

def
do_repeats
(
s
)
if
self
.
repeats
.
end
>
1
possible_repeat
=
self
.
dup
p_s
=
possible_repeat
.
parse
(
s
)
if
p_s
s
=
p_s
self
.
next_repeat
=
possible_repeat
end
# if parsed
end
# more repeats
s
end

Try to parse the current element one more time if required. Returns the rest of the string
 or the same string if no more repeats are found or required.

Try to parse the current element one more time if required . Returns the rest of the string or the same string if no more repeats are found or required .


def find(e)
      #puts "Finding [#{e}] in #{self.class} #{name}"
      case self
        when X12::Loop
        # Breadth first
        res = nodes.find{|i| e==i.name }
        return res if res
        # Depth now
        nodes.each{|i|
          res = i.find(e) if i.kind_of?(X12::Loop)
          return res unless res.nil? or EMPTY==res # otherwise keep looping
        }
        when X12::Segment
        return find_field(e).to_s
      end # case
      return EMPTY
    end

Make a deep copy of the element
 dup
 Recursively find a sub-element, which also has to be of type Base.

Make a deep copy of the element dup Recursively find a sub - element which also has to be of type Base .


def method_missing(meth, *args, &block)
      str = meth.id2name
      str = str[1..str.length] if str =~ /^_\d+$/ # to avoid pure number names like 270, 997, etc.
      #puts "Missing #{str}"
      if str =~ /=$/
        # Assignment
        str.chop!
        #puts str
        case self
        when X12::Segment
          res = find_field(str)
          throw Exception.new("No field '#{str}' in segment '#{self.name}'") if EMPTY == res
          res.content = args[0].to_s
          #puts res.inspect
        else
          throw Exception.new("Illegal assignment to #{meth} of #{self.class}")
        end # case
      else
        # Retrieval
        res = find(str)
        yield res if block_given?
        res
      end # if assignment
    end

The main method implementing Ruby-like access methods for nested elements

The main method implementing Ruby - like access methods for nested elements


def parse(str)
      s = str
      #puts "Parsing segment #{name} from #{s} with regexp [#{regexp.source}]"
      m = regexp.match(s)
      #puts "Matched #{m ? m[0] : 'nothing'}"

      return nil unless m

      s = m.post_match
      self.parsed_str = m[0]
      s = do_repeats(s)

      #puts "Parsed segment "+self.inspect
      return s
    end

Parses this segment out of a string, puts the match into value, returns the rest of the string - nil
 if cannot parse

Parses this segment out of a string puts the match into value returns the rest of the string - nil if cannot parse


def render
      self.to_a.inject(''){|repeat_str, i|
        if i.repeats.begin < 1 and !i.has_content?
          # Skip optional empty segments
          repeat_str
        else
          # Have to render no matter how empty
          repeat_str += i.name+i.nodes.reverse.inject(''){|nodes_str, j|
            field = j.render
            (j.required or nodes_str != '' or field != '') ? field_separator+field+nodes_str : nodes_str
          } + segment_separator
        end
      }
    end

def
render
self
.
to_a
.
inject
(
''
)
{
|
repeat_str
,
i
|
if
i
.
repeats
.
begin
<
1
and
!
i
.
has_content?
# Skip optional empty segments
repeat_str
else
# Have to render no matter how empty
repeat_str
+=
i
.
name
+
i
.
nodes
.
reverse
.
inject
(
''
)
{
|
nodes_str
,
j
|
field
=
j
.
render
(
j
.
required
or
nodes_str
!=
''
or
field
!=
''
)
field_separator
+
field
+
nodes_str
:
nodes_str
}
+
segment_separator
end
}
end

parse
 Render all components of this segment as string suitable for EDI


def regexp
      unless @regexp
        if self.nodes.find{|i| i.type =~ /^".+"$/ }
          # It's a very special regexp if there are constant fields
          re_str = self.nodes.inject("^#{name}#{Regexp.escape(field_separator)}"){|s, i|
            field_re = i.simple_regexp(field_separator, segment_separator)+Regexp.escape(field_separator)+'?'
            field_re = "(#{field_re})?" unless i.required
            s+field_re
          } + Regexp.escape(segment_separator)
          @regexp = Regexp.new(re_str)
        else
          # Simple match
          @regexp = Regexp.new("^#{name}#{Regexp.escape(field_separator)}[^#{Regexp.escape(segment_separator)}]*#{Regexp.escape(segment_separator)}")
        end
        #puts sprintf("%s %p", name, @regexp)
      end
      @regexp
    end

render
 Returns a regexp that matches this particular segment


def find_field(str)
      #puts "Finding field [#{str}] in #{self.class} #{name}"
      # If there is such a field to begin with
      field_num = nil
      self.nodes.each_index{|i|
        field_num = i if str == self.nodes[i].name
      }
      return EMPTY if field_num.nil?
      #puts field_num

      # Parse the segment if not parsed already
      unless @fields
        @fields = self.to_s.chop.split(Regexp.new(Regexp.escape(field_separator)))
        self.nodes.each_index{|i| self.nodes[i].content = @fields[i+1] }
      end
      #puts self.nodes[field_num].inspect
      return self.nodes[field_num]
    end

Finds a field in the segment. Returns EMPTY if not found.

Finds a field in the segment . Returns EMPTY if not found .


def parse(loop_name, str)
      loop = @x12_definition[X12::Loop][loop_name]
      #puts "Loops to parse #{@x12_definition[X12::Loop].keys}"
      throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop
      loop = loop.dup
      loop.parse(str)
      return loop
    end

Creates a parser out of a definition
 initialize
 Parse a loop of a given name out of a string. Throws an exception if the loop name is not defined.

Creates a parser out of a definition initialize Parse a loop of a given name out of a string . Throws an exception if the loop name is not defined .


def factory(loop_name)
      loop = @x12_definition[X12::Loop][loop_name]
      throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop
      loop = loop.dup
      return loop
    end

parse
 Make an empty loop to be filled out with information


def process_loop(loop)
      loop.nodes.each{|i|
        case i
          when X12::Loop then process_loop(i)
          when X12::Segment then process_segment(i) unless i.nodes.size > 0
          else return
        end
      }
    end

def process_loop ( loop ) loop . nodes . each { | i | case i when X12 :: Loop then process_loop ( i ) when X12 :: Segment then process_segment ( i ) unless i . nodes . size > 0 else return end } end

Recursively scan the loop and instantiate fields' definitions for all its
 segments

Recursively scan the loop and instantiate fields definitions for all its segments


def process_segment(segment)
      #puts "Trying to process segment #{segment.inspect}"
      unless @x12_definition[X12::Segment] && @x12_definition[X12::Segment][segment.name]
        # Try to find it in a separate file if missing from the @x12_definition structure
        initialize(segment.name+'.xml')
        segment_definition = @x12_definition[X12::Segment][segment.name]
        throw Exception.new("Cannot find a definition for segment #{segment.name}") unless segment_definition
      else
        segment_definition = @x12_definition[X12::Segment][segment.name]
      end
      segment_definition.nodes.each_index{|i|
        segment.nodes[i] = segment_definition.nodes[i]
        # Make sure we have the validation table if any for this field. Try to read one in if missing.
        table = segment.nodes[i].validation
        if table
          unless @x12_definition[X12::Table] && @x12_definition[X12::Table][table]
            initialize(table+'.xml')
            throw Exception.new("Cannot find a definition for table #{table}") unless @x12_definition[X12::Table] && @x12_definition[X12::Table][table]
          end
        end
      }
    end

Instantiate segment's fields as previously defined

Instantiate segment s fields as previously defined


def render
      if self.has_content?
        self.to_a.inject(''){|loop_str, i|
          loop_str += i.nodes.inject(''){|nodes_str, j|
            nodes_str += j.render
          }
        }
      else
        ''
      end
    end

def render if self . has_content? self . to_a . inject ( '' ) { | loop_str , i | loop_str += i . nodes . inject ( '' ) { | nodes_str , j | nodes_str += j . render } } else '' end end

parse
 Render all components of this loop as string suitable for EDI


def calculate_sortable_values
      response_fieldable.input_fields.each do |response_field|
        if (x = response_value(response_field)).present?
          get_responses["#{response_field.id}_sortable_value"] = response_field.sortable_value(x)
        end
      end

      mark_responses_as_changed!
    end

def calculate_sortable_values response_fieldable . input_fields . each do | response_field | if ( x = response_value ( response_field ) ) . present? get_responses [ "#{response_field.id}_sortable_value" ] = response_field . sortable_value ( x ) end end mark_responses_as_changed! end


def normalize_responses
      return if form.blank?

      form.response_fields.each do |response_field|
        if (x = self.response_value(response_field))
          response_field.normalize_response(x, get_responses)
        end
      end

      mark_responses_as_changed!
    end

def normalize_responses return if form . blank? form . response_fields . each do | response_field | if ( x = self . response_value ( response_field ) ) response_field . normalize_response ( x , get_responses ) end end mark_responses_as_changed! end

Normalizations get run before validation.

Normalizations get run before validation .


def audit_responses
      form.response_fields.each do |response_field|
        response_field.audit_response(self.response_value(response_field), get_responses)
      end

      mark_responses_as_changed!
    end

def audit_responses form . response_fields . each do | response_field | response_field . audit_response ( self . response_value ( response_field ) , get_responses ) end mark_responses_as_changed! end


def tag!(tag, *args, &block)
      text, attributes = nil, {}
      args.each do |arg|
        case arg
        when ::Hash
          attributes.merge!(arg)
        when ::String
          text ||= ''
          text << arg
        end
      end
      @stack << [tag, attributes, text ? [text] : []]
      if block
        _process(&block)
      end
      if @stack.length > 1
        node = @stack.pop
        @stack.last[2] << node
        NodeBuilder.new(node, self)
      else
        NodeBuilder.new(@stack.last, self)
      end
    end

def tag! ( tag , * args , & block ) text , attributes = nil , { } args . each do | arg | case arg when :: Hash attributes . merge! ( arg ) when :: String text ||= '' text << arg end end @stack << [ tag , attributes , text ? [ text ] : [ ] ] if block _process ( block ) end if @stack . length > 1 node = @stack . pop @stack . last [ 2 ] << node NodeBuilder . new ( node , self ) else NodeBuilder . new ( @stack . last , self ) end end

Construct a new builder, and start building

 The recommended way to call this is through `Hexp.build`. If the block
 takes an argument, then builder methods need to be called on that variable.

 @example With an explicit builder
   hi = Hexp.build {|html| html.span "Hello" ; html.span " World"}

 @example Without a builder object
   hi = Hexp.build { span "Hello" ; span " World"}

 @param [Symbol] tag
   The tag of the outermost element (optional)
 @param [Array<Hash,String>] args
   Extra arguments, a String for a text node, a Hash for attributes

 @yieldparam [Hexp::Builder]
   If the block takes an argument it will receive the builder object

 @api private

 Add a tag (HTML element)

 Typically this is called implicitly through method missing, but in case of
 name clashes or dynamically generated tags you can call this directly.

 @example
   hexp = Hexp.build :div do
     tag!(:p, "Oh the code, such sweet joy it brings")
   end
   hexp.to_html #=> "

Oh the code, such sweet joy it brings

"

 @param [Symbol] tag
   The tag name, like 'div' or 'head'
 @param [Array<Hash|String>] args
   A hash of attributes, or a string to use inside the tag, or both. Multiple
   occurences of each can be specified
 @param [Proc] block
   Builder directives for the contents of the tag

 @return [nil]

 @api public

Construct a new builder and start building


def <<(*args)
      args.each do |arg|
        if arg.respond_to?(:to_hexp)
          @stack.last[2] << arg
          self
        else
          ::Kernel.raise ::Hexp::FormatError, "Inserting literal HTML into a builder with << is deliberately not supported by Hexp"
        end
      end
    end

Add Hexp objects to the current tag

 Any Hexp::Node or other object implementing to_hexp can be added with
 this operator. Multiple objects can be specified in one call.

 Nokogiri and Builder allow inserting of strings containing HTML through
 this operator. Since this would violate the core philosophy of Hexp, and
 open the door for XSS vulnerabilities, we do not support that usage.

 If you really want to insert HTML that is already in serialized form,
 consider parsing it to Hexps first

 @example
   widget = H[:button, "click me!"]
   node = Hexp.build :div do |h|
     h << widget
   end
   node.to_html #=>
<button>click me!</button>

 @param [Array<#to_hexp>] args
   Hexpable objects to add to the current tag

 @return [Hexp::Builder]

 @api public