text:
require 'tk'

demodir = File.dirname($0)
themesdir = File.join(demodir, 'themes')
Tk::AUTO_PATH.lappend('.', demodir, themesdir)

Dir.foreach(themesdir){|name|
  next if name == '.' || name == '..'
  dir = File.join(themesdir, name)
  Tk::AUTO_PATH.lappend(dir) if File.directory?(dir)
}

require 'tkextlib/tile'

def version?(ver)
  TkPackage.vcompare(Tk::Tile.package_version, ver) >= 0
end

# define Tcl/Tk procedures for compatibility
Tk::Tile.__define_LoadImages_proc_for_compatibility__!
Tk::Tile::Style.__define_wrapper_proc_for_compatibility__!

unless Tk::Tile::Style.theme_names.include?('step')
  Tk::Tile::Style.theme_create('step')
end

Tk.load_tclscript(File.join(demodir, 'toolbutton.tcl'))
Tk.load_tclscript(File.join(demodir, 'repeater.tcl'))

# This forces an update of the available packages list. It's required
# for package names to find the themes in demos/themes/*.tcl
## Tk.tk_call(TkPackage.unknown_proc, 'Tcl', TkPackage.provide('Tcl'))
##  --> This doesn't work.
##      Because, unknown_proc may be "command + some arguments".
Tk.ip_eval("#{TkPackage.unknown_proc}  Tcl #{TkPackage.provide('Tcl')}")

TkRoot.new{
  title 'Tile demo'
  iconname 'Tile demo'
}

# The descriptive names of the builtin themes.
$THEMELIST = [
  ['default', 'Default'],
  ['classic', 'Classic'],
  ['alt', 'Revitalized'],
  ['winnative', 'Windows native'],
  ['xpnative', 'XP Native'],
  ['aqua', 'Aqua'],
]

$V = TkVariable.new_hash(:THEME      => 'default',
                         :COMPOUND   => 'top',
                         :CONSOLE    => false,
                         :MENURADIO1 => 'One',
                         :MENUCHECK1 => true,
                         :PBMODE     => 'determinate',
                         :SELECTED   => true,
                         :CHOICE     => 2)

# Add in any available loadable themes.
TkPackage.names.find_all{|n| n =~ /^(tile|ttk)::theme::/}.each{|pkg|
  name = pkg.split('::')[-1]
  unless $THEMELIST.assoc(name)
    $THEMELIST << [name, Tk.tk_call('string', 'totitle', name)]
  end
}

# Add theme definition written by ruby
$RUBY_THEMELIST = []
begin
  load(File.join(demodir, 'themes', 'kroc.rb'), true)
rescue => e
raise e
  $RUBY_THEMELIST << ['kroc-rb', 'Kroc (by Ruby)', false]
else
  $RUBY_THEMELIST << ['kroc-rb', 'Kroc (by Ruby)', true]
end

def makeThemeControl(parent)
  c = Tk::Tile::Labelframe.new(parent, :text=>'Theme')
  $THEMELIST.each{|theme, name|
    b = Tk::Tile::Radiobutton.new(c, :text=>name, :value=>theme,
                                  :variable=>$V.ref(:THEME),
                                  :command=>proc{setTheme(theme)})
    b.grid(:sticky=>:ew)
    unless (TkPackage.names.find{|n| n =~ /(tile|ttk)::theme::#{theme}/})
      b.ttk_state(:disabled)
    end
  }
  $RUBY_THEMELIST.each{|theme, name, available|
    b = Tk::Tile::Radiobutton.new(c, :text=>name, :value=>theme,
                                  :variable=>$V.ref(:THEME),
                                  :command=>proc{setTheme(theme)})
    b.grid(:sticky=>:ew)
    b.ttk_state(:disabled) unless available
  }
  c
end

def makeThemeMenu(parent)
  m = TkMenu.new(parent)
  $THEMELIST.each{|theme, name|
    m.add(:radiobutton, :label=>name, :variable=>$V.ref(:THEME),
          :value=>theme, :command=>proc{setTheme(theme)})
    unless (TkPackage.names.find{|n| n =~ /(tile|ttk)::theme::#{theme}/})
      m.entryconfigure(:end, :state=>:disabled)
    end
  }
  $RUBY_THEMELIST.each{|theme, name, available|
    m.add(:radiobutton, :label=>name, :variable=>$V.ref(:THEME),
          :value=>theme, :command=>proc{setTheme(theme)})
    m.entryconfigure(:end, :state=>:disabled) unless available
  }
  m
end

def setTheme(theme)
  if (pkg = TkPackage.names.find{|n| n =~ /(tile|ttk)::theme::#{theme}/})
    unless Tk::Tile::Style.theme_names.find{|n| n == theme}
      TkPackage.require(pkg)
    end
  end
  Tk::Tile::Style.theme_use(theme)
end

#
# Load icons...
#
$BUTTONS = ['open', 'new', 'save']
$CHECKBOXES = ['bold', 'italic']
$ICON = {}

def loadIcons(file)
  Tk.load_tclscript(file)
  img_data = TkVarAccess.new('ImgData')
  img_data.keys.each{|icon|
    $ICON[icon] = TkPhotoImage.new(:data=>img_data[icon])
  }
end

loadIcons(File.join(demodir, 'iconlib.tcl'))

#
# Utilities:
#
def foreachWidget(wins, cmd)
  wins.each{|w|
    cmd.call(w)
    foreachWidget(w.winfo_children, cmd)
  }
end

# sbstub
#	Used as the :command option for a scrollbar,
#	updates the scrollbar's position.
#
def sbstub(sb, cmd, num, units = 'units')
  num = TkComm.number(num)
  case cmd.to_s
  when 'moveto'
    sb.set(num, num+0.5)

  when 'scroll'
    if units.to_s == 'pages'
      delta = 0.2
    else
      delta = 0.05
    end
    current = sb.get
    sb.set(current[0] + delta * num, current[1] + delta * num)
  end
end

# ... for debugging:
TkBindTag::ALL.bind('ButtonPress-3', proc{|w| $W = w}, '%W')
TkBindTag::ALL.bind('Control-ButtonPress-3', proc{|w| w.set_focus}, '%W')

def showHelp()
  Tk.messageBox(:message=>'No help yet...')
end

#
# See toolbutton.tcl.
TkOption.add('*Toolbar.relief', :groove)
TkOption.add('*Toolbar.borderWidth', 2)

TkOption.add('*Toolbar.Button.Pad', 2)

$ROOT = Tk.root
$BASE = $ROOT
Tk.destroy(*($ROOT.winfo_children))

$TOOLBARS = []

#
# Toolbar button standard vs. tile comparison:
#
def makeToolbars
  #
  # Tile toolbar:
  #
  tb = Tk::Tile::Frame.new($BASE, :class=>'Toolbar')
  $TOOLBARS << tb
  i = 0
  $BUTTONS.each{|icon|
    i += 1
    Tk::Tile::Button.new(tb, :text=>icon, :image=>$ICON[icon],
                         :compound=>$V[:COMPOUND],
                         :style=>:Toolbutton).grid(:row=>0, :column=>i,
                                                   :sticky=>:news)
  }
  $CHECKBOXES.each{|icon|
    i += 1
    Tk::Tile::Checkbutton.new(tb, :text=>icon, :image=>$ICON[icon],
                              :variable=>$V.ref(icon),
                              :compound=>$V[:COMPOUND],
                              :style=>:Toolbutton).grid(:row=>0, :column=>i,
                                                        :sticky=>:news)
  }

  mb = Tk::Tile::Menubutton.new(tb, :text=>'toolbar', :image=>$ICON['file'],
                                :compound=>$V[:COMPOUND])
  mb.configure(:menu=>makeCompoundMenu(mb))
  i += 1
  mb.grid(:row=>0, :column=>i, :sticky=>:news)

  i += 1
  tb.grid_columnconfigure(i, :weight=>1)

  #
  # Standard toolbar:
  #
  tb = TkFrame.new($BASE, :class=>'Toolbar')
  $TOOLBARS << tb
  i = 0
  $BUTTONS.each{|icon|
    i += 1
    TkButton.new(tb, :text=>icon, :image=>$ICON[icon],
                 :compound=>$V[:COMPOUND], :relief=>:flat,
                 :overrelief=>:raised).grid(:row=>0, :column=>i,
                                            :sticky=>:news)
  }
  $CHECKBOXES.each{|icon|
    i += 1
    TkCheckbutton.new(tb, :text=>icon, :image=>$ICON[icon],
                      :variable=>$V.ref(icon), :compound=>$V[:COMPOUND],
                      :indicatoron=>false, :selectcolor=>'', :relief=>:flat,
                      :overrelief=>:raised).grid(:row=>0, :column=>i,
                                                 :sticky=>:news)
  }

  mb = TkMenubutton.new(tb, :text=>'toolbar', :image=>$ICON['file'],
                        :compound=>$V[:COMPOUND])
  mb.configure(:menu=>makeCompoundMenu(mb))
  i += 1
  mb.grid(:row=>0, :column=>i, :sticky=>:news)

  i += 1
  tb.grid_columnconfigure(i, :weight=>1)
end

#
# Toolbar :compound control:
#
def makeCompoundMenu(mb)
  menu = TkMenu.new(mb)
  %w(text image none top bottom left right center).each{|str|
    menu.add(:radiobutton, :label=>Tk.tk_call('string', 'totitle', str),
             :variable=>$V.ref(:COMPOUND), :value=>str,
             :command=>proc{ changeToolbars() })
  }
  menu
end

makeToolbars()

## CONTROLS
control = Tk::Tile::Frame.new($BASE)

#
# Overall theme control:
#
makeThemeControl(control).grid(:sticky=>:news, :padx=>6, :ipadx=>6)
control.grid_rowconfigure(99, :weight=>1)

def changeToolbars
  foreachWidget($TOOLBARS,
                proc{|w|
                  begin
                    w.compound($V[:COMPOUND])
                  rescue
                  end
                })
end

def scrolledWidget(parent, klass, themed, *args)
  if themed
    f = Tk::Tile::Frame.new(parent)
    t = klass.new(f, *args)
    vs = Tk::Tile::Scrollbar.new(f)
    hs = Tk::Tile::Scrollbar.new(f)
  else
    f = TkFrame.new(parent)
    t = klass.new(f, *args)
    vs = TkScrollbar.new(f)
    hs = TkScrollbar.new(f)
  end
  t.yscrollbar(vs)
  t.xscrollbar(hs)

  TkGrid.configure(t, vs, :sticky=>:news)
  TkGrid.configure(hs, 'x', :sticky=>:news)
  TkGrid.rowconfigure(f, 0, :weight=>1)
  TkGrid.columnconfigure(f, 0, :weight=>1)

  [f, t]
end

#
# Notebook demonstration:
#
def makeNotebook
  nb = Tk::Tile::Notebook.new($BASE, :padding=>6)
  nb.enable_traversal
  client = Tk::Tile::Frame.new(nb)
  nb.add(client, :text=>'Demo', :underline=>0)
  nb.select(client)

  scales = Tk::Tile::Frame.new(nb)
  nb.add(scales, :text=>'Scales')
  combo = Tk::Tile::Frame.new(nb)
  nb.add(combo, :text=>'Combobox', :underline=>7)
  tree = Tk::Tile::Frame.new(nb)
  nb.add(tree, :text=>'Tree')
  others = Tk::Tile::Frame.new(nb)
  nb.add(others, :text=>'Others', :underline=>4)

  [nb, client, scales, combo, tree, others]
end

nb, client, scales, combo, tree, others = makeNotebook()

#
# Side-by side check, radio, and menu button comparison:
#
def fillMenu(menu)
  %w(above below left right flush).each{|dir|
    menu.add(:command, :label=>Tk.tk_call('string', 'totitle', dir),
             :command=>proc{ menu.winfo_parent.direction(dir) })
  }
  menu.add(:cascade, :label=>'Submenu', :menu=>(submenu = TkMenu.new(menu)))
  submenu.add(:command, :label=>'Subcommand 1')
  submenu.add(:command, :label=>'Subcommand 2')
  submenu.add(:command, :label=>'Subcommand 3')

  menu.add(:separator)
  menu.add(:command, :label=>'Quit', :command=>proc{Tk.root.destroy})
end

l = Tk::Tile::Labelframe.new(client, :text=>'Themed', :padding=>6)
r = TkLabelframe.new(client, :text=>'Standard', :padx=>6, :pady=>6)

## Styled frame
cb = Tk::Tile::Checkbutton.new(l, :text=>'Checkbutton',
                               :variable=>$V.ref(:SELECTED), :underline=>2)
rb1 = Tk::Tile::Radiobutton.new(l, :text=>'One', :variable=>$V.ref(:CHOICE),
                                :value=>1, :underline=>0)
rb2 = Tk::Tile::Radiobutton.new(l, :text=>'Two', :variable=>$V.ref(:CHOICE),
                                :value=>2)
rb3 = Tk::Tile::Radiobutton.new(l, :text=>'Three',
                                :variable=>$V.ref(:CHOICE),
                                :value=>3, :underline=>0)
btn = Tk::Tile::Button.new(l, :text=>'Button', :underline=>0)

mb = Tk::Tile::Menubutton.new(l, :text=>'Menubutton', :underline=>2)
m = TkMenu.new(mb)
mb.menu(m)
fillMenu(m)

$entryText = TkVariable.new('Entry widget')
e = Tk::Tile::Entry.new(l, :textvariable=>$entryText)
e.selection_range(6, :end)

ltext_f, ltext = scrolledWidget(l, TkText, true,
                                :width=>12, :height=>5, :wrap=>:none)
# NOTE TO MAINTAINERS:
# The checkbuttons are -sticky ew / -expand x  on purpose:
# it demonstrates one of the differences between TCheckbuttons
# and standard checkbuttons.
#
Tk.grid(cb, :sticky=>:ew)
Tk.grid(rb1, :sticky=>:ew)
Tk.grid(rb2, :sticky=>:ew)
Tk.grid(rb3, :sticky=>:ew)
Tk.grid(btn, :sticky=>:ew, :padx=>2, :pady=>2)
Tk.grid(mb, :sticky=>:ew, :padx=>2, :pady=>2)
Tk.grid(e, :sticky=>:ew, :padx=>2, :pady=>2)
Tk.grid(ltext_f, :sticky=>:news)

TkGrid.columnconfigure(l, 0, :weight=>1)
TkGrid.rowconfigure(l, 7, :weight=>1) # text widget (grid is a PITA)

## Orig frame
cb = TkCheckbutton.new(r, :text=>'Checkbutton', :variable=>$V.ref(:SELECTED))
rb1 = TkRadiobutton.new(r, :text=>'One',
                        :variable=>$V.ref(:CHOICE), :value=>1)
rb2 = TkRadiobutton.new(r, :text=>'Two', :variable=>$V.ref(:CHOICE),
                        :value=>2, :underline=>1)
rb3 = TkRadiobutton.new(r, :text=>'Three',
                        :variable=>$V.ref(:CHOICE), :value=>3)
btn = TkButton.new(r, :text=>'Button')

mb = TkMenubutton.new(r, :text=>'Menubutton', :underline=>3, :takefocus=>true)
m = TkMenu.new(mb)
mb.menu(m)
$V[:rmbIndicatoron] = mb.indicatoron
m.add(:checkbutton, :label=>'Indicator?', #'
      :variable=>$V.ref(:rmbIndicatoron),
      :command=>proc{mb.indicatoron($V[:rmbIndicatoron])})
m.add(:separator)
fillMenu(m)

e = TkEntry.new(r, :textvariable=>$entryText)

rtext_f, rtext = scrolledWidget(r, TkText, false,
                                :width=>12, :height=>5, :wrap=>:none)

Tk.grid(cb, :sticky=>:ew)
Tk.grid(rb1, :sticky=>:ew)
Tk.grid(rb2, :sticky=>:ew)
Tk.grid(rb3, :sticky=>:ew)
Tk.grid(btn, :sticky=>:ew, :padx=>2, :pady=>2)
Tk.grid(mb, :sticky=>:ew, :padx=>2, :pady=>2)
Tk.grid(e, :sticky=>:ew, :padx=>2, :pady=>2)
Tk.grid(rtext_f, :sticky=>:news)

TkGrid.columnconfigure(l, 0, :weight=>1)
TkGrid.rowconfigure(l, 7, :weight=>1) # text widget (grid is a PITA)

Tk.grid(l, r, :sticky=>:news, :padx=>6, :pady=>6)
TkGrid.rowconfigure(client, 0, :weight=>1)
TkGrid.columnconfigure(client, [0, 1], :weight=>1)

#
# Add some text to the text boxes:
#
msgs = [
"The cat crept into the crypt, crapped and crept out again",
"Peter Piper picked a peck of pickled peppers",
"How much wood would a woodchuck chuck if a woodchuck could chuck wood",
"He thrusts his fists against the posts and still insists he sees the ghosts",
"Who put the bomb in the bom-b-bom-b-bom,",
"Is this your sister's sixth zither, sir?",
"Who put the ram in the ramalamadingdong?",
"I am not the pheasant plucker, I'm the pheasant plucker's mate."
]

nmsgs = msgs.size
(0...50).each{|n|
  msg = msgs[n % nmsgs]
  ltext.insert(:end, "#{n}: #{msg}\n")
  rtext.insert(:end, "#{n}: #{msg}\n")
}
#
# Scales and sliders pane:
#
l = Tk::Tile::Labelframe.new(scales, :text=>'Themed', :padding=>6)
r = TkLabelframe.new(scales, :text=>'Standard', :padx=>6, :pady=>6)

if version?('0.6')

  # thremed frame
  scale = Tk::Tile::Scale.new(l, :orient=>:horizontal, :from=>0, :to=>100,
          :variable=>$V.ref(:SCALE))
  vscale = Tk::Tile::Scale.new(l, :orient=>:vertical, :from=>0, :to=>100,
          :variable=>$V.ref(:VSCALE))
  progress = Tk::Tile::Progressbar.new(l, :orient=>:horizontal, :maximum=>100)
  vprogress = Tk::Tile::Progressbar.new(l, :orient=>:vertical, :maximum=>100)

  if true
    def progress.inverted(w, value)
      if w.mode == 'indeterminate'
        w.value(value)
      else
        w.value(w.maximum - value)
      end
    end
    scale.command {|value| progress.value(value)}
    vscale.command {|value| progress.inverted(vprogress, value) }
  else
    # This would also work, but the Tk scale widgets
    # in the right hand pane cause some interference when
    # in autoincrement/indeterminate mode.
    #
    progress.variable $V.ref(:SCALE)
    vprogress.variable $V.ref(:VSCALE)
  end

  scale.set(50)
  vscale.set(50)

  lmode = Tk::Tile::Label.new(l, :text=>'Progress bar mode')
  pbmode0 = Tk::Tile::Radiobutton.new(l, :variable=>$V.ref(:PBMODE),
          :text=>'determinate', :value=>'determinate',
          :command=>proc{pbMode(progress, vprogress)})
  pbmode1 = Tk::Tile::Radiobutton.new(l, :variable=>$V.ref(:PBMODE),
          :text=>'indeterminate', :value=>'indeterminate',
          :command=>proc{pbMode(progress, vprogress)})
  def pbMode(progress, vprogress)
    if vprogress.mode != $V[:PBMODE]
      vprogress.value(vprogress.maximum - vprogress.value)
    end

    progress.mode $V[:PBMODE]
    vprogress.mode $V[:PBMODE]
  end

  start = Tk::Tile::Button.new(l, :text=>"Start",
          :command=>proc{pbStart(progress, vprogress)})
  def pbStart(progress, vprogress)
    # $V[:PBMODE] = 'indeterminate'
    pbMode(progress, vprogress)
    progress.start 10
    vprogress.start
  end

  stop = Tk::Tile::Button.new(l, :text=>'Stop',
          :command=>proc{pbStop(progress, vprogress)})
  def pbStop(progress, vprogress)
    progress.stop
    vprogress.stop
  end

  Tk.grid(scale, :columnspan=>2, :sticky=>'ew')
  Tk.grid(progress, :columnspan=>2, :sticky=>'ew')
  Tk.grid(vscale, vprogress, :sticky=>'nws')

  Tk.grid(lmode, :sticky=>'we', :columnspan=>2)
  Tk.grid(pbmode0, :sticky=>'we', :columnspan=>2)
  Tk.grid(pbmode1, :sticky=>'we', :columnspan=>2)
  Tk.grid(start, :sticky=>'we', :columnspan=>2)
  Tk.grid(stop, :sticky=>'we', :columnspan=>2)

  l.grid_columnconfigure(0, :weight=>1)
  l.grid_columnconfigure(1, :weight=>1)
  l.grid_rowconfigure(99, :weight=>1)

  # standard frame
  TkScale.new(r, :orient=>:horizontal, :from=>0, :to=>100,
          :variable=>$V.ref(:SCALE)).grid(:sticky=>'news')
  TkScale.new(r, :orient=>:vertical, :from=>0, :to=>100,
          :variable=>$V.ref(:VSCALE)).grid(:sticky=>'nws')

  r.grid_columnconfigure(0, :weight=>1)
  r.grid_columnconfigure(1, :weight=>1)
  r.grid_rowconfigure(99, :weight=>1)

else # tile 0.5 or earlier

  # themed frame
  scale = Tk::Tile::Scale.new(l, :variable=>$V.ref(:SCALE),
          :orient=>:horizontal, :from=>0, :to=>100)
  vscale = Tk::Tile::Scale.new(l, :variable=>$V.ref(:VSCALE),
          :orient=>:vertical, :from=>-25, :to=>25)

  progress = Tk::Tile::Progress.new(l,
          :orient=>:horizontal, :from=>0, :to=>100)
  vprogress = Tk::Tile::Progress.new(l,
          :orient=>:vertical, :from=>-25, :to=>25)

  if true
    scale.command{|value| progress.set(value)}
    vscale.command{|value| vprogress.set(value)}
  else # this would also work. (via TkVariable#trace)
    v1 = scale.variable
    v2 = vscale.variable
    v1.trace('w', proc{ progress.set(v1.value) })
    v2.trace('w', proc{ vprogress.set(v2.value) })
  end

  Tk.grid(scale, :columnspan=>2, :sticky=>:ew)
  Tk.grid(progress, :columnspan=>2, :sticky=>:ew)
  Tk.grid(vscale, vprogress, :sticky=>:nws)
  TkGrid.columnconfigure(l, 0, :weight=>1)
  TkGrid.columnconfigure(l, 1, :weight=>1)

  # standard frame
  TkScale.new(r, :variable=>$V.ref(:SCALE),
          :orient=>:horizontal, :from=>0, :to=>100).grid(:sticky=>'news')
  TkScale.new(r, :variable=>$V.ref(:VSCALE),
          :orient=>:vertical, :from=>-25, :to=>25).grid(:sticky=>'nws')

  TkGrid.columnconfigure(r, 0, :weight=>1)
  TkGrid.columnconfigure(r, 1, :weight=>1)
end

# layout frames
Tk.grid(l, r, :sticky=>'nwes', :padx=>6, :pady=>6)
scales.grid_columnconfigure(0, :weight=>1)
scales.grid_columnconfigure(1, :weight=>1)
scales.grid_rowconfigure(0, :weight=>1)

#
# Command box:
#
cmd = Tk::Tile::Frame.new($BASE)
b_close = Tk::Tile::Button.new(cmd, :text=>'Close',
                               :underline=>0, :default=>:normal,
                               :command=>proc{Tk.root.destroy})
b_help = Tk::Tile::Button.new(cmd, :text=>'Help', :underline=>0,
                              :default=>:normal, :command=>proc{showHelp()})
Tk.grid('x', b_close, b_help, :pady=>[6, 4], :padx=>4)
TkGrid.columnconfigure(cmd, 0, :weight=>1)

#
# Set up accelerators:
#
$ROOT.bind('KeyPress-Escape', proc{Tk.event_generate(b_close, '<Invoke>')})
$ROOT.bind('<Help>', proc{Tk.event_generate(b_help, '<Invoke>')})
Tk::Tile::KeyNav.enableMnemonics($ROOT)
Tk::Tile::KeyNav.defaultButton(b_help)

Tk.grid($TOOLBARS[0], '-', :sticky=>:ew)
Tk.grid($TOOLBARS[1], '-', :sticky=>:ew)
Tk.grid(control,      nb,  :sticky=>:news)
Tk.grid(cmd,          '-', :sticky=>:ew)
TkGrid.columnconfigure($ROOT, 1, :weight=>1)
TkGrid.rowconfigure($ROOT, 2, :weight=>1)

#
# Add a menu
#
menu = TkMenu.new($BASE)
$ROOT.menu(menu)
m_file = TkMenu.new(menu, :tearoff=>0)
menu.add(:cascade, :label=>'File', :underline=>0, :menu=>m_file)
m_file.add(:command, :label=>'Open', :underline=>0,
           :compound=>:left, :image=>$ICON['open'])
m_file.add(:command, :label=>'Save', :underline=>0,
           :compound=>:left, :image=>$ICON['save'])
m_file.add(:separator)
m_f_test = TkMenu.new(menu, :tearoff=>0)
m_file.add(:cascade, :label=>'Test submenu', :underline=>0, :menu=>m_f_test)
m_file.add(:checkbutton, :label=>'Text check', :underline=>5,
           :variable=>$V.ref(:MENUCHECK1))
m_file.insert(:end, :separator)

if Tk.windowingsystem != 'x11'
  TkConsole.create
  m_file.insert(:end, :checkbutton, :label=>'Console', :underline=>5,
                :variable=>$V.ref(:CONSOLE), :command=>proc{toggle_console()})
  def toggle_console
    if TkComm.bool($V[:CONSOLE])
      TkConsole.show
    else
      TkConsole.hide
    end
  end
end

m_file.add(:command, :label=>'Exit', :underline=>1,
           :command=>proc{Tk.event_generate(b_close, '<Invoke>')})

%w(One Two Three Four).each{|lbl|
  m_f_test.add(:radiobutton, :label=>lbl, :variable=>$V.ref(:MENURADIO1))
}

# Add Theme menu.
#
menu.add(:cascade, :label=>'Theme', :underline=>3,
         :menu=>makeThemeMenu(menu))

setTheme($V[:THEME])

#
# Combobox demo pane:
#
values = %w(list abc def ghi jkl mno pqr stu vwx yz)
2.times {|i|
  cb = Tk::Tile::Combobox.new(
    combo, :values=>values, :textvariable=>$V.ref(:COMBO))
  cb.pack(:side=>:top, :padx=>2, :pady=>2, :expand=>false, :fill=>:x)
  if i == 1
    cb.ttk_state :readonly
    begin
      cb.current = 3 # ignore if unsupported (tile0.4)
    rescue
    end
  end
}

#
# Treeview widget demo pane:
#
if version?('0.5')

  treeview = nil # avoid 'undefined' error
  scrollbar = Tk::Tile::Scrollbar.new(tree,
      :command=>proc{|*args| treeview.yview(*args)})
  treeview = Tk::Tile::Treeview.new(tree, :columns=>%w(Class), :padding=>4,
      :yscrollcommand=>proc{|*args| scrollbar.set(*args)})

  Tk.grid(treeview, scrollbar, :sticky=>'news')
  tree.grid_columnconfigure(0, :weight=>1)
  tree.grid_rowconfigure(0, :weight=>1)
  tree.grid_propagate(0)

  # Add initial tree node:
  # Later nodes will be added in <<TreeviewOpen>> binding.
  treeview.insert('', 0, :id=>'.', :text=>'Main Window', :open=>false,
      :values=>[TkWinfo.classname('.')])
  treeview.headingconfigure('#0', :text=>'Widget')
  treeview.headingconfigure('Class', :text=>'Class')
  treeview.bind('<TreeviewOpen>', proc{fillTree(treeview)})

  def fillTree(treeview)
    id = treeview.focus_item
    unless TkWinfo.exist?(id)
      treeview.delete(id)
    end
    # Replace tree item children with current list of child windows.
    treeview.delete(treeview.children(id))
    for child in TkWinfo.children(id)
      treeview.insert(id, :end, :id=>child, :text=>TkWinfo.appname(child),
          :open=>false, :values=>[TkWinfo.classname(child)])
      unless TkWinfo.children(child).empty?
        # insert dummy child to show [+] indicator
        treeview.insert(child, :end)
      end
    end
  end

else
  Tk::Tile::Label.new(tree,
      :text=>'Treeview is supported on tile 0.5 or later...').pack
end

#
# Other demos:
#
$Timers = {:StateMonitor=>nil, :FocusMonitor=>nil}

begin
  msg = Tk::Tile::Label.new(others, :justify=>:left, :wraplength=>300)
rescue
  msg = TkMessage.new(others, :aspect=>200)
end

$Desc = {}

showDescription = TkBindTag.new
showDescription.bind('Enter', proc{|w| msg.text($Desc[w.path])}, '%W')
showDescription.bind('Leave', proc{|w| msg.text('')}, '%W')

[
  [ :trackStates, "Widget states...",
    "Display/modify widget state bits" ],

  [ :scrollbarResizeDemo,  "Scrollbar resize behavior...",
    "Shows how Tile and standard scrollbars differ when they're sized too large" ],

  [ :trackFocus, "Track keyboard focus..." ,
    "Display the name of the widget that currently has focus" ],

  [ :repeatDemo, "Repeating buttons...",
    "Demonstrates custom classes (see demos/repeater.tcl)" ]

].each{|demo_cmd, label, description|
  b = Tk::Tile::Button.new(others, :text=>label,
                           :command=>proc{ self.__send__(demo_cmd) })
  $Desc[b.path] = description
  b.bindtags <<= showDescription

  b.pack(:side=>:top, :expand=>false, :fill=>:x, :padx=>6, :pady=>6)
}

msg.pack(:side=>:bottom, :expand=>true, :fill=>:both)

#
# Scrollbar resize demo:
#
$scrollbars = nil

def scrollbarResizeDemo
  if $scrollbars
    begin
      $scrollbars.destroy
    rescue
    end
  end
  $scrollbars = TkToplevel.new(:title=>'Scrollbars', :geometry=>'200x200')
  f = TkFrame.new($scrollbars, :height=>200)
  tsb = Tk::Tile::Scrollbar.new(f, :command=>proc{|*args| sbstub(tsb, *args)})
  sb = TkScrollbar.new(f, :command=>proc{|*args| sbstub(sb, *args)})
  Tk.grid(tsb, sb, :sticky=>:news)

  sb.set(0, 0.5)  # prevent backwards-compatibility mode for old SB

  f.grid_columnconfigure(0, :weight=>1)
  f.grid_columnconfigure(1, :weight=>1)
  f.grid_rowconfigure(0, :weight=>1)

  f.pack(:expand=>true, :fill=>:both)
end

#
# Track focus demo:
#
$FocusInf = TkVariable.new_hash
$focus = nil

def trackFocus
  if $focus
    begin
      $focus.destroy
    rescue
    end
  end
  $focus = TkToplevel.new(:title=>'Keyboard focus')
  i = 0
  [
    ["Focus widget:", :Widget],
    ["Class:", :WidgetClass],
    ["Next:", :WidgetNext],
    ["Grab:", :Grab],
    ["Status:", :GrabStatus]
  ].each{|label, var_index|
    Tk.grid(Tk::Tile::Label.new($focus, :text=>label, :anchor=>:e),
            Tk::Tile::Label.new($focus,
                                :textvariable=>$FocusInf.ref(var_index),
                                :width=>40, :anchor=>:w, :relief=>:groove),
            :sticky=>:ew)
    i += 1
  }
  $focus.grid_columnconfigure(1, :weight=>1)
  $focus.grid_rowconfigure(i, :weight=>1)

  $focus.bind('Destroy', proc{Tk.after_cancel($Timers[:FocusMonitor])})
  focusMonitor
end

def focusMonitor
  $FocusInf[:Widget] = focus_win = Tk.focus
  if focus_win
    $FocusInf[:WidgetClass] = focus_win.winfo_classname
    $FocusInf[:WidgetNext] = Tk.focus_next(focus_win)
  else
    $FocusInf[:WidgetClass] = $FocusInf[:WidgetNext] = ''
  end

  $FocusInf[:Grab] = grab_wins = Tk.current_grabs
  unless grab_wins.empty?
    $FocusInf[:GrabStatus] = grab_wins[0].grab_status
  else
    $FocusInf[:GrabStatus] = ''
  end

  $Timers[:FocusMonitor] = Tk.after(200, proc{ focusMonitor() })
end

#
# Widget state demo:
#
$Widget = TkVariable.new

TkBindTag::ALL.bind('Control-Shift-ButtonPress-1',
                    proc{|w|
                      $Widget.value = w
                      updateStates()
                      Tk.callback_break
                    }, '%W')
$states_list = %w(active disabled focus pressed selected
                  background indeterminate invalid default)
$states_btns = {}
$states = nil

$State = TkVariable.new_hash

def trackStates
  if $states
    begin
      $state.destroy
    rescue
    end
  end
  $states = TkToplevel.new(:title=>'Widget states')

  l_inf = Tk::Tile::Label.new($states, :text=>"Press Control-Shift-Button-1 on any widget")

  l_lw = Tk::Tile::Label.new($states, :text=>'Widget:',
                             :anchor=>:e, :relief=>:groove)
  l_w = Tk::Tile::Label.new($states, :textvariable=>$Widget,
                             :anchor=>:w, :relief=>:groove)

  Tk.grid(l_inf, '-', :sticky=>:ew, :padx=>6, :pady=>6)
  Tk.grid(l_lw, l_w, :sticky=>:ew)

  $states_list.each{|st|
    cb = Tk::Tile::Checkbutton.new($states, :text=>st,
                                   :variable=>$State.ref(st),
                                   :command=>proc{ changeState(st) })
    $states_btns[st] = cb
    Tk.grid('x', cb, :sticky=>:nsew)
  }

  $states.grid_columnconfigure(1, :weight=>1)

  f_cmd = Tk::Tile::Frame.new($states)
  Tk.grid('x', f_cmd, :sticky=>:nse)

  b_close = Tk::Tile::Button.new(f_cmd, :text=>'Close',
                                 :command=>proc{ $states.destroy })
  Tk.grid('x', b_close, :padx=>4, :pady=>[6,4])
  f_cmd.grid_columnconfigure(0, :weight=>1)

  $states.bind('KeyPress-Escape', proc{Tk.event_generate(b_close, '<Invoke>')})

  $states.bind('Destroy', proc{Tk.after_cancel($Timers[:StateMonitor])})
  stateMonitor()
end

def stateMonitor
  updateStates() if $Widget.value != ''
  $Timers[:StateMonitor] = Tk.after(200, proc{ stateMonitor() })
end

def updateStates
  $states_list.each{|st|
    begin
      $State[st] = $Widget.window.ttk_instate(st)
    rescue
      $states_btns[st].ttk_state('disabled')
    else
      $states_btns[st].ttk_state('!disabled')
    end
  }
end

def changeState(st)
  if $Widget.value != ''
    if $State.bool_element(st)
      $Widget.window.ttk_state(st)
    else
      $Widget.window.ttk_state("!#{st}")
    end
  end
end

#
# Repeating buttons demo:
#
def repeatDemo
  if defined?($repeatDemo) && $repeatDemo.exist?
    $repeatDemo.deiconify; return
  end
  $repeatDemo = TkToplevel.new(:title=>'Repeating button')

  f = Tk::Tile::Frame.new($repeatDemo)
  b = Tk::Tile::Button.new(f, :class=>'Repeater', :text=>'Press and hold')
  if version?('0.6')
    p = Tk::Tile::Progressbar.new(f, :orient=>:horizontal, :maximum=>10)
  else # progressbar is not supported
    p = Tk::Tile::Progress.new(f, :orient=>:horizontal, :from=>0, :to=>10)
    def p.step
      i = self.get + 1
      i = self.from if i > self.to
      self.set(i)
    end
  end
  b.command {p.step}

  b.pack(:side=>:left, :expand=>false, :fill=>:none, :padx=>6, :pady=>6)
  p.pack(:side=>:right, :expand=>true, :fill=>:x, :padx=>6, :pady=>6)
  f.pack(:expand=>true, :fill=>:both)
end

Tk.mainloop


text:
> Draft topic

This document targets Orchard developers. Using only the admin dashboard, you will create a gallery that renders thumbnails of images that you select from the Media folder. Afterward, you can customize the gallery with CSS and an alternate HTML template.

# Create the Image Gallery Content Type

- From the admin dashboard, click **Content Definition**.
- The Manage Content Types page will open.
- Click **Create new type**.
- Give the new type a Display Name (e.g. *My Image Gallery*).
- Click **Create**.

![New content type](../Attachments/Creating-an-image-gallery/new-content-type.JPG)

- When you click create, Orchard will open the Add Parts page.
- Check **Widget**, then click **Save**.
- The Edit Content Type page will now show.
- Change the **Stereotype** to Widget and click **Save**.
- Then click **Add Field**.
- The Add New Field page will open.
- Choose **Media Library Picker Field**.
- Name the field (e.g. *My Media Library Picker Field*.)
- Click **Save**.

![Add a new field](../Attachments/Creating-an-image-gallery/add-new-field.JPG)

- After you click save, click on the down carat beside the new field.
- Check "**Allow multiple content items**."
- Click **Save** at the bottom of the page.
- You will now have the following Content Type. It has both a Widget Part and a Media Library Picker Field.

![Finished content type](../Attachments/Creating-an-image-gallery/finished-content-type.jpg)

# Add the Widget a Zone

- From the admin dashboard, click on **Widgets**.
- Click **Add** beside any zone (e.g. BeforeContent.)
- The Choose a Widget page will open.
- Choose the Widget that you just created (i.e. *My Image Gallery*.)
- The Add Widget page will open.
- Give the Widget a Title (e.g. *My Gallery Widget*.)
- Click the **Add** button below the "My Media Library Picker Field" label.
- The Media Library Picker modal will show.

In this screen shot, we have already imported some images and created some folders. You can create folders using the **Create Folder** button. You can import images by opening a folder and clicking the **Import** button. This tutorial assumes you know how to do that.

 ![Finished content type](../Attachments/Creating-an-image-gallery/modal-popup.jpg)

- Select the images that you want to display.
    - Tip: Use ctrl + click to select multiple images at once.
- Then click the **Select** button in the lower left of the modal (it's a bit hidden.)
- The Add Widget page will again display. Click **Save**.
- Visit the front end of your site to see the scaffolding of an image gallery.

# Customize the Look of the Gallery

- Turn on Shape Tracing
- Create an Alternate for the Fields_MediaPickerLibrary
- Edit the HTML and add CSS.
- Here are example alternate templates, courtesy of Bertrand Le Roy's [Codeplex Reply](https://orchard.codeplex.com/discussions/454808)

Fields.MediaLibraryPicker.cshtml

    @using Orchard.ContentManagement
    @using Orchard.MediaLibrary.Fields
    @using Orchard.Utility.Extensions;
    @{
        var field = (MediaLibraryPickerField) Model.ContentField;
        string name = field.DisplayName;
        var contents = field.MediaParts;
    }

    @foreach(var content in contents)
    {

            @Display(BuildDisplay(content, "Summary"))

    }

Media.Summary.cshtml

    @using Orchard.MediaLibrary.Models
    @using Orchard.Utility.Extensions;
    @{
        MediaPart mediaPart = Model.ContentItem.MediaPart;
    }

redpajama_set_name: RedPajamaGithub


text:
class CreateSiteProperties < ActiveRecord::Migration
  def up
    create_table :site_properties do |t|
      t.references :site
      t.references :room_property
      t.integer "price"
      t.timestamps
    end
    add_index :site_properties, ['site_id', 'room_property_id']
  end

  def down
  	drop_table :site_properties
  end
end


text:
package com.longluo.demo.filemanager;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * This class is completely modular, which is to say that it has
 * no reference to the any GUI activity. This class could be taken
 * and placed into in other java (not just Android) project and work.
 *

 *

 * This class handles all file and folder operations on the system.
 * This class dictates how files and folders are copied/pasted, (un)zipped
 * renamed and searched. The EventHandler class will generally call these
 * methods and have them performed in a background thread. Threading is not
 * done in this class.
 *
 * @author longluo
 */
public class FileManager {
    private static final int BUFFER = 2048;
    private static final int SORT_NONE = 0;
    private static final int SORT_ALPHA = 1;
    private static final int SORT_TYPE = 2;
    private static final int SORT_SIZE = 3;

    private boolean mShowHiddenFiles = false;
    private int mSortType = SORT_ALPHA;
    private long mDirSize = 0;
    private Stack<String> mPathStack;
    private ArrayList<String> mDirContent;

    /**
     * Constructs an object of the class
     *

     * this class uses a stack to handle the navigation of directories.
     */
    public FileManager() {
        mDirContent = new ArrayList<String>();
        mPathStack = new Stack<String>();

        mPathStack.push("/");
        mPathStack.push(mPathStack.peek() + "sdcard");
    }

    /**
     * This will return a string of the current directory path
     *
     * @return the current directory
     */
    public String getCurrentDir() {
        return mPathStack.peek();
    }

    /**
     * This will return a string of the current home path.
     *
     * @return the home directory
     */
    public ArrayList<String> setHomeDir(String name) {
        //This will eventually be placed as a settings item
        mPathStack.clear();
        mPathStack.push("/");
        mPathStack.push(name);

        return populate_list();
    }

    /**
     * This will determine if hidden files and folders will be visible to the
     * user.
     *
     * @param choice true if user is veiwing hidden files, false otherwise
     */
    public void setShowHiddenFiles(boolean choice) {
        mShowHiddenFiles = choice;
    }

    /**
     * @param type
     */
    public void setSortType(int type) {
        mSortType = type;
    }

    /**
     * This will return a string that represents the path of the previous path
     *
     * @return returns the previous path
     */
    public ArrayList<String> getPreviousDir() {
        int size = mPathStack.size();

        if (size >= 2)
            mPathStack.pop();

        else if (size == 0)
            mPathStack.push("/");

        return populate_list();
    }

    /**
     * @param path
     * @param isFullPath
     * @return
     */
    public ArrayList<String> getNextDir(String path, boolean isFullPath) {
        int size = mPathStack.size();

        if (!path.equals(mPathStack.peek()) && !isFullPath) {
            if (size == 1)
                mPathStack.push("/" + path);
            else
                mPathStack.push(mPathStack.peek() + "/" + path);
        } else if (!path.equals(mPathStack.peek()) && isFullPath) {
            mPathStack.push(path);
        }

        return populate_list();
    }

    /**
     * @param old    the file to be copied
     * @param newDir the directory to move the file to
     * @return
     */
    public int copyToDirectory(String old, String newDir) {
        File old_file = new File(old);
        File temp_dir = new File(newDir);
        byte[] data = new byte[BUFFER];
        int read = 0;

        if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
            String file_name = old.substring(old.lastIndexOf("/"), old.length());
            File cp_file = new File(newDir + file_name);

            try {
                BufferedOutputStream o_stream = new BufferedOutputStream(
                        new FileOutputStream(cp_file));
                BufferedInputStream i_stream = new BufferedInputStream(
                        new FileInputStream(old_file));

                while ((read = i_stream.read(data, 0, BUFFER)) != -1)
                    o_stream.write(data, 0, read);

                o_stream.flush();
                i_stream.close();
                o_stream.close();

            } catch (FileNotFoundException e) {
                Log.e("FileNotFoundException", e.getMessage());
                return -1;

            } catch (IOException e) {
                Log.e("IOException", e.getMessage());
                return -1;
            }

        } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
            String files[] = old_file.list();
            String dir = newDir + old.substring(old.lastIndexOf("/"), old.length());
            int len = files.length;

            if (!new File(dir).mkdir())
                return -1;

            for (int i = 0; i < len; i++)
                copyToDirectory(old + "/" + files[i], dir);

        } else if (!temp_dir.canWrite())
            return -1;

        return 0;
    }

    /**
     * @param zipName
     * @param toDir
     * @param fromDir
     */
    public void extractZipFilesFromDir(String zipName, String toDir, String fromDir) {
        if (!(toDir.charAt(toDir.length() - 1) == '/'))
            toDir += "/";
        if (!(fromDir.charAt(fromDir.length() - 1) == '/'))
            fromDir += "/";

        String org_path = fromDir + zipName;

        extractZipFiles(org_path, toDir);
    }

    /**
     * @param zip_file
     * @param directory
     */
    public void extractZipFiles(String zip_file, String directory) {
        byte[] data = new byte[BUFFER];
        String name, path, zipDir;
        ZipEntry entry;
        ZipInputStream zipstream;

        if (!(directory.charAt(directory.length() - 1) == '/'))
            directory += "/";

        if (zip_file.contains("/")) {
            path = zip_file;
            name = path.substring(path.lastIndexOf("/") + 1,
                    path.length() - 4);
            zipDir = directory + name + "/";

        } else {
            path = directory + zip_file;
            name = path.substring(path.lastIndexOf("/") + 1,
                    path.length() - 4);
            zipDir = directory + name + "/";
        }

        new File(zipDir).mkdir();

        try {
            zipstream = new ZipInputStream(new FileInputStream(path));

            while ((entry = zipstream.getNextEntry()) != null) {
                String buildDir = zipDir;
                String[] dirs = entry.getName().split("/");

                if (dirs != null && dirs.length > 0) {
                    for (int i = 0; i < dirs.length - 1; i++) {
                        buildDir += dirs[i] + "/";
                        new File(buildDir).mkdir();
                    }
                }

                int read = 0;
                FileOutputStream out = new FileOutputStream(
                        zipDir + entry.getName());
                while ((read = zipstream.read(data, 0, BUFFER)) != -1)
                    out.write(data, 0, read);

                zipstream.closeEntry();
                out.close();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param path
     */
    public void createZipFile(String path) {
        File dir = new File(path);
        String[] list = dir.list();
        String name = path.substring(path.lastIndexOf("/"), path.length());
        String _path;

        if (!dir.canRead() || !dir.canWrite())
            return;

        int len = list.length;

        if (path.charAt(path.length() - 1) != '/')
            _path = path + "/";
        else
            _path = path;

        try {
            ZipOutputStream zip_out = new ZipOutputStream(
                    new BufferedOutputStream(
                            new FileOutputStream(_path + name + ".zip"), BUFFER));

            for (int i = 0; i < len; i++)
                zip_folder(new File(_path + list[i]), zip_out);

            zip_out.close();

        } catch (FileNotFoundException e) {
            Log.e("File not found", e.getMessage());

        } catch (IOException e) {
            Log.e("IOException", e.getMessage());
        }
    }

    /**
     * @param filePath
     * @param newName
     * @return
     */
    public int renameTarget(String filePath, String newName) {
        File src = new File(filePath);
        String ext = "";
        File dest;

        if (src.isFile())
            /*get file extension*/
            ext = filePath.substring(filePath.lastIndexOf("."), filePath.length());

        if (newName.length() < 1)
            return -1;

        String temp = filePath.substring(0, filePath.lastIndexOf("/"));

        dest = new File(temp + "/" + newName + ext);
        if (src.renameTo(dest))
            return 0;
        else
            return -1;
    }

    /**
     * @param path
     * @param name
     * @return
     */
    public int createDir(String path, String name) {
        int len = path.length();

        if (len < 1 || len < 1)
            return -1;

        if (path.charAt(len - 1) != '/')
            path += "/";

        if (new File(path + name).mkdir())
            return 0;

        return -1;
    }

    /**
     * The full path name of the file to delete.
     *
     * @param path name
     * @return
     */
    public int deleteTarget(String path) {
        File target = new File(path);

        if (target.exists() && target.isFile() && target.canWrite()) {
            target.delete();
            return 0;
        } else if (target.exists() && target.isDirectory() && target.canRead()) {
            String[] file_list = target.list();

            if (file_list != null && file_list.length == 0) {
                target.delete();
                return 0;

            } else if (file_list != null && file_list.length > 0) {

                for (int i = 0; i < file_list.length; i++) {
                    File temp_f = new File(target.getAbsolutePath() + "/" + file_list[i]);

                    if (temp_f.isDirectory())
                        deleteTarget(temp_f.getAbsolutePath());
                    else if (temp_f.isFile())
                        temp_f.delete();
                }
            }
            if (target.exists())
                if (target.delete())
                    return 0;
        }
        return -1;
    }

    /**
     * @param name
     * @return
     */
    public boolean isDirectory(String name) {
        return new File(mPathStack.peek() + "/" + name).isDirectory();
    }

    /**
     * converts integer from wifi manager to an IP address.
     *
     * @param des
     * @return
     */
    public static String integerToIPAddress(int ip) {
        String ascii_address = "";
        int[] num = new int[4];

        num[0] = (ip & 0xff000000) >> 24;
        num[1] = (ip & 0x00ff0000) >> 16;
        num[2] = (ip & 0x0000ff00) >> 8;
        num[3] = ip & 0x000000ff;

        ascii_address = num[0] + "." + num[1] + "." + num[2] + "." + num[3];

        return ascii_address;
    }

    /**
     * @param dir
     * @param pathName
     * @return
     */
    public ArrayList<String> searchInDirectory(String dir, String pathName) {
        ArrayList<String> names = new ArrayList<String>();
        search_file(dir, pathName, names);

        return names;
    }

    /**
     * @param path
     * @return
     */
    public long getDirSize(String path) {
        get_dir_size(new File(path));

        return mDirSize;
    }

    private static final Comparator alph = new Comparator<String>() {
        @Override
        public int compare(String arg0, String arg1) {
            return arg0.toLowerCase().compareTo(arg1.toLowerCase());
        }
    };

    private final Comparator size = new Comparator<String>() {
        @Override
        public int compare(String arg0, String arg1) {
            String dir = mPathStack.peek();
            Long first = new File(dir + "/" + arg0).length();
            Long second = new File(dir + "/" + arg1).length();

            return first.compareTo(second);
        }
    };

    private final Comparator type = new Comparator<String>() {
        @Override
        public int compare(String arg0, String arg1) {
            String ext = null;
            String ext2 = null;
            int ret;

            try {
                ext = arg0.substring(arg0.lastIndexOf(".") + 1, arg0.length()).toLowerCase();
                ext2 = arg1.substring(arg1.lastIndexOf(".") + 1, arg1.length()).toLowerCase();

            } catch (IndexOutOfBoundsException e) {
                return 0;
            }
            ret = ext.compareTo(ext2);

            if (ret == 0)
                return arg0.toLowerCase().compareTo(arg1.toLowerCase());

            return ret;
        }
    };

    /* (non-Javadoc)
     * this function will take the string from the top of the directory stack
     * and list all files/folders that are in it and return that list so
     * it can be displayed. Since this function is called every time we need
     * to update the the list of files to be shown to the user, this is where
     * we do our sorting (by type, alphabetical, etc).
     *
     * @return
     */
    private ArrayList<String> populate_list() {

        if (!mDirContent.isEmpty())
            mDirContent.clear();

        File file = new File(mPathStack.peek());

        if (file.exists() && file.canRead()) {
            String[] list = file.list();
            int len = list.length;

			/* add files/folder to arraylist depending on hidden status */
            for (int i = 0; i < len; i++) {
                if (!mShowHiddenFiles) {
                    if (list[i].toString().charAt(0) != '.')
                        mDirContent.add(list[i]);

                } else {
                    mDirContent.add(list[i]);
                }
            }

			/* sort the arraylist that was made from above for loop */
            switch (mSortType) {
                case SORT_NONE:
                    //no sorting needed
                    break;

                case SORT_ALPHA:
                    Object[] tt = mDirContent.toArray();
                    mDirContent.clear();

                    Arrays.sort(tt, alph);

                    for (Object a : tt) {
                        mDirContent.add((String) a);
                    }
                    break;

                case SORT_SIZE:
                    int index = 0;
                    Object[] size_ar = mDirContent.toArray();
                    String dir = mPathStack.peek();

                    Arrays.sort(size_ar, size);

                    mDirContent.clear();
                    for (Object a : size_ar) {
                        if (new File(dir + "/" + (String) a).isDirectory())
                            mDirContent.add(index++, (String) a);
                        else
                            mDirContent.add((String) a);
                    }
                    break;

                case SORT_TYPE:
                    int dirindex = 0;
                    Object[] type_ar = mDirContent.toArray();
                    String current = mPathStack.peek();

                    Arrays.sort(type_ar, type);
                    mDirContent.clear();

                    for (Object a : type_ar) {
                        if (new File(current + "/" + (String) a).isDirectory())
                            mDirContent.add(dirindex++, (String) a);
                        else
                            mDirContent.add((String) a);
                    }
                    break;
            }

        } else {
            mDirContent.add("Emtpy");
        }

        return mDirContent;
    }

    /*
     *
     * @param file
     * @param zout
     * @throws IOException
     */
    private void zip_folder(File file, ZipOutputStream zout) throws IOException {
        byte[] data = new byte[BUFFER];
        int read;

        if (file.isFile()) {
            ZipEntry entry = new ZipEntry(file.getName());
            zout.putNextEntry(entry);
            BufferedInputStream instream = new BufferedInputStream(
                    new FileInputStream(file));

            while ((read = instream.read(data, 0, BUFFER)) != -1)
                zout.write(data, 0, read);

            zout.closeEntry();
            instream.close();

        } else if (file.isDirectory()) {
            String[] list = file.list();
            int len = list.length;

            for (int i = 0; i < len; i++)
                zip_folder(new File(file.getPath() + "/" + list[i]), zout);
        }
    }

    /*
     *
     * @param path
     */
    private void get_dir_size(File path) {
        File[] list = path.listFiles();
        int len;

        if (list != null) {
            len = list.length;

            for (int i = 0; i < len; i++) {
                try {
                    if (list[i].isFile() && list[i].canRead()) {
                        mDirSize += list[i].length();

                    } else if (list[i].isDirectory() && list[i].canRead() && !isSymlink(list[i])) {
                        get_dir_size(list[i]);
                    }
                } catch (IOException e) {
                    Log.e("IOException", e.getMessage());
                }
            }
        }
    }

    // Inspired by org.apache.commons.io.FileUtils.isSymlink()
    private static boolean isSymlink(File file) throws IOException {
        File fileInCanonicalDir = null;
        if (file.getParent() == null) {
            fileInCanonicalDir = file;
        } else {
            File canonicalDir = file.getParentFile().getCanonicalFile();
            fileInCanonicalDir = new File(canonicalDir, file.getName());
        }
        return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
    }

    /*
     * (non-JavaDoc)
     * I dont like this method, it needs to be rewritten. Its hacky in that
     * if you are searching in the root dir (/) then it is not going to be treated
     * as a recursive method so the user dosen't have to sit forever and wait.
     *
     * I will rewrite this ugly method.
     *
     * @param dir		directory to search in
     * @param fileName	filename that is being searched for
     * @param n			ArrayList to populate results
     */
    private void search_file(String dir, String fileName, ArrayList<String> n) {
        File root_dir = new File(dir);
        String[] list = root_dir.list();

        if (list != null && root_dir.canRead()) {
            int len = list.length;

            for (int i = 0; i < len; i++) {
                File check = new File(dir + "/" + list[i]);
                String name = check.getName();

                if (check.isFile() && name.toLowerCase().
                        contains(fileName.toLowerCase())) {
                    n.add(check.getPath());
                } else if (check.isDirectory()) {
                    if (name.toLowerCase().contains(fileName.toLowerCase()))
                        n.add(check.getPath());

                    else if (check.canRead() && !dir.equals("/"))
                        search_file(check.getAbsolutePath(), fileName, n);
                }
            }
        }
    }
}


text:
#ifndef ROS_VIEW_H
#define ROS_VIEW_H

#include <core/Common.h>
#include <core/Environment.h>
#include <application/Events.h>

namespace ros {
    class ROS_API View : public boost::noncopyable {
        public:
            virtual ~View() {}

            virtual bool init(const PropertyTree& config) =0;
            virtual void uninit() =0;

            virtual void onKeyboardPressEvent(const KeyboardPressEvent& event) =0;
            virtual void onMouseMotionEvent(const MouseMotionEvent& event) =0;
            virtual void onMousePressEvent(const MousePressEvent& event) =0;
    };

    typedef boost::shared_ptr<View> ViewPtr;
}

#endif // ROS_VIEW_H


text:
package org.apache.nifi.authorization;

/**
 *
 */
public class StandardAuthorizerInitializationContext implements AuthorizerInitializationContext {

    private final String identifier;
    private final AuthorizerLookup authorizerLookup;

    public StandardAuthorizerInitializationContext(String identifier, AuthorizerLookup authorizerLookup) {
        this.identifier = identifier;
        this.authorizerLookup = authorizerLookup;
    }

    @Override
    public String getIdentifier() {
        return identifier;
    }

    public AuthorizerLookup getAuthorizerLookup() {
        return authorizerLookup;
    }

}


text:
package org.apache.nifi.web.search.attributematchers;

import org.apache.nifi.connectable.Connection;
import org.apache.nifi.controller.queue.FlowFileQueue;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

import java.util.concurrent.TimeUnit;

public class ExpirationMatcherTest extends AbstractAttributeMatcherTest{

    @Mock
    private Connection component;

    @Mock
    private FlowFileQueue flowFileQueue;

    @Before
    public void setUp() {
        super.setUp();
        Mockito.when(component.getFlowFileQueue()).thenReturn(flowFileQueue);
    }

    @Test
    public void testWhenKeywordExpiresAppearsAndExpired() {
        // given
        final ExpirationMatcher testSubject = new ExpirationMatcher();
        givenSearchTerm("expires");
        givenExpired();

        // when
        testSubject.match(component, searchQuery, matches);

        // then
        thenMatchConsistsOf("FlowFile expiration: 5");
    }

    @Test
    public void testWhenKeywordExpirationAppearsAndExpired() {
        // given
        final ExpirationMatcher testSubject = new ExpirationMatcher();
        givenSearchTerm("expiration");
        givenExpired();

        // when
        testSubject.match(component, searchQuery, matches);

        // then
        thenMatchConsistsOf("FlowFile expiration: 5");
    }

    @Test
    public void testWhenNoKeywordAppearsAndExpired() {
        // given
        final ExpirationMatcher testSubject = new ExpirationMatcher();
        givenSearchTerm("lorem");
        givenExpired();

        // when
        testSubject.match(component, searchQuery, matches);

        // then
        thenNoMatches();
    }

    @Test
    public void testWhenKeywordExpiresAppearsAndDoesNotExpired() {
        // given
        final ExpirationMatcher testSubject = new ExpirationMatcher();
        givenSearchTerm("expires");
        givenNotExpired();

        // when
        testSubject.match(component, searchQuery, matches);

        // then
        thenNoMatches();
    }

    private void givenExpired() {
        Mockito.when(flowFileQueue.getFlowFileExpiration(TimeUnit.MILLISECONDS)).thenReturn(5L);
        Mockito.when(flowFileQueue.getFlowFileExpiration()).thenReturn("5");
    }

    private void givenNotExpired() {
        Mockito.when(flowFileQueue.getFlowFileExpiration(TimeUnit.MILLISECONDS)).thenReturn(0L);
    }
}


text:
require 'spec_helper'
require SUPPORT_PATH.join('resource_service')

RSpec.describe 'Functional Socket Client' do
  before(:all) do
    load "protobuf/socket.rb"
    @options = OpenStruct.new(:host => "127.0.0.1", :port => 9399, :backlog => 100, :threshold => 100)
    @runner = ::Protobuf::Rpc::SocketRunner.new(@options)
    @server_thread = Thread.new(@runner, &:run)
    Thread.pass until @runner.running?
  end

  after(:all) do
    @runner.stop
    @server_thread.join
  end

  it 'runs fine when required fields are set' do
    expect do
      client = ::Test::ResourceService.client

      client.find(:name => 'Test Name', :active => true) do |c|
        c.on_success do |succ|
          expect(succ.name).to eq("Test Name")
          expect(succ.status).to eq(::Test::StatusType::ENABLED)
        end

        c.on_failure do |err|
          fail err.inspect
        end
      end
    end.to_not raise_error
  end

  it 'calls the on_failure callback when a message is malformed' do
    error = nil
    request = ::Test::ResourceFindRequest.new(:active => true)
    client = ::Test::ResourceService.client

    client.find(request) do |c|
      c.on_success { fail "shouldn't pass" }
      c.on_failure { |e| error = e }
    end

    expect(error.message).to match(/Required field.*does not have a value/)
  end

  it 'calls the on_failure callback when the request type is wrong' do
    error = nil
    request = ::Test::Resource.new(:name => 'Test Name')
    client = ::Test::ResourceService.client

    client.find(request) do |c|
      c.on_success { fail "shouldn't pass" }
      c.on_failure { |e| error = e }
    end
    expect(error.message).to match(/expected request.*ResourceFindRequest.*Resource instead/i)
  end
end


text:
@interface CVTodaysNewsContentView : UIView {
	UIImageView *_imageFirThumb;
	UIImageView *_imageSecThumb;
	UIImageView *_imageThiThumb;

	UIImageView *_imagePoint1;
	UIImageView *_imagePoint2;
	UIImageView *_imageLine;

	UILabel *_labelFirTitle;
	UILabel *_labelSecTitle;
	UILabel *_labelThiTitle;
	UILabel *_labelFouTitle;

	UIButton *_buttonFirst;
	UIButton *_buttonSecond;
	UIButton *_buttonThird;
	UIButton *_buttonForth;
}

@property (nonatomic, retain) UIImageView *imageFirThumb;
@property (nonatomic, retain) UIImageView *imageSecThumb;
@property (nonatomic, retain) UIImageView *imageThiThumb;

@property (nonatomic, retain) UIImageView *imagePoint1;
@property (nonatomic, retain) UIImageView *imagePoint2;
@property (nonatomic, retain) UIImageView *imageLine;

@property (nonatomic, retain) UILabel *labelFirTitle;
@property (nonatomic, retain) UILabel *labelSecTitle;
@property (nonatomic, retain) UILabel *labelThiTitle;
@property (nonatomic, retain) UILabel *labelFouTitle;

@property (nonatomic, retain) UIButton *buttonFirst;
@property (nonatomic, retain) UIButton *buttonSecond;
@property (nonatomic, retain) UIButton *buttonThird;
@property (nonatomic, retain) UIButton *buttonForth;
@end


text:
Angular2 HTTP client to consume RESTful services. Built on angular2/http with TypeScript.
**Note:** this solutions is not production ready, it's in a very basic alpha state. Any ideas or contributions are very welcomed :)

## Installation

```sh
npm install angular2-rest
```

## Example

```ts

import {Request, Response} from 'angular2/http';
import {RESTClient, GET, PUT, POST, DELETE, BaseUrl, Headers, DefaultHeaders, Path, Body, Query} from 'angular2-rest';

import {Todo} from './models/Todo';
import {SessionFactory} from './sessionFactory';

@Injectable()
@BaseUrl("http://localhost:3000/api/")
@DefaultHeaders({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
})
export class TodoRESTClient extends RESTClient {

    protected requestInterceptor(req: Request) {
        if (SessionFactory.getInstance().isAuthenticated) {
            req.headers.append('jwt', SessionFactory.getInstance().credentials.jwt);
        }
    }

    protected requestInterceptor(req: Response) {
        // do sg with responses
    }

    @GET("todo/")
    public getTodos( @Query("sort") sort?: string): Observable { return null; };

    @GET("todo/{id}")
    public getTodoById( @Path("id") id: string): Observable { return null; };

    @POST("todo")
    public postTodo( @Body todo: Todo): Observable { return null; };

    @PUT("todo/{id}")
    public putTodoById( @Path("id") id: string, @Body todo: Todo): Observable { return null; };

    @DELETE("todo/{id}")
    public deleteTodoById( @Path("id") id: string): Observable { return null; };

}
```

### Using it in your component

``` ts
@Component({
  selector: 'to-do',
  viewProviders: [TodoRESTClient],
})
@View({
  templateUrl: 'components/to-do-template.html',
})
export class ToDoCmp {

  constructor(todoRESTClient: TodoRESTClient) {
  }

  //Use todoRESTClient
}
```
## API Docs

### RESTClient
#### Methods:
- `getBaseUrl(): string`: returns the base url of RESTClient
- `getDefaultHeaders(): Object`: returns the default headers of RESTClient in a key-value pair

### Class decorators:
- `@BaseUrl(url: string)`
- `@DefaultHeaders(headers: Object)`

### Method decorators:
- `@GET(url: String)`
- `@POST(url: String)`
- `@PUT(url: String)`
- `@DELETE(url: String)`
- `@Headers(headers: Object)`

### Parameter decorators:
- `@Path(key: string)`
- `@Query(key: string)`
- `@Header(key: string)`
- `@Body`

# License

MIT


text:
package com.quollwriter.ui.components;

import java.util.EventListener;

public interface DragListener extends EventListener
{

    public void dragFinished (DragEvent ev);

    public void dragStarted (DragEvent ev);

    public void dragInProgress (DragEvent ev);

}


text:
"use strict";

module.exports = Iterator;

var Object = require("./shim-object");
var GenericCollection = require("./generic-collection");

// upgrades an iterable to a Iterator
function Iterator(iterable) {

    if (!(this instanceof Iterator)) {
        return new Iterator(iterable);
    }

    if (Array.isArray(iterable) || typeof iterable === "string")
        return Iterator.iterate(iterable);

    iterable = Object(iterable);

    if (iterable instanceof Iterator) {
        return iterable;
    } else if (iterable.next) {
        this.next = function () {
            return iterable.next();
        };
    } else if (iterable.iterate) {
        var iterator = iterable.iterate();
        this.next = function () {
            return iterator.next();
        };
    } else if (Object.prototype.toString.call(iterable) === "[object Function]") {
        this.next = iterable;
    } else {
        throw new TypeError("Can't iterate " + iterable);
    }

}

Iterator.prototype.forEach = GenericCollection.prototype.forEach;
Iterator.prototype.map = GenericCollection.prototype.map;
Iterator.prototype.filter = GenericCollection.prototype.filter;
Iterator.prototype.every = GenericCollection.prototype.every;
Iterator.prototype.some = GenericCollection.prototype.some;
Iterator.prototype.any = GenericCollection.prototype.any;
Iterator.prototype.all = GenericCollection.prototype.all;
Iterator.prototype.min = GenericCollection.prototype.min;
Iterator.prototype.max = GenericCollection.prototype.max;
Iterator.prototype.sum = GenericCollection.prototype.sum;
Iterator.prototype.average = GenericCollection.prototype.average;
Iterator.prototype.flatten = GenericCollection.prototype.flatten;
Iterator.prototype.zip = GenericCollection.prototype.zip;
Iterator.prototype.enumerate = GenericCollection.prototype.enumerate;
Iterator.prototype.sorted = GenericCollection.prototype.sorted;
Iterator.prototype.group = GenericCollection.prototype.group;
Iterator.prototype.reversed = GenericCollection.prototype.reversed;
Iterator.prototype.toArray = GenericCollection.prototype.toArray;
Iterator.prototype.toObject = GenericCollection.prototype.toObject;
Iterator.prototype.iterator = GenericCollection.prototype.iterator;

// this is a bit of a cheat so flatten and such work with the generic
// reducible
Iterator.prototype.constructClone = function (values) {
    var clone = [];
    clone.addEach(values);
    return clone;
};

Iterator.prototype.mapIterator = function (callback /*, thisp*/) {
    var self = Iterator(this),
        thisp = arguments[1],
        i = 0;

    if (Object.prototype.toString.call(callback) != "[object Function]")
        throw new TypeError();

    return new self.constructor(function () {
        return callback.call(thisp, self.next(), i++, self);
    });
};

Iterator.prototype.filterIterator = function (callback /*, thisp*/) {
    var self = Iterator(this),
        thisp = arguments[1],
        i = 0;

    if (Object.prototype.toString.call(callback) != "[object Function]")
        throw new TypeError();

    return new self.constructor(function () {
        var value;
        while (true) {
            value = self.next();
            if (callback.call(thisp, value, i++, self))
                return value;
        }
    });
};

Iterator.prototype.reduce = function (callback /*, initial, thisp*/) {
    var self = Iterator(this),
        result = arguments[1],
        thisp = arguments[2],
        i = 0,
        value;

    if (Object.prototype.toString.call(callback) != "[object Function]")
        throw new TypeError();

    // first iteration unrolled
    try {
        value = self.next();
        if (arguments.length > 1) {
            result = callback.call(thisp, result, value, i, self);
        } else {
            result = value;
        }
        i++;
    } catch (exception) {
        if (isStopIteration(exception)) {
            if (arguments.length > 1) {
                return arguments[1]; // initial
            } else {
                throw TypeError("cannot reduce a value from an empty iterator with no initial value");
            }
        } else {
            throw exception;
        }
    }

    // remaining entries
    try {
        while (true) {
            value = self.next();
            result = callback.call(thisp, result, value, i, self);
            i++;
        }
    } catch (exception) {
        if (isStopIteration(exception)) {
            return result;
        } else {
            throw exception;
        }
    }

};

Iterator.prototype.concat = function () {
    return Iterator.concat(
        Array.prototype.concat.apply(this, arguments)
    );
};

Iterator.prototype.dropWhile = function (callback /*, thisp */) {
    var self = Iterator(this),
        thisp = arguments[1],
        stopped = false,
        stopValue;

    if (Object.prototype.toString.call(callback) != "[object Function]")
        throw new TypeError();

    self.forEach(function (value, i) {
        if (!callback.call(thisp, value, i, self)) {
            stopped = true;
            stopValue = value;
            throw StopIteration;
        }
    });

    if (stopped) {
        return self.constructor([stopValue]).concat(self);
    } else {
        return self.constructor([]);
    }
};

Iterator.prototype.takeWhile = function (callback /*, thisp*/) {
    var self = Iterator(this),
        thisp = arguments[1];

    if (Object.prototype.toString.call(callback) != "[object Function]")
        throw new TypeError();

    return self.mapIterator(function (value, i) {
        if (!callback.call(thisp, value, i, self))
            throw StopIteration;
        return value;
    });
};

Iterator.prototype.zipIterator = function () {
    return Iterator.unzip(
        Array.prototype.concat.apply(this, arguments)
    );
};

Iterator.prototype.enumerateIterator = function (start) {
    return Iterator.count(start).zipIterator(this);
};

// creates an iterator for Array and String
Iterator.iterate = function (iterable) {
    var start;
    start = 0;
    return new Iterator(function () {
        // advance to next owned entry
        if (typeof iterable === "object") {
            while (!(start in iterable)) {
                // deliberately late bound
                if (start >= iterable.length)
                    throw StopIteration;
                start += 1;
            }
        } else if (start >= iterable.length) {
            throw StopIteration;
        }
        var result = iterable[start];
        start += 1;
        return result;
    });
};

Iterator.cycle = function (cycle, times) {
    if (arguments.length < 2)
        times = Infinity;
    //cycle = Iterator(cycle).toArray();
    var next = function () {
        throw StopIteration;
    };
    return new Iterator(function () {
        var iteration;
        try {
            return next();
        } catch (exception) {
            if (isStopIteration(exception)) {
                if (times <= 0)
                    throw exception;
                times--;
                iteration = Iterator.iterate(cycle);
                next = iteration.next.bind(iteration);
                return next();
            } else {
                throw exception;
            }
        }
    });
};

Iterator.concat = function (iterators) {
    iterators = Iterator(iterators);
    var next = function () {
        throw StopIteration;
    };
    return new Iterator(function (){
        var iteration;
        try {
            return next();
        } catch (exception) {
            if (isStopIteration(exception)) {
                iteration = Iterator(iterators.next());
                next = iteration.next.bind(iteration);
                return next();
            } else {
                throw exception;
            }
        }
    });
};

Iterator.unzip = function (iterators) {
    iterators = Iterator(iterators).map(Iterator);
    if (iterators.length === 0)
        return new Iterator([]);
    return new Iterator(function () {
        var stopped;
        var result = iterators.map(function (iterator) {
            try {
                return iterator.next();
            } catch (exception) {
                if (isStopIteration(exception)) {
                    stopped = true;
                } else {
                    throw exception;
                }
            }
        });
        if (stopped) {
            throw StopIteration;
        }
        return result;
    });
};

Iterator.zip = function () {
    return Iterator.unzip(
        Array.prototype.slice.call(arguments)
    );
};

Iterator.chain = function () {
    return Iterator.concat(
        Array.prototype.slice.call(arguments)
    );
};

Iterator.range = function (start, stop, step) {
    if (arguments.length < 3) {
        step = 1;
    }
    if (arguments.length < 2) {
        stop = start;
        start = 0;
    }
    start = start || 0;
    step = step || 1;
    return new Iterator(function () {
        if (start >= stop)
            throw StopIteration;
        var result = start;
        start += step;
        return result;
    });
};

Iterator.count = function (start, step) {
    return Iterator.range(start, Infinity, step);
};

Iterator.repeat = function (value, times) {
    return new Iterator.range(times).mapIterator(function () {
        return value;
    });
};

// shim isStopIteration
if (typeof isStopIteration === "undefined") {
    global.isStopIteration = function (exception) {
        return Object.prototype.toString.call(exception) === "[object StopIteration]";
    };
}

// shim StopIteration
if (typeof StopIteration === "undefined") {
    global.StopIteration = {};
    Object.prototype.toString = (function (toString) {
        return function () {
            if (
                this === global.StopIteration ||
                this instanceof global.ReturnValue
            )
                return "[object StopIteration]";
            else
                return toString.call(this, arguments);
        };
    })(Object.prototype.toString);
}

// shim ReturnValue
if (typeof ReturnValue === "undefined") {
    global.ReturnValue = function ReturnValue(value) {
        this.message = "Iteration stopped with " + value;
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, ReturnValue);
        }
        if (!(this instanceof global.ReturnValue))
            return new global.ReturnValue(value);
        this.value = value;
    };
    ReturnValue.prototype = Error.prototype;
}


text:
class vlcsystem : public QObject
{
    Q_OBJECT
public:
    explicit vlcsystem(QObject *parent = 0);
    ~vlcsystem();

private:
    //VLC指针
    vlcpackage *vlcp;

    //视频窗口和列表窗口指针
    VLCPlayer *video;
    listDialog *list;

    bool islistopen;

public slots:
    //播放功能
    void setMedia(bool isfile, char *address);
    void play();
    void pauseresume(bool);
    void stop();
    void previous();
    void next();
    void setvolume(int);
    void videoclose();
    void listclose();

    //列表窗口操作
    void showList();
    void listFromVideo();
    void listPlay(bool, QString);
    void checklist();
};

#endif // SYSTEM_H


text:
package de.rwth.idsg.bikeman.ixsi.dispatcher;

import de.rwth.idsg.bikeman.ixsi.CommunicationContext;

/**
 * @author Sevket Goekay <goekay@dbis.rwth-aachen.de>
 * @since 26.09.2014
 */
public interface Dispatcher {
    void handle(CommunicationContext context);
}


text:
<?php

namespace Kdig\MediaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

use APY\DataGridBundle\Grid\Source\Entity;
use APY\DataGridBundle\Grid\Action\RowAction;
use APY\DataGridBundle\Grid\Action\MassAction;
use APY\DataGridBundle\Grid\Action\DeleteMassAction;
use APY\DataGridBundle\Grid\Column\ActionsColumn;
use APY\DataGridBundle\Grid\Export\PHPExcel2007Export;

use APY\BreadcrumbTrailBundle\Annotation\Breadcrumb;

use JMS\SecurityExtraBundle\Annotation\Secure;
/**
 * Bucket controller.
 *
 * @Route("/media")
 * @Breadcrumb("Media", route="media_index")
 */
class MediaController extends Controller
{
    /**
     * @Route("/", name="media_index")
     * @Breadcrumb("Media", route="media_index")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/list", name="media")
     * @Breadcrumb("List", route="media")
     * @Template()
     */
    public function listAction()
    {
        return array();
    }

    /**
     * @Route("/home/", name="media_home")
     * @Breadcrumb("Home", route="media_home")
     * @Secure(roles="ROLE_MEDIA , ROLE_ADMIN")
     * @Template()
     */
    public function homeAction()
    {
        return array();
    }

    /**
     * @Route("/upload/", name="media_new")
     * @Breadcrumb("Upload", route="media_new")
     * @Secure(roles="ROLE_MEDIA , ROLE_ADMIN")
     * @Template()
     */
    public function uploadAction()
    {

    }
    /**
     * @Route("/getmediafromquery", name="media_getmediafromquery")
     */
    public function getmediafromquery(Request $request)
    {
        $value = $request->get('q');
        $callback = $request->get('callback');
        $em = $this->getDoctrine()->getManager();
        $entities = $em->getRepository('KedigMediaBundle:Media')->findAllUseLike($value);//findBy(array('name'=>$value));
        $json = array();
        foreach ($entities as $member) {
            $json[] = array(
                'id'    =>  $member->getId(),
                'name'  =>  $member->getName(),
                'size'  =>  $member->getSize(),
                'mime'  =>  $member->getMime()
            );
        }

        $response = new Response();
        $response->headers->set('Content-Type', 'application/json');
        $result = array('results'=>$json);
        $result["total"] = 959;
        $response->setContent(json_encode($result));

        return $response;
    }
    /**
     * Finds and displays a Media entity with json.
     *
     * @Route("/showjson", name="media_showjson")
     */
    public function showjsonAction(Request $request)
    {
        $id = (int)$request->get('id');
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KedigMediaBundle:Media')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Media entity.');
        }

        $json = array();
        $json[] = array(
            'id'    =>  $entity->getId(),
            'name'  =>  $entity->getName(),
            'size'  =>  $entity->getSize(),
            'mime'  =>  $entity->getMime()
        );
        $response = new Response();
        //die(var_dump($json));
        $response->headers->set('Content-Type', 'application/json');
        $result = array('result'=>$json);
        $response->setContent(json_encode($json));

        return $response;
    }
}


text:
SharePoint list pagination demo.

## Usage
Open the project with Visual Studio and deploy it to your SharePoint environment.


text: Dictionary of UX terms.


text:
package net.ymate.module.security.handle;

import net.ymate.module.security.ComponentsMeta;
import net.ymate.module.security.ISecurity;
import net.ymate.platform.core.beans.IBeanHandler;

/**
 * 组件对象处理器
 *
 * @author 刘镇 (suninformation@163.com) on 17/2/20 下午6:21
 * @version 1.0
 */
public class ComponentsHandler implements IBeanHandler {

    public ComponentsHandler(ISecurity owner) {
    }

    public Object handle(Class<?> targetClass) throws Exception {
        ComponentsMeta.createIfNeed(targetClass);
        return null;
    }
}


text:
<?php

/**
 * Creational design pattern namespace.
 *
 * Creational design patterns are design patterns that deal with object creation
 * mechanisms, trying to cream objects in a manner suitable to the situation.
 * The basic form of object creation could result in design problems or added
 * complexity to the design. Creational design patterns solve this problem by
 * somehow controlling this object creation. Creational design patterns can be
 * further categoriezed into Object-creational and Class-creational patterns.
 * Where, Object-creational patterns deal with Object creation and
 * Class-creational deal with Class-initialization.
 *
 * @package    Nerd
 * @subpackage Design
 */
namespace Nerd\Design\Creational;

/**
 * Factory pattern trait
 *
 * The factory method pattern is an object-oriented design pattern to implement
 * the concept of factories. Like other creational patterns, it deals with the
 * problem of creating objects (products) without specifying the exact class
 * that will be created. The creation of an object often requires complex
 * processes not appropriate to include within the composing object. The
 * object's creation may lead to a significant duplication of code, may require
 * information not accessible to the composing object, may not provide a
 * sufficient level of abstraction, or may otherwise not be part of the
 * composing object's concerns. The factory method design pattern handles these
 * problems by defining a separate method for creating the objects, which
 * subclasses can then override the specific derived type of product that will
 * be created.
 *
 * Some of the processes required in the creation of an object include
 * determining which object to create, managing the lifetime of the object, and
 * managing specialized build-up and tear-down concerns of the object. Outside
 * the scope of design patterns, the term **factory method** can also refer to a
 * method of factory whose main purpose is creation of objects.
 *
 * __Note:__ Some classes may opt to not require the developer to specify a
 * driver during the Factory::instance() call. If they wish to specify a
 * default, the class must provide a `public static $defaultDriver` which will
 * be read during the `::instance()` call.
 *
 * __Note:__ Some derived classes may prefer to use some other variation of the
 * word driver (for example, gateway). If they wish to use a different form of
 * wording for it, they can specify a `public static $factoryType`, where the
 * keyword is used as the directory under the parent class.
 *
 * ## Usage
 *
 * To implement the factory method pattern into a class, simply include it:
 *
 *     class MyClass
 *     {
 *         use \Nerd\Design\Creational\Factory;
 *     }
 *
 * After you've created the parent class, you need to create at least one driver
 * type that can be loaded by the `::instance()` method, following this pattern:
 *
 *     namespace MyClass\Driver;
 *
 *     class Mydriver
 *     {
 *     }
 *
 * Once the driver is available, you can call the `::instance()` method to
 * create an instance of that driver.
 *
 *     $instance = MyClass::instance('mydriver');
 *
 * __Note:__ To follow the factory method specification, the first character of
 * a driver's class name must be uppercase. Additional uppercase letters in the
 * class name must be specified during the `::instance()` call if you choose
 * to use them. It is highly recommended to leave drivers all lowercase, except
 * for the first letter.
 *
 *     // Assuming the class name is 'MyDriver'
 *     $instance = MyClass::instance('MyDriver'); // Instancing becomes much more annoying
 *     $instance = MyClass::instance('myDriver'); // The first letter could also be lowercase
 *
 *     // Assuming the class name is 'Mydriver', this is a lot easier to work with. Highly recommended!
 *     $instance = MyClass::instance('mydriver');
 *
 * @package    Nerd
 * @subpackage Design
 */
trait Factory
{
    /**
     * The factory driver verb to utilize, defaults to 'Driver'
     *
     * @var    string
     */
    public static $factoryType = 'driver';

    /**
     * A default driver to provide, in the event non is specified. Defaults to
     * null.
     *
     * @var    string
     */
    public static $defaultDriver;

    /**
     * Construct a new instance to the factory driver, and pass along any
     * additionally provided arguments that were defined.
     *
     * @param    string           The factory driver to be loaded, otherwise `$defaultDriver` will be utilized if available
     * @param    mixed            Argument #n to be passed along to the driver
     * @return object                    An instance to the appropriate driver, determined by this factory
     * @throws \InvalidArgumentException This exception is thrown when a driver was not specified, and no `$defaultDriver` is available
     * @throws \OutOfBoundsException     This exception is thrown when the specified $driver, or $defaultDriver, does not exist and cannot be instantiated
     */
    final public static function instance($driver = null)
    {
        $class = get_called_class();
        $args  = func_get_args() and array_shift($args);

        if ($driver === null) {
            if (static::$defaultDriver === null) {
                throw new \InvalidArgumentException('A $driver was not specified during '.$class.'::instance(), and no $defaultDriver is available. Please specify the driver you wish to use');
            }

            $driver = static::$defaultDriver;
        }

        try {
            $instance = '\\'.$class.'\\'.\ucfirst(static::$factoryType).'\\'.\ucfirst($driver);
            $instance = new \ReflectionClass($instance);
            $instance = $instance->newInstanceArgs($args);
        } catch (\ReflectionException $e) {
            throw new \OutOfBoundsException($class.' driver type ['.$driver.'] cannot be instanciated, ensure the driver exists and has a __construct method.');
        }

        return $instance;
    }

    /**
     * Magic Static Caller
     *
     * This method enables convenient access to drivers as static methods, providing
     * better syntax.
     */
    public static function __callStatic($driver, $parameters)
    {
        $class = get_called_class() and array_unshift($parameters, $driver);

        return forward_static_call_array([$class, 'instance'], $parameters);
    }
}


text:
require 'bindata/lazy'

module BinData
  module AcceptedParametersPlugin
    # Mandatory parameters must be present when instantiating a data object.
    def mandatory_parameters(*args)
      accepted_parameters.mandatory(*args)
    end

    # Optional parameters may be present when instantiating a data object.
    def optional_parameters(*args)
      accepted_parameters.optional(*args)
    end

    # Default parameters can be overridden when instantiating a data object.
    def default_parameters(*args)
      accepted_parameters.default(*args)
    end

    # Mutually exclusive parameters may not all be present when
    # instantiating a data object.
    def mutually_exclusive_parameters(*args)
      accepted_parameters.mutually_exclusive(*args)
    end

    alias_method :mandatory_parameter, :mandatory_parameters
    alias_method :optional_parameter, :optional_parameters
    alias_method :default_parameter, :default_parameters

    def accepted_parameters #:nodoc:
      unless defined? @accepted_parameters
        ancestor_params = superclass.respond_to?(:accepted_parameters) ?
                            superclass.accepted_parameters : nil
        @accepted_parameters = AcceptedParameters.new(ancestor_params)
      end
      @accepted_parameters
    end

    # BinData objects accept parameters when initializing.  AcceptedParameters
    # allow a BinData class to declaratively identify accepted parameters as
    # mandatory, optional, default or mutually exclusive.
    class AcceptedParameters
      def initialize(ancestor_parameters = nil)
        if ancestor_parameters
          @mandatory = ancestor_parameters.mandatory.dup
          @optional  = ancestor_parameters.optional.dup
          @default   = ancestor_parameters.default.dup
          @mutually_exclusive = ancestor_parameters.mutually_exclusive.dup
        else
          @mandatory = []
          @optional  = []
          @default   = Hash.new
          @mutually_exclusive = []
        end
      end

      def mandatory(*args)
        if not args.empty?
          @mandatory.concat(to_syms(args))
          @mandatory.uniq!
        end
        @mandatory
      end

      def optional(*args)
        if not args.empty?
          @optional.concat(to_syms(args))
          @optional.uniq!
        end
        @optional
      end

      def default(args = nil)
        if args
          to_syms(args.keys)  # call for side effect of validating names
          args.each_pair do |param, value|
            @default[param.to_sym] = value
          end
        end
        @default
      end

      def mutually_exclusive(*args)
        arg1 = args.shift
        while not args.empty?
          args.each do |arg2|
            @mutually_exclusive.push([arg1.to_sym, arg2.to_sym])
            @mutually_exclusive.uniq!
          end
          arg1 = args.shift
        end
        @mutually_exclusive
      end

      def all
        (@mandatory + @optional + @default.keys).uniq
      end

      #---------------
      private

      def to_syms(args)
        syms = args.collect { |el| el.to_sym }
        ensure_valid_names(syms)
        syms
      end

      def ensure_valid_names(names)
        invalid_names = self.class.invalid_parameter_names
        names.each do |name|
          if invalid_names.include?(name)
            raise NameError.new("Rename parameter '#{name}' " +
                                "as it shadows an existing method.", name)
          end
        end
      end

      def self.invalid_parameter_names
        unless defined? @invalid_names
          all_names = LazyEvaluator.instance_methods(true) + Kernel.methods
          allowed_names = [:name, :type]
          invalid_names = (all_names - allowed_names).uniq
          @invalid_names = Hash[*invalid_names.collect { |key| [key.to_sym, true] }.flatten]
        end
        @invalid_names
      end
    end
  end
end


text:
import React, {Component} from 'react';

import styles from './../styles/score_btn.css';

class ScoreBtns extends Component {

  constructor(props) {
    super(props);

    //Binding functions
    this.touchdown = this.touchdown.bind(this);
    this.fieldgoal = this.fieldgoal.bind(this);
    this.safety = this.safety.bind(this);
    this.extraPoint = this.extraPoint.bind(this);
    this.extraPointTwo = this.extraPointTwo.bind(this);

    //State
    this.state = {
      extraPointAttempt: false
    }
  }

  //touchdown, 6 points
  touchdown(team) {
    this.props.action(6, team);
    this.setState({extraPointAttempt: true});
  }

  //field Goal, 3 points
  fieldgoal(team) {
    this.props.action(3, team)
  }

  //safety, 2 points
  safety(team) {
    this.props.action(2, team);
  }

  //extra point, 1 point
  extraPoint(team) {
    this.props.action(1, team);
    this.setState({extraPointAttempt: false});
  }

  //extraPoint, 2 points
  extraPointTwo(team) {
    this.props.action(2, team);
    this.setState({extraPointAttempt: false});
  }

  //enable or disable and add point

  render() {
    return (
      <div className="score-btn-container">
        <button className="score-touchdown" onClick={() => {this.touchdown(this.props.team)}}
                                                            disabled={this.state.extraPointAttempt}>Touchdown</button>
        <button className="score-field-goal" onClick={() => {this.fieldgoal(this.props.team)}}
                                                             disabled={this.state.extraPointAttempt}>Field Goal</button>
        <button className="score-safety" onClick={() => {this.safety(this.props.team)}}
                                                         disabled={this.state.extraPointAttempt}>Safety</button>
        <button className="score-extra-point-one" onClick={() => {this.extraPoint(this.props.team)}}
                                                                  disabled={!this.state.extraPointAttempt} >Extra Point (1)</button>
        <button className="score-extra-point-two" onClick={() => {this.extraPointTwo(this.props.team)}}
                                                                  disabled={!this.state.extraPointAttempt} >Extra Point (2)</button>
         <button className="score-extra-point-zero" onClick={() => {this.setState({extraPointAttempt: false})}} disabled={!this.state.extraPointAttempt}>Missed FG</button>
      </div>
    )
  };
}

export default ScoreBtns;


text:
/* Based on the template in Web Starter Kit :
https://github.com/google/web-starter-kit/blob/master/app/index.html
*/
const chromeFavicon = require('../images/chrome-ninja192-precomposed.png');
const appleFavicon = require('../images/apple-ninja152-precomposed.png');
const msFavicon = require('../images/ms-ninja144-precomposed.png');
const favicon = require('../images/favicon.png');

const metaAssets = () => {
  return [
    { charset: 'utf-8' },
    // Meta descriptions are commonly used on search engine result pages to
    // display preview snippets for a given page.
    { name: 'description', content: 'Your One-Stop solution for a full-stack universal Redux App' },
    // Setting IE=edge tells Internet Explorer to use the latest engine to
    //  render the page and execute Javascript
    { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' },
    // Using the viewport tag allows you to control the width and scaling of
    // the browser's viewport:
    // - include width=device-width to match the screen's width in
    // device-independent pixels
    // - include initial-scale=1 to establish 1:1 relationship between css pixels
    // and device-independent pixels
    // - ensure your page is accessible by not disabling user scaling.
    { name: 'viewport', content: 'width=device-width, initial-scale=1' },
    // Disable tap highlight on IE
    { name: 'msapplication-tap-highlight', content: 'no' },
    // Add to homescreen for Chrome on Android
    { name: 'mobile-web-app-capable', content: 'yes' },
    // Add to homescreen for Safari on IOS
    { name: 'apple-mobile-web-app-capable', content: 'yes' },
    { name: 'apple-mobile-web-app-status-bar-style', content: 'black' },
    { name: 'apple-mobile-web-app-title', content: 'reactGo' },
    // Tile icon for Win8 (144x144 + tile color)
    { name: 'msapplication-TileImage', content: msFavicon },
    { name: 'msapplication-TileColor', content: '#3372DF' }
  ];
};

const linkAssets = () => {
  const links = [
    // Add to homescreen for Chrome on Android
    { rel: 'icon', href: favicon },
    { rel: 'icon', sizes: '192x192', href: chromeFavicon },
    // Add to homescreen for Safari on IOS
    { rel: 'apple-touch-icon', sizes: '152x152', href: appleFavicon }
    // SEO: If your mobile URL is different from the desktop URL,
    // add a canonical link to the desktop page https://developers.google.com/webmasters/smartphone-sites/feature-phones
    // { 'rel': 'canonical', 'href': 'http://www.example.com/' }
  ];

  return links;
};

export const title = 'reactGo - just ship it';
export const meta = metaAssets();
export const link = linkAssets();


text:
package com.orasi.bluesource.features.manageDepartments;

import org.testng.ITestContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.orasi.bluesource.LoginPage;
import com.orasi.bluesource.commons.TopNavigationBar;
import com.orasi.bluesource.departmentsPage.ListingDepartmentsPage;
import com.orasi.bluesource.departmentsPage.ManageDepartmentPage;
import com.orasi.utils.Constants;
import com.orasi.utils.OrasiDriver;
import com.orasi.utils.Randomness;
import com.orasi.utils.TestEnvironment;
import com.orasi.utils.TestReporter;
import com.orasi.utils.dataProviders.ExcelDataProvider;

import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Parameter;
import ru.yandex.qatools.allure.annotations.Severity;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.allure.model.SeverityLevel;

public class TestManageDepartments  extends TestEnvironment {

    private String departmentName = "";
    private String subDepartment = "";
    private String mainDepartment = "Rural Testing";
    private OrasiDriver driver = null;
    @DataProvider(name = "dataScenario")
    public Object[][] scenarios() {
	return new ExcelDataProvider(Constants.BLUESOURCE_DATAPROVIDER_PATH + "TestAddNewDept.xlsx", "TestAddNewDept").getTestData();
    }

    @BeforeClass( alwaysRun=true)
    @Parameters({ "runLocation", "browserUnderTest", "browserVersion", "operatingSystem", "environment" })
    public void setup(String runLocation, String browserUnderTest, String browserVersion, String operatingSystem, String environment) {
	setApplicationUnderTest("Bluesource");
	setBrowserUnderTest(browserUnderTest);
	setBrowserVersion(browserVersion);
	setOperatingSystem(operatingSystem);
	setRunLocation(runLocation);
	setTestEnvironment(environment);
	//setThreadDriver(true);
    }

    @AfterClass( alwaysRun=true)
    public void closeSession(ITestContext test) {
	endTest(testName, test);
    }

    @Features("Manage Departments")
    @Stories("As an admin, I should be able to create a new department")
    @Severity(SeverityLevel.BLOCKER)
    @Title("ManageDepartments - Create Department")
    @Test(dataProvider = "dataScenario", groups = { "demo", "regression","manageDepartments", "qaOnly" })
    public void testAddDepartment(@Parameter String testScenario, @Parameter String role,
	    @Parameter String newDept) {

	   	setTestName("Manage Departments_" + getBrowserUnderTest() + "_" + getOperatingSystem());

	   	//Create a unique department name
		departmentName = newDept;
		if (departmentName.equalsIgnoreCase("RANDOM")){
			departmentName = Randomness.randomAlphaNumeric(11);
		}

		TestReporter.logScenario("This test creates a new department, verifies the department was created successfully,"
				+ " then deletes the department & verifies the department was deleted successfully");

		//Launch browser & create driver
		testStart(testName);
		driver = getDriver();

		// Login
		TestReporter.logStep("Login to Bluesource");
		LoginPage loginPage = new LoginPage(driver);
		TestReporter.assertTrue(loginPage.pageLoaded(),"Verify login page is displayed");
		loginPage.login(role);

		// Verify user is logged in
		TestReporter.logStep("Verify successful login");
		TopNavigationBar topNavigationBar = new TopNavigationBar(driver);
		TestReporter.assertTrue(topNavigationBar.isLoggedIn(), "Validate the user logged in successfully");

		// Navigate to the dept page
		TestReporter.logStep("Navigate to Departments page");
		topNavigationBar.clickAdminLink();
		topNavigationBar.clickDepartmentsLink();

		// Verify navigated to the dept page
		ListingDepartmentsPage deptPage = new ListingDepartmentsPage(driver);
		TestReporter.assertTrue(deptPage.pageLoaded(),"Verify list of departments page is displayed");

		// Add a new dept
		TestReporter.logStep("Add a new department: [" + departmentName + "]");
		deptPage.clickAddDeptLink();
		ManageDepartmentPage manageDepartmentPage = new ManageDepartmentPage(driver);
		manageDepartmentPage.createDepartment(departmentName);

		TestReporter.logStep("Verify successful department creation");
		// Verify the dept is added
		TestReporter.assertTrue(deptPage.isSuccessMsgDisplayed(), "Validate success message appears");

		// Verify the dept is displayed on the dept results table
		TestReporter.logStep("Verify new department displays in the list of departments");
		TestReporter.assertTrue(deptPage.searchTableByDept(departmentName), "Validate new department exists in table");

    }

    @Features("Manage Departments")
    @Stories("As an admin, I should be able to delete a department")
    @Severity(SeverityLevel.NORMAL)
    @Title("ManageDepartments - Delete Department")
    @Test(groups = { "demo", "regression","manageDepartments", "qaOnly" },dependsOnMethods= "testAddDepartment")
    public void testDeleteDepartment() {

		ListingDepartmentsPage deptPage = new ListingDepartmentsPage(driver);
		TestReporter.assertTrue(deptPage.pageLoaded(),"Verify list of departments page is displayed");

		// Delete the new dept
		TestReporter.logStep("Delete new department: [" + departmentName + "]");
		deptPage.deleteDepartment(departmentName, getBrowserUnderTest());

		// Verify the dept is deleted
		TestReporter.logStep("Verify new department is deleted");
		ListingDepartmentsPage refreshedPage = new ListingDepartmentsPage(driver);
		TestReporter.assertTrue(refreshedPage.isSuccessMsgDisplayed(), "Validate success message appears");

		//Logout
		TestReporter.logStep("Logout of application");
		TopNavigationBar topNavigationBar = new TopNavigationBar(driver);
		topNavigationBar.clickLogout();
    }

}