text:
<?php

declare(strict_types=1);

namespace Symplify\Autodiscovery\Tests\Yaml;

use Nette\Utils\FileSystem;
use Nette\Utils\Strings;
use Symfony\Component\Yaml\Yaml;
use Symplify\Autodiscovery\HttpKernel\AutodiscoveryKernel;
use Symplify\Autodiscovery\Yaml\ExplicitToAutodiscoveryConverter;
use Symplify\PackageBuilder\Tests\AbstractKernelTestCase;

final class ExplicitToAutodiscoveryConverterTest extends AbstractKernelTestCase
{
    /**
     * @var string
     */
    private const SPLIT_LINE = "#-----\n#";

    /**
     * @var ExplicitToAutodiscoveryConverter
     */
    private $explicitToAutodiscoveryConverter;

    protected function setUp(): void
    {
        $this->bootKernel(AutodiscoveryKernel::class);

        $this->explicitToAutodiscoveryConverter = static::$container->get(ExplicitToAutodiscoveryConverter::class);
    }

    public function test(): void
    {
        $this->doTestFile(__DIR__ . '/Fixture/short_tags.yaml', 2);
        $this->doTestFile(__DIR__ . '/Fixture/vendor.yaml', 2);
        $this->doTestFile(__DIR__ . '/Fixture/singly_implemented_interfaces.yaml', 2);
        $this->doTestFile(__DIR__ . '/Fixture/singly_implemented_interfaces_excluded.yaml', 2);
        $this->doTestFile(__DIR__ . '/Fixture/first.yaml', 2);
        $this->doTestFile(__DIR__ . '/Fixture/tags_with_values.yaml', 2);
        $this->doTestFile(__DIR__ . '/Fixture/shopsys.yaml', 3);
        $this->doTestFile(__DIR__ . '/Fixture/elasticr.yaml', 3);
        $this->doTestFile(__DIR__ . '/Fixture/untouch.yaml', 3);
        $this->doTestFile(__DIR__ . '/Fixture/existing_autodiscovery.yaml', 3);
        $this->doTestFile(__DIR__ . '/Fixture/blog_post_votruba.yaml', 1);
        $this->doTestFile(__DIR__ . '/Fixture/exclude.yaml', 4);
    }

    private function doTestFile(string $file, int $nestingLevel): void
    {
        $yamlContent = FileSystem::read($file);

        [$originalYamlContent, $expectedYamlContent] = $this->splitFile($yamlContent);

        $originalYaml = Yaml::parse($originalYamlContent);
        $expectedYaml = Yaml::parse($expectedYamlContent);

        $this->assertSame(
            $expectedYaml,
            $this->explicitToAutodiscoveryConverter->convert($originalYaml, $file, $nestingLevel, ''),
            'Caused by ' . $file
        );
    }

    /**
     * @return string[]
     */
    private function splitFile(string $yamlContent): array
    {
        if (Strings::match($yamlContent, self::SPLIT_LINE)) {
            return Strings::split($yamlContent, self::SPLIT_LINE);
        }

        return [$yamlContent, $yamlContent];
    }
}


text:
module DateValidators
  # Проверяет валидность даты/времени (конец раньше начала, пересечение, выход из промежутка...)
  extend ActiveSupport::Concern

  class EventValidator < ActiveModel::Validator
    def validate(record)
      if record.begin_datetime.blank? || record.end_datetime.blank?
        record.errors[:text] << 'Неправильная дата'
        return
      end

      if (record.end_datetime - record.begin_datetime).to_i / 60 < 15
        record.errors[:text] << 'Длительность < 15 минут'
      end
    end
  end

  class RoomValidator < ActiveModel::Validator
    def validate(record)
      if record.begin_work_time.blank? || record.end_work_time.blank?
        record.errors[:text] << 'Неправильная дата'
        return
      end

      if (record.end_work_time - record.begin_work_time).to_i / 60 < 15
        record.errors[:text] << 'Длительность < 15 минут'
      end

      if (record.end_work_time - record.begin_work_time).to_i / 3600 > 24
        record.errors[:text] << 'Длительность > 1 дня'
      end
    end
  end

  class OrderValidator < ActiveModel::Validator
    def validate(record)
      if record.begin_datetime.blank? || record.end_datetime.blank?
        record.errors[:text] << 'Неправильная дата'
        return
      end

      if (record.end_datetime - record.begin_datetime).to_i / 60 < 15
        record.errors[:text] << 'Длительность < 15 минут'
      end

      if record.event.blank?
        record.errors[:text] << 'Нет события'
        return
      end

      if record.end_datetime > record.event.end_datetime || record.begin_datetime < record.event.begin_datetime
        record.errors[:text] << 'Мимо события'
      end

      if record.room.blank?
        record.errors[:text] << 'Нет комнаты'
        return
      end

      if record.end_datetime.min + 60 * record.end_datetime.hour > record.room.end_work_time.min + 60 * record.room.end_work_time.hour ||
         record.begin_datetime.min + 60 * record.begin_datetime.hour < record.room.begin_work_time.min + 60 * record.room.begin_work_time.hour

        record.errors[:text] << 'Мимо комнаты'
      end

      record.room.orders.each do |order|
        if (record.begin_datetime < order.begin_datetime && record.end_datetime > order.begin_datetime) ||
           (record.begin_datetime < order.end_datetime && record.end_datetime > order.end_datetime) ||
           (record.begin_datetime >= order.begin_datetime && record.end_datetime <= order.end_datetime)

          record.errors[:text] << 'Пересечение событий'
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.googlecode.blaisemath.coordinate;

import com.googlecode.blaisemath.annotation.InvokedFromThread;
import com.googlecode.blaisemath.coordinate.CoordinateManager;

/**
 * Receives updates regarding the locations of a collection of objects. Handlers
 * should be aware that the update may be invoked from any thread.
 *
 * @param <S> type of object being located
 * @param <C> type of coordinate
 *
 * @author Elisha Peterson
 */
public interface CoordinateListener<S,C> {

    /**
     * Called when coordinates/points are added or changed in a {@link CoordinateManager}.
     * This method is called from the same thread that made the change.
     * @param evt description of what coordinates were added/removed/changed
     */
    @InvokedFromThread("unknown")
    void coordinatesChanged(CoordinateChangeEvent<S,C> evt);

}


text:
require_relative "../rails_helper.rb"

describe "TeeTime Features" do
  describe "TeeTime#index", type: :feature do

    before :each do
      User.create(
        username: "tylerB",
        email: "tyler@gmail.com",
        password: "123456",
        password_confirmation: "123456",
        pace: 4,
        experience: 6
      )
    end

    before :each do
      User.create(
        username: "jonS",
        email: "jon@gmail.com",
        password: "123456",
        password_confirmation: "123456",
        pace: 2,
        experience: 8
      )
    end

    before :each do
      Course.create(
        name: "Augusta National GC",
        description: "Home of the Masters",
        location: "Augusta, GA"
      )
    end

    let(:user) {
      User.first
    }

    let(:user2) {
      User.last
    }

    let(:course) {
      Course.first
    }

    it "displays with name and time" do
      tee_time1 = course.tee_times.build(time: "Dec 1 2098")
      tee_time2 = course.tee_times.build(time: "Dec 1 2099")
      tee_time1.user_tee_times.build(user_id: user.id)
      tee_time2.user_tee_times.build(user_id: user.id)
      course.save
      visit tee_times_path
      expect(page).to have_content(tee_time1.course.name)
      expect(page).to have_content("Dec 1, 2098")
      expect(page).to have_content("Dec 1, 2099")
    end

    it "displays with size, avg pace, and avg experience" do
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      tee_time.add_user(user)
      tee_time.add_user(user2)
      visit tee_times_path
      expect(page).to have_content("Avg. Pace: 3.0")
      expect(page).to have_content("Avg. Experience: 7.0")
      expect(page).to have_content("Size: 2/4")
    end

    it "defaults to displaying in chronological order" do
      tee_time1 = course.tee_times.build(time: "Dec 1 2099")
      tee_time2 = course.tee_times.build(time: "Dec 1 2097")
      tee_time3 = course.tee_times.build(time: "Dec 1 2098")
      tee_time1.user_tee_times.build(user_id: user.id)
      tee_time2.user_tee_times.build(user_id: user.id)
      tee_time3.user_tee_times.build(user_id: user.id)
      course.save
      visit tee_times_path
      expect(page.body.index(tee_time2.time.year.to_s)).to be < page.body.index(tee_time1.time.year.to_s)
    end

    it "does not display tee times that have already taken place" do
      tee_time1 = course.tee_times.build(time: Time.now)
      tee_time1.add_user(user)
      visit tee_times_path
      expect(page).to_not have_content(format_tee_time(tee_time1))
    end

    it "has links to tee_time show pages" do
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      tee_time.add_user(user)
      visit_signin
      user_login
      visit tee_times_path
      click_link tee_time.time.year
      expect(current_path).to eq(tee_time_path(tee_time))
    end

    it "has a link to TeeTime#new" do
      visit_signin
      user_login
      visit tee_times_path
      click_link "Create New Tee Time"
      expect(current_path).to eq(new_tee_time_path)
    end
  end

  # describe "TeeTime#new", type: :feature do
  #
  #   before :each do
  #     User.create(
  #       username: "tylerB",
  #       email: "tyler@gmail.com",
  #       password: "123456",
  #       password_confirmation: "123456"
  #     )
  #   end
  #
  #   before :each do
  #     Course.create(
  #       name: "Augusta National GC",
  #       description: "Home of the Masters",
  #       location: "Augusta, GA"
  #     )
  #   end
  #
  #   let(:user) {
  #     User.first
  #   }
  #
  #   let(:course) {
  #     Course.first
  #   }
  #
  #   it "allows a user to create a new TeeTime with an existing course" do
  #     visit_signin
  #     user_login
  #     visit new_user_tee_time_path(user)
  #     select("2018", from: "tee_time[time(1i)]")
  #     select(course.name, from: "tee_time[course_id]")
  #     click_button("Create Tee Time")
  #     expect(current_path).to eq(user_tee_time_path(user, TeeTime.first))
  #     expect(page).to have_content(course.name)
  #   end
  #
  #   it "allows a user to create a new TeeTime with a new course" do
  #     visit_signin
  #     user_login
  #     visit new_user_tee_time_path(user)
  #     select("2018", from: "tee_time[time(1i)]")
  #     fill_in("tee_time[course_attributes][name]", with: "new course")
  #     fill_in("tee_time[course_attributes][description]", with: "description")
  #     fill_in("tee_time[course_attributes][location]", with: "location")
  #     click_button("Create Tee Time")
  #     expect(current_path).to eq(user_tee_time_path(user, TeeTime.first))
  #     expect(page).to have_content("new course")
  #   end
  #
  #   it "handles selecting a guest count" do
  #     visit_signin
  #     user_login
  #     visit new_user_tee_time_path(user)
  #     select("2018", from: "tee_time[time(1i)]")
  #     select(course.name, from: "tee_time[course_id]")
  #     select('2', from: "tee_time[user_tee_times_attributes][0][guest_count]")
  #     click_button("Create Tee Time")
  #     expect(current_path).to eq(user_tee_time_path(user, TeeTime.first))
  #     expect(page).to have_content(course.name)
  #     expect(TeeTime.first.group_size).to eq(3)
  #   end
  # end

  describe "TeeTime#show", type: :feature do

    before :each do
      User.create(
        username: "tylerB",
        email: "tyler@gmail.com",
        password: "123456",
        password_confirmation: "123456"
      )
    end

    let(:user_attributes) do {
        username: "jonS",
        email: "jon@gmail.com",
        password: "123456",
        password_confirmation: "123456",
        pace: 8,
        experience: 7
      }
    end

    before :each do
      Course.create(
        name: "Augusta National GC",
        description: "Home of the Masters",
        location: "Augusta, GA"
      )
    end

    let(:user) {
      User.first
    }

    let(:course) {
      Course.first
    }

    let(:user_attributes2) {user_attributes.merge(username: "user2", email: "u2@g.c")}
    let(:user_attributes3) {user_attributes.merge(username: "user3", email: "u3@g.c")}
    let(:user_attributes4) {user_attributes.merge(username: "user4", email: "u4@g.c")}

    it "allows a user view a TeeTime" do
      visit_signin
      user_login
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      user_tee_time = tee_time.user_tee_times.build(user_id: user.id)
      course.save
      visit user_tee_time_path(user, tee_time)
      expect(page).to have_content(course.name)
      expect(page).to have_content(user.username)
      expect(page).to have_content(tee_time.time.year)
    end

    it "doesn't display a Join Tee Time button if full" do
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      tee_time.add_user(User.create(user_attributes))
      tee_time.add_user(User.create(user_attributes2))
      tee_time.add_user(User.create(user_attributes3))
      tee_time.add_user(User.create(user_attributes4))
      visit_signin
      user_login
      visit tee_time_path(tee_time)
      expect(page).to_not have_content("Join Tee Time")
    end

    it "doesn't display a Join Tee Time button if already joined" do
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      visit_signin
      user_login
      tee_time.add_user(current_user)
      visit tee_time_path(tee_time)
      expect(page).to_not have_content("Join Tee Time")
    end

  end
end


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>Assignment 2 -- Question 2</title><meta name="generator" content="MATLAB 8.6"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2017-08-22"><meta name="DC.source" content="myMainScript.m">

Assignment 2 -- Question 2

CS-663 Group-163059009,16305R011,16305R006

Contents

Intialization

Original Image

Bilateral Filtering

Spatial

Comparison: Tuned parameter

Observation

i) Comparison: (0.9 x tuned-sigma-space, tuned-sigma-intensity)

ii) Comparison: (tuned-sigma-space, 0.9 x tuned-sigma-intensity)

iii) Comparison: (tuned-sigma-space, 1.1 x tuned-sigma-intensity)

Intialization

Intializing the Color Map to 150 as max value of intensity in the image file is 100.

file='../data/barbara.mat';
cmap=150;
l = load(file);
img1=l.imageOrig;

Original Image

tic;
img=img1;
figure('name','Original Image');
imshow(img,colormap(gray(cmap)));
title('\fontsize{10}{\color{red}Original Image: Barbara}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);
pause(1);

Bilateral Filtering

myBilateralFiltering function take image, then it corrupt's the image by adding * Guassain nosie * with sigma as 5% of the intensity range . After that, it processes the noisy by the Bilateral filtering. For performing the Bilateral filtering in Spacial and Intensity region it use Gaussian Kernel with below configuration as input:

Sigma Space: 2

Sigma Intensity: 28

Window Size: 31x31

Output: Returns three thing respectively

Corruted/Noisy image

Filtered Image

 Spacial Mask

RMSD of Filtered and Original image.

tic
windowSize=31;
sigmaSpace=2;
sigmaIntensity=28;
[corrupted,filtered,spaceMask,rmsError]=myBilateralFiltering(img,cmap,windowSize,sigmaSpace,sigmaIntensity);
toc;

Elapsed time is 13.578242 seconds.

Spatial

Showing the Spatial mask with sigma-space as 2

figure('name','Spatial Mask');
imagesc(uint8(spaceMask*cmap)),colormap(gray(cmap)),colorbar();
title('\fontsize{10}{\color{magenta}Spatial}');
pause(2);

Comparison: Tuned parameter

Comparing the result of filtered image with corrupted and original image. RMSD is calculated between Filtered and Original image.

figure('name','Output - barbara','units','normalized','outerposition',[0 0 1 1]);
subplot(121);
imshow(corrupted,colormap(gray(cmap)));
title('\fontsize{10}{\color{red}Corrupted - Barbara}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);

subplot(122);
imshow(filtered,colormap(gray(cmap)));
title('\fontsize{10}{\color{magenta}Bilateral Filter - Barbara [sigma-space=2],sigma-intesity=28]}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);
pause(3);

% Printing result
fprintf('\nSigma Space:%d Sigma Intensity:%d  RMS of the image:%f\n',sigmaSpace,sigmaIntensity,rmsError);

Sigma Space:2 Sigma Intensity:28  RMS of the image:5.439130

Observation

While tuning sigam-space and sigma-Intesity below are few stats of the
tuning. If we reduce the sigma intensity by large amount as compare to
sigma-space the RMSD is increase drastically.

i) Comparison: (0.9 x tuned-sigma-space, tuned-sigma-intensity)

tic
windowSize=31;
sigmaSpace=0.9*2;
sigmaIntensity=28;
[corrupted,filtered,spaceMask,rmsError]=myBilateralFiltering(img,cmap,windowSize,sigmaSpace,sigmaIntensity);

figure('name','Output - barbara','units','normalized','outerposition',[0 0 1 1]);
subplot(121);
imshow(corrupted,colormap(gray(cmap)));
title('\fontsize{10}{\color{red}Corrupted - Barbara}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);

subplot(122);
imshow(filtered,colormap(gray(cmap)));
title('\fontsize{10}{\color{magenta}Bilateral Filter - Barbara [sigma-space=0.9*2],sigma-intesity=28]}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);
toc
pause(3);

% Printing result
fprintf('\nSigma Space:%d Sigma Intensity:%d  RMS of the image:%f\n',sigmaSpace,sigmaIntensity,rmsError);

Elapsed time is 13.546838 seconds.

Sigma Space:1.800000e+00 Sigma Intensity:28  RMS of the image:5.354155

ii) Comparison: (tuned-sigma-space, 0.9 x tuned-sigma-intensity)

tic
windowSize=31;
sigmaSpace=2;
sigmaIntensity=0.9*28;
[corrupted,filtered,spaceMask,rmsError]=myBilateralFiltering(img,cmap,windowSize,sigmaSpace,sigmaIntensity);

figure('name','Output - barbara','units','normalized','outerposition',[0 0 1 1]);
subplot(121);
imshow(corrupted,colormap(gray(cmap)));
title('\fontsize{10}{\color{red}Corrupted - Barbara}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);

subplot(122);
imshow(filtered,colormap(gray(cmap)));
title('\fontsize{10}{\color{magenta}Bilateral Filter - Barbara [sigma-space=2],sigma-intesity=0.9*28]}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);
toc
pause(3);

% Printing result
fprintf('\nSigma Space:%d Sigma Intensity:%d  RMS of the image:%f\n',sigmaSpace,sigmaIntensity,rmsError);

Elapsed time is 19.512797 seconds.

Sigma Space:2 Sigma Intensity:2.520000e+01  RMS of the image:5.196094

iii) Comparison: (tuned-sigma-space, 1.1 x tuned-sigma-intensity)

tic
windowSize=31;
sigmaSpace=2;
sigmaIntensity=1.1*28;
[corrupted,filtered,spaceMask,rmsError]=myBilateralFiltering(img,cmap,windowSize,sigmaSpace,sigmaIntensity);

figure('name','Output - barbara','units','normalized','outerposition',[0 0 1 1]);
subplot(121);
imshow(corrupted,colormap(gray(cmap)));
title('\fontsize{10}{\color{red}Corrupted - Barbara}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);

subplot(122);
imshow(filtered,colormap(gray(cmap)));
title('\fontsize{10}{\color{magenta}Bilateral Filter - Barbara [sigma-space=2,sigma-intesity=1.1*28]}');
axis tight,axis on;
o1 = get(gca, 'Position');
colorbar(),set(gca, 'Position', o1);
toc
pause(3);

% Printing result
fprintf('\nSigma Space:%d Sigma Intensity:%d  RMS of the image:%f\n',sigmaSpace,sigmaIntensity,rmsError);

Elapsed time is 13.386590 seconds.

Sigma Space:2 Sigma Intensity:3.080000e+01  RMS of the image:5.658619

Published with MATLAB® R2015b


text:
unless Object.const_defined?('DemoVar')
  fail RuntimeError, "This is NOT a stand alone script. This script is called from 'demo.rb'. "
end

module DemoManager
  @@progress    = TkVariable.new(false)
  @@status      = TkVariable.new('Compute in progress...')
  @@homogeneous = TkVariable.new(false)
  @@constw      = TkVariable.new
  @@afterobj    = nil

  def self.create(nb)
    frame = nb.insert('end', 'demoManager', :text=>'Manager')

    topf = TkFrame.new(frame)
    titf1 = Tk::BWidget::TitleFrame.new(topf, :text=>"MainFrame")
    titf2 = Tk::BWidget::TitleFrame.new(topf, :text=>"NoteBook")
    titf3 = Tk::BWidget::TitleFrame.new(frame, :text=>"Paned & ScrolledWindow")

    _mainframe(titf1.get_frame)
    _notebook(titf2.get_frame)
    _paned(titf3.get_frame)

    Tk.pack(titf1, titf2, :padx=>4, :side=>:left, :fill=>:both, :expand=>true)
    Tk.pack(topf, :fill=>:x, :pady=>2)
    Tk.pack(titf3, :pady=>2, :padx=>4, :fill=>:both, :expand=>true)

    frame
  end

  def self._mainframe(parent)
    labf1 = Tk::BWidget::LabelFrame.new(parent, :text=>'Toolbar',
                                        :side=>:top, :anchor=>:w,
                                        :relief=>:sunken, :borderwidth=>2)
    subf = labf1.get_frame
    chk1 = TkCheckbutton.new(subf, :text=>'View toolbar 1',
                             :variable=>DemoVar.toolbar1,
                             :command=>proc{
                               DemoVar.mainframe.show_toolbar(
                                  0, DemoVar.toolbar1.value
                               )
                             })
    chk2 = TkCheckbutton.new(subf, :text=>'View toolbar 2',
                             :variable=>DemoVar.toolbar2,
                             :command=>proc{
                               DemoVar.mainframe.show_toolbar(
                                  1, DemoVar.toolbar2.value
                               )
                             })

    Tk.pack(chk1, chk2, :anchor=>:w, :fill=>:x)
    labf1.pack(:fill=>:both)

    labf2 = Tk::BWidget::LabelFrame.new(parent, :text=>'Status bar',
                                        :side=>:top, :anchor=>:w,
                                        :relief=>:sunken, :borderwidth=>2)
    subf = labf2.get_frame
    chk1 = TkCheckbutton.new(subf, :text=>"Show Progress\nindicator",
                             :justify=>:left, :variable=>@@progress,
                             :command=>proc{ _show_progress })
    chk1.pack(:anchor=>:w, :fill=>:x)

    Tk.pack(labf1, labf2, :side=>:left, :padx=>4, :fill=>:both)
  end

  def self._notebook(parent)
    TkCheckbutton.new(parent, :text=>'Homogeneous label',
                      :variable=>@@homogeneous,
                      :command=>proc{
                        DemoVar.notebook[:homogeneous] = @@homogeneous.value
                      }).pack(:side=>:left, :anchor=>:n, :fill=>:x)
  end

  def self._paned(parent)
    pw1   = Tk::BWidget::PanedWindow.new(parent, :side=>:top)
    pane  = pw1.add(:minsize=>100)

    pw2   = Tk::BWidget::PanedWindow.new(pane, :side=>:left)
    pane1 = pw2.add(:minsize=>100)
    pane2 = pw2.add(:minsize=>100)

    pane3 = pw1.add(:minsize=>100)

    [pane1, pane2].each{|pane|
      sw = Tk::BWidget::ScrolledWindow.new(pane)
      lb = TkListbox.new(sw, :height=>8, :width=>20, :highlightthickness=>0)
      (1..8).each{|i| lb.insert('end', "Value #{i}") }
      sw.set_widget(lb)
      sw.pack(:fill=>:both, :expand=>true)
    }

    sw = Tk::BWidget::ScrolledWindow.new(pane3, :relief=>:sunken,
                                         :borderwidth=>2)
    sf = Tk::BWidget::ScrollableFrame.new(sw)
    sw.set_widget(sf)
    subf = sf.get_frame
    lab = TkLabel.new(subf, :text=>'This is a ScrollableFrame')
    chk = TkCheckbutton.new(subf, :text=>'Constrained with',
                            :variable=>@@constw, :command=>proc{
                              sf['constrainedwidth'] = @@constw.value
                            })
    lab.pack
    chk.pack(:anchor=>:w)
    chk.bind('FocusIn', proc{sf.see(chk)})
    (0..20).each{|i|
      ent = TkEntry.new(subf, :width=>50).pack(:fill=>:x, :pady=>4)
      ent.bind('FocusIn', proc{sf.see(ent)})
      ent.insert('end', "Text field #{i}")
    }

    Tk.pack(sw, pw2, pw1, :fill=>:both, :expand=>true)
  end

  def self._show_progress
    unless @@afterobj
      @@afterobj = TkTimer.new(30, -1, proc{_update_progress})
    end
    if @@progress.bool
      DemoVar.status.value = 'Compute in progress...'
      DemoVar.prgindic.value = 0
      DemoVar.mainframe.show_statusbar(:progression)
      @@afterobj.start unless @@afterobj.running?
    else
      DemoVar.status.value = ''
      DemoVar.mainframe.show_statusbar(:status)
      @@afterobj.stop
    end
  end

  def self._update_progress
    if @@progress.bool
      if DemoVar.prgindic.numeric < 100
        DemoVar.prgindic.numeric += 5
      else
        @@progress.value = false
        DemoVar.mainframe.show_statusbar(:status)
        DemoVar.status.value = 'Done'
        @@afterobj.stop
        Tk.after(500, proc{ DemoVar.status.value = '' })
      end
    else
      @@afterobj.stop
    end
  end

end


text:
name: Bug report
about: Create a report to help us improve
title: "[KiPart BUG]"
labels: bug
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**
 - OS [type & version]
 - Python version
 - KiPart version [e.g. 0.1.22]

**Additional context**
Add any other context about the problem here.


text:
import furl
import threading

from django.utils import timezone

from website import mails
from website.models import PreprintProvider
from website.settings import DOMAIN, CAMPAIGN_REFRESH_THRESHOLD
from website.util.time import throttle_period_expired

mutex = threading.Lock()
CAMPAIGNS = None
CAMPAIGNS_LAST_REFRESHED = timezone.now()

def get_campaigns():

    global CAMPAIGNS
    global CAMPAIGNS_LAST_REFRESHED

    if not CAMPAIGNS or (not mutex.locked() and throttle_period_expired(CAMPAIGNS_LAST_REFRESHED, CAMPAIGN_REFRESH_THRESHOLD)):
        with mutex:
            # Native campaigns: PREREG and ERPC
            newest_campaigns = {
                'prereg': {
                    'system_tag': 'prereg_challenge_campaign',
                    'redirect_url': furl.furl(DOMAIN).add(path='prereg/').url,
                    'confirmation_email_template': mails.CONFIRM_EMAIL_PREREG,
                    'login_type': 'native',
                },
                'erpc': {
                    'system_tag': 'erp_challenge_campaign',
                    'redirect_url': furl.furl(DOMAIN).add(path='erpc/').url,
                    'confirmation_email_template': mails.CONFIRM_EMAIL_ERPC,
                    'login_type': 'native',
                },
            }

            # Institution Login
            newest_campaigns.update({
                'institution': {
                    'system_tag': 'institution_campaign',
                    'redirect_url': '',
                    'login_type': 'institution',
                },
            })

            # Proxy campaigns: Preprints, both OSF and branded ones
            preprint_providers = PreprintProvider.objects.all()
            for provider in preprint_providers:
                if provider._id == 'osf':
                    template = 'osf'
                    name = 'OSF'
                    url_path = 'preprints/'
                else:
                    template = 'branded'
                    name = provider.name
                    url_path = 'preprints/{}'.format(provider._id)
                campaign = '{}-preprints'.format(provider._id)
                system_tag = '{}_preprints'.format(provider._id)
                newest_campaigns.update({
                    campaign: {
                        'system_tag': system_tag,
                        'redirect_url': furl.furl(DOMAIN).add(path=url_path).url,
                        'confirmation_email_template': mails.CONFIRM_EMAIL_PREPRINTS(template, name),
                        'login_type': 'proxy',
                        'provider': name,
                    }
                })

            CAMPAIGNS = newest_campaigns
            CAMPAIGNS_LAST_REFRESHED = timezone.now()

    return CAMPAIGNS

def system_tag_for_campaign(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('system_tag')
    return None

def email_template_for_campaign(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('confirmation_email_template')
    return None

def campaign_for_user(user):
    campaigns = get_campaigns()
    for campaign, config in campaigns.items():
        if config.get('system_tag') in user.system_tags:
            return campaign
    return None

def is_institution_login(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('login_type') == 'institution'
    return None

def is_native_login(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('login_type') == 'native'
    return None

def is_proxy_login(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('login_type') == 'proxy'
    return None

def get_service_provider(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('provider')
    return None

def campaign_url_for(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('redirect_url')
    return None


text:
.focusField {
	background: white;
	color: black;
}

.idleField {
	background: #EEE;
	color: black;
}

.defaultIdleField {
	background: #EEE;
	color: #5F5F5F;
}


text:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class MyZone_viewinfo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ////Session["User"] = "08122387";
        //string User = Session["User"].ToString();
        //SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MemManaSysConnectionString"].ConnectionString);
        //// conn.ConnectionString=@System.Configuration.ConfigurationManager.ConnectionStrings["MemManaSysConnectionString"].ConnectionString;
        //string sqlstring = "select * from member where mno='" + User + "'";
        //string sqlstring2 = "select * from contact where mno='" + User + "'";
        //SqlDataAdapter sda = new SqlDataAdapter(sqlstring, conn);
        //SqlDataAdapter sda2 = new SqlDataAdapter(sqlstring2, conn);
        //DataSet ds = new DataSet();
        //DataSet ds2 = new DataSet();
        //sda.Fill(ds);
        //sda2.Fill(ds2);
        //if (ds.Tables[0].Rows.Count != 0)
        //{
        //    Label1.Text = ds.Tables[0].Rows[0]["mno"].ToString();
        //    Label2.Text = ds.Tables[0].Rows[0]["mname"].ToString();
        //    Label3.Text = ds.Tables[0].Rows[0]["msex"].ToString();
        //    Label4.Text = ds.Tables[0].Rows[0]["mage"].ToString();
        //    Label5.Text = ds.Tables[0].Rows[0]["coll"].ToString();
        //    Label6.Text = ds.Tables[0].Rows[0]["prof"].ToString();
        //    Label7.Text = ds.Tables[0].Rows[0]["department"].ToString();
        //    Label8.Text = ds.Tables[0].Rows[0]["ismoney"].ToString();

        //}
        //if (ds2.Tables[0].Rows.Count != 0)
        //{
        //    Label9.Text = ds2.Tables[0].Rows[0]["phone"].ToString();
        //    Label10.Text = ds2.Tables[0].Rows[0]["qq"].ToString();
        //    Label11.Text = ds2.Tables[0].Rows[0]["email"].ToString();
        //    Label12.Text = ds2.Tables[0].Rows[0]["bbs_user"].ToString();
        //    Label13.Text = ds2.Tables[0].Rows[0]["zhifubao"].ToString();
        //    if (Label12.Text == "")
        //        Label12.Text = "暂无";
        //    if (Label13.Text == "")
        //        Label13.Text = "暂无";

        //}
    }
}


text:
var should = require('should');
var Client = require('../../../client/v1');
var Promise = require('bluebird');
var path = require('path');
var mkdirp = require('mkdirp');
var inquirer = require('inquirer');
var _ = require('underscore');
var fs = require('fs');

describe("`Timeline` class", function() {

    var feed, session;

    before(function() {
        session = require('../../run').session;
        feed = new Client.Feed.Timeline(session)
    })

    it("should not be problem to get timeline feed", function(done) {
        var originalCursor = feed.getCursor();
        feed.get().then(function(media) {
            media.should.not.be.empty();
            _.each(media, function(medium) {
                medium.should.be.instanceOf(Client.Media)
            })
            should(originalCursor).should.not.equal(feed.getCursor())
            feed.moreAvailable.should.be.Boolean();
            feed.moreAvailable.should.equal(true);
            done()
        })
    })

})


text:
FROM jupyter/datascience-notebook

RUN apt-get update
RUN apt-get install openssh-client -y # Needed for Versioned unit tests to pass
RUN git clone http://github.com/scidash/sciunit
WORKDIR sciunit
RUN pip install -e .
RUN git clone -b cosmosuite http://github.com/scidash/scidash ../scidash
USER $NB_USER
RUN sh test.sh


text:
require 'rspec/core/formatters/documentation_formatter'
require 'rspec/instafail'

class DocumentationInstafail < RSpec::Core::Formatters::DocumentationFormatter
  def example_failed(example)
    super(example)
    # instafail.example_failed(example)
  end

  def instafail
    @instafail ||= ModifiedInstafail.new(output)
  end

  class ModifiedInstafail < RSpec::Instafail

    def dump_backtrace(example)
      exception = example.execution_result[:exception]
      format_backtrace(exception.backtrace, example).each do |backtrace_info|
        path = File.expand_path backtrace_info[%r{(\A.+?):\d}, 1] rescue binding.pry
        if path.start_with?(RAILS_ROOT.to_s)
          output.puts detail_color("#{long_padding}# #{backtrace_info}")
        else
          output.puts default_color("#{long_padding}# #{backtrace_info}")
        end
      end
    end

  end

end


text:
<?php

namespace app\models\queries;

/**
 * This is the ActiveQuery class for [[\app\models\Lang]].
 *
 * @see \app\models\Lang
 */
class Lang extends \yii\db\ActiveQuery
{
    public function active()
    {
        $this->andWhere('[[active]]=1');
        return $this;
    }

    /**
     * @inheritdoc
     * @return \app\models\Lang[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return \app\models\Lang|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }

    /**
     * @inheritdoc
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getDefault()
    {
        return parent::where('`default` = :default', [':default' => 1])->one();
    }

    /**
     * @inheritdoc
     * @param $url
     * @return array|null|\yii\db\ActiveRecord
     */
    public function byUrl($url)
    {
        return parent::where('url = :url', [':url' => $url])->one();
    }

    public function allWithoutCurrent($current_id)
    {
        return parent::where('id != :current_id', [':current_id' => $current_id])->all();
    }
}


text:
import crypto from 'crypto'
import fs from 'fs'

export function getHash(filePath: string): Promise<string> {
  const hash = crypto.createHash('sha256')
  const input = fs.createReadStream(filePath)
  return new Promise((resolve) => {
    input.on('readable', () => {
      const data = input.read()
      if (data) {
        hash.update(data)
      } else {
        resolve(hash.digest('hex'))
      }
    })
  })
}


text:
/* © 2014 the PBNF Authors under the MIT license. See AUTHORS for the list of authors.*/

/**
 * \file pq.h
 *
 *
 *
 * \author Ethan Burns
 * \date 2009-02-10
 */

#if !defined(_PRIORITY_QUEUE_H_)
#define _PRIORITY_QUEUE_H_

#include <assert.h>
//#define PQ_DEBUG

#include <iostream>
#include <list>
using namespace std;

/**
 * A template priority queue class.
 *
 * The PQOps class must have the following methods:
 *
 *   int operator()(Elem *a, Elem *b);
 *
 *       -- returns true if a is a predecessor of b.  When used to
 *          determine where a node should go in the queue's order, the
 *          first argument will always be the new element.  This
 *          guarentee allows the queue to perform FIFO tie-breaking.
 *          Where the prec operator is not determining ordering in the
 *          queue (when determining the 'max child' for example) there
 *          is no guarentee).
 *
 *   int get_value(Elem *e);
 *
 *       -- get the value of the element (for debugging only).
 *
 *   void operator()(Elem *e, int i);
 *
 *       -- set the index of element e to the value i.
 *
 *   int operator()(Elem *e);
 *
 *       -- get the index of element e.
 *
 */
template<class Elem, class PQOps> class PriorityQueue {
public:
	PriorityQueue(void);
	~PriorityQueue(void);
	void add(Elem e);
	Elem take(void);
	void remove(int i);
	Elem front(void);
	bool empty(void);
	void reset(void);
	void resort(void);

	list<Elem> *to_list(void);

	/** When the value of an element gets better (closer to the
	 * front of the queue) this function re-sifts it. */
	void see_update(int i);

	int get_fill() { return fill; }
	Elem get_elem(int i) { assert(i < fill); return heap[i]; }

	/* only for testing purposes. */
	Elem *get_vec() { return heap; }

	bool heap_holds(int, int);
	bool indexes_match(void);

private:
	int left_of(int i);
	int right_of(int i);
	int parent_of(int i);
	bool is_leaf(int i);
	int max_child(int i);
	int sift_up(int i);
	int try_push(Elem e, int i);
	int sift_down(Elem e, int i);

	int fill;
	int size;
	Elem* heap;
	PQOps pred;
	PQOps set_index;
};

/**
 * Create a new priority queue.
 */
template<class Elem, class PQOps>
	PriorityQueue<Elem, PQOps>::PriorityQueue(void)
{
	heap = NULL;
	reset();
}

/**
 * Destroy a PQ.
 */
template<class Elem, class PQOps>
	PriorityQueue<Elem, PQOps>::~PriorityQueue(void)
{
	if (heap)
		delete[] heap;
}

/**
 * Get the index of the element to the left of the element [i] in the
 * tree.
 */
template<class Elem, class PQOps>
	 int PriorityQueue<Elem, PQOps>::left_of(int i)
{
	return 2 * i + 1;
}

/**
 * Get the index of the element to the right of the element [i] in the
 * tree.
 */
template<class Elem, class PQOps>
	 int PriorityQueue<Elem, PQOps>::right_of(int i)
{
	return 2 * i + 2;
}

/**
 * Get the index of the element that is the parent of element [i] in
 * the tree.
 */
template<class Elem, class PQOps>
	int PriorityQueue<Elem, PQOps>::parent_of(int i)
{
	return (i - 1) / 2;
}

/**
 * Predicate that tests if element [i] is a leaf node.
 */
template<class Elem, class PQOps>
	bool PriorityQueue<Elem, PQOps>::is_leaf(int i)
{
	return left_of(i) >= fill && right_of(i) >= fill;
}

/**
 * Get the index of the max valued child of element [i].  Element [i]
 * must not be a leaf.
 */
template<class Elem, class PQOps>
	int PriorityQueue<Elem, PQOps>::max_child(int i)
{
	int right = right_of(i);
	int left = left_of(i);
	assert(!is_leaf(i));
	if (left < fill && right < fill) {
		if (pred(heap[right], heap[left]))
			return right;
		else
			return left;
	} else if (left < fill) {
		return left;
	} else {
		return right;
	}
	assert(1); /* Should never reach here. */
	return -1;
}

/**
 * Sift element [i] up the tree.
 *
 * \return The new index of the element that was initially at location [i].
 *
 * \note The index of [i] must be reset explicitly by the caller after
 *       this function is called.
 */
template<class Elem, class PQOps>
	 int PriorityQueue<Elem, PQOps>::sift_up(int i)
{
	int p_ind = parent_of(i);
	Elem parent = heap[p_ind];
	Elem e = heap[i];
	while (i > 0 && pred(e, parent)) {
		heap[i] = parent;
		set_index(parent, i);
		assert(i < fill);
		i = p_ind;
		p_ind = parent_of(i);
		parent = heap[p_ind];
	}
	heap[i] = e;
	return i;
}

/**
 * Tries to push an element down the tree.
 *
 * \return The new index is returned.
 *
 * \note This function does not set the new index of the element.
 */
template<class Elem, class PQOps>
	int PriorityQueue<Elem, PQOps>::try_push(Elem e, int i)
{
	assert(i != -1);
	int child_i = left_of(i);
	if (child_i < fill) {
		Elem child = heap[child_i];
		int right_i = right_of(i);
		if (right_i < fill) {
			Elem right = heap[right_i];
			if (pred(right, child)) {
				child = right;
				child_i = right_i;
			}
		}
		if (pred(e, child)) {
			return i;
		} else {
			heap[i] = child;
			set_index(child, i);
			assert(i < fill);
			return try_push(e, child_i);
		}
	} else {
		return i;
	}
}

/**
 * Push an element down the tree, and set its new index.
 *
 * \return The new index.
 */
template<class Elem, class PQOps>
	int  PriorityQueue<Elem, PQOps>::sift_down(Elem e, int i)
{
	i = try_push(e, i);
	assert(i < fill);
	heap[i] = e;
	set_index(e, i);
	assert(i < fill);

	return i;
}

/**
 * Add an element to the priority queue.
 */
template<class Elem, class PQOps>
	void PriorityQueue<Elem, PQOps>::add(Elem e)
{
	if (size <= fill) {
		size = size * 2;
		Elem *new_heap = new Elem[size];
		for (int i = 0; i < fill; i += 1)
			new_heap[i] = heap[i];
		Elem *heap_tmp = heap;
		heap = new_heap;
		delete[] heap_tmp;
	}

	heap[fill] = e;
	fill += 1;
	int i = sift_up(fill - 1);
	set_index(e, i);
	assert(i < fill);
#if defined(PQ_DEBUG)
	assert(indexes_match());
	assert(heap_holds(0, fill - 1));
#endif
}

/**
 * Take and return the front element of the priority queue.
 */
template<class Elem, class PQOps>
	Elem PriorityQueue<Elem, PQOps>::take(void)
{
	Elem e;

	if (fill <= 0)
		return NULL;

	e = heap[0];
	set_index(e, -1);

	heap[0] = heap[fill - 1];
	heap[fill - 1] = NULL;
	fill -= 1;
	if (fill > 0)
		sift_down(heap[0], 0);

#if defined(PQ_DEBUG)
	assert(indexes_match());
	assert(heap_holds(0, fill - 1));
#endif

	return e;
}

/**
 * Remove the element at index i.
 */
template<class Elem, class PQOps>
	void PriorityQueue<Elem, PQOps>::remove(int i)
{
	assert(i < fill);
	set_index(heap[i], -1);
	heap[i] = heap[fill - 1];
	heap[fill - 1] = NULL;
	fill = fill - 1;
	if (i < fill) {
		Elem e = heap[i];
		set_index(e, i);
		sift_down(e, sift_up(i));
	}

#if defined(PQ_DEBUG)
	assert(indexes_match());
	assert(heap_holds(0, fill - 1));
#endif
}

/**
 * Re-sort a single element in the PQ whose value has changed.
 */
template<class Elem, class PQOps>
	void PriorityQueue<Elem, PQOps>::see_update(int i)
{
	assert(i >= 0);
	assert(i < fill);
	Elem e = heap[i];
	int ind = sift_up(i);
	sift_down(e, ind);

#if defined(PQ_DEBUG)
	assert(indexes_match());
	assert(heap_holds(0, fill - 1));
#endif
}

/**
 * Look at the front element of the priority queue.
 */
template<class Elem, class PQOps>
	Elem PriorityQueue<Elem, PQOps>::front(void)
{
	if (fill <= 0)
		return NULL;

	return heap[0];
}

/**
 * Test for empty.
 */
template<class Elem, class PQOps>
	 bool PriorityQueue<Elem, PQOps>::empty(void)
{
	return fill <= 0;
}

/**
 * Remove all elements (if any), reset fill and the default heap size.
 */
template<class Elem, class PQOps>
	void PriorityQueue<Elem, PQOps>::reset(void)
{
	if (heap) {
		for (int i = 0; i < fill; i += 1)
			set_index(heap[i], -1);
	}

	fill = 0;
	size = 100;
	if (heap)
		delete[] heap;
	heap = new Elem[size];
}

/**
 * Diagnosis function for making sure that the heap property holds.
 */
template<class Elem, class PQOps>
	bool PriorityQueue<Elem, PQOps>::heap_holds(int ind_start, int ind_end)
{
	for (int i = ind_start; i <= ind_end; i += 1) {
		int right = right_of(i);
		int left = left_of(i);
		if (right < fill && pred(heap[right], heap[i])) {
			std::cerr << "fill: " << fill
				  << " right: " << right
				  << " val: " << pred.get_value(heap[right])
				  << " i: " << i
				  << " val: " << pred.get_value(heap[i])
				  << std::endl;
			return false;
		}
		if (left < fill && pred(heap[left], heap[i])) {
			std::cerr << "fill: " << fill
				  <<  " left: " << left
				  << " val: " << pred.get_value(heap[left])
				  << " i: " << i
				  << " val: " << pred.get_value(heap[i])
				  << std::endl;
			return false;
		}
	}

	return true;
}

template<class Elem, class PQOps>
	bool PriorityQueue<Elem, PQOps>::indexes_match(void)
{
	for (int i = 0; i < fill; i += 1) {
		if (pred(heap[i]) != i) {
			std::cerr << "ind=" << pred(heap[i])
				  << " should be: " << i
				  << std::endl;
			return false;
		}
	}
	return true;
}

/**
 * Run through the priority queue and resort all of its elements.
 *
 * This function should be called if *all* of the elements in the
 * priority queue have changed in value.
 */
template<class Elem, class PQOps>
	void PriorityQueue<Elem, PQOps>::resort(void)
{
	int old_fill = fill;
	Elem *old_heap = heap;

	heap = new Elem[size];
	fill = 0;

	for (int i = 0; i < old_fill; i += 1)
		add(old_heap[i]);

	delete [] old_heap;

	assert(heap_holds(0, fill - 1));
}

/**
 * Get a list of all of the PQ entries.  This list is in no *
 * particular order.
 */
template<class Elem, class PQOps>
	list<Elem> *PriorityQueue<Elem, PQOps>::to_list(void)
{
	list<Elem> *lst = new list<Elem>();

	if (!lst)
		return NULL;

	for (int i = 0; i < fill; i += 1)
		lst->push_front(heap[i]);

	return lst;
}

#endif /* !_PRIORITY_QUEUE_H_ */


text:
package io.hekate.messaging.operation;

import io.hekate.cluster.ClusterNode;
import io.hekate.messaging.MessagingChannel;
import java.util.List;
import java.util.Map;

/**
 * Result of a {@link Broadcast} operation.
 *
 * @param <T> Base type of broadcast message.
 *
 * @see MessagingChannel#newBroadcast(Object)
 */
public interface BroadcastResult<T> {
    /**
     * Returns the original message object that was submitted to the cluster.
     *
     * @return Original message.
     */
    T message();

    /**
     * Returns the broadcast operation participants. Returns an empty list if there were no suitable nodes in the cluster to perform the
     * operation.
     *
     * @return Cluster nodes that participated in the broadcast operation or an empty list if there were no suitable nodes in the cluster to
     * perform the operation.
     */
    List<ClusterNode> nodes();

    /**
     * Returns the map of cluster nodes and errors that happened while trying to communicate with these nodes. Returns an empty map if
     * there were no communication failures.
     *
     * @return Map of nodes and their corresponding failures. Returns an empty map if there were no communication failures.
     *
     * @see #errorOf(ClusterNode)
     */
    Map<ClusterNode, Throwable> errors();

    /**
     * Returns {@code true} if broadcast completed successfully without any {@link #errors() errors}.
     *
     * @return {@code true} if broadcast completed successfully without any errors.
     *
     * @see #errors()
     */
    default boolean isSuccess() {
        Map<ClusterNode, Throwable> errors = errors();

        return errors == null || errors.isEmpty();
    }

    /**
     * Returns {@code true} if there was no communication failure with the specified cluster node..
     *
     * @param node Cluster node (must be one of {@link #nodes()}, otherwise results will be unpredictable).
     *
     * @return {@code true} if there was no communication failure with the specified cluster node.
     */
    default boolean isSuccess(ClusterNode node) {
        return errorOf(node) == null;
    }

    /**
     * Returns a communication error for the specified node or {@code null} if there was no communication failure with that node.
     *
     * @param node Cluster node (must be one of {@link #nodes()}, otherwise results will be unpredictable).
     *
     * @return Error in case of a communication error with the specified node or {@code null}.
     *
     * @see #errors()
     */
    default Throwable errorOf(ClusterNode node) {
        Map<ClusterNode, Throwable> errors = errors();

        return errors != null ? errors.get(node) : null;
    }
}


text:
//===========================================================================
// xml_parser.cpp provides parser functions for input xml config file
//===========================================================================

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <inttypes.h>
#include <cmath>

#include "xml_parser.h"

using namespace std;

XmlParser::XmlParser()
{
    xml_sim.max_msg_size = 0;
    xml_sim.num_recv_threads = 1;
    xml_sim.thread_sync_interval = 0;
    xml_sim.proc_sync_interval = 0;
    xml_sim.syscall_cost = 0;
    xml_sim.sys.sys_type = 0;
    xml_sim.sys.protocol_type = 0;
    xml_sim.sys.max_num_sharers = 0;
    xml_sim.sys.page_size = 0;
    xml_sim.sys.tlb_enable = 0;
    xml_sim.sys.shared_llc = 0;
    xml_sim.sys.verbose_report = 0;
    xml_sim.sys.cpi_nonmem = 0;
    xml_sim.sys.dram_access_time = 0;
    xml_sim.sys.num_levels = 0;
    xml_sim.sys.freq = 0;
    xml_sim.sys.num_cores = 0;
    xml_sim.sys.bus_latency = 0;
    xml_sim.sys.page_miss_delay = 0;

    xml_sim.sys.directory_cache.level = 0;
    xml_sim.sys.directory_cache.share = 0;
    xml_sim.sys.directory_cache.access_time = 0;
    xml_sim.sys.directory_cache.size = 0;
    xml_sim.sys.directory_cache.block_size = 0;
    xml_sim.sys.directory_cache.num_ways = 0;

    xml_sim.sys.tlb_cache.level = 0;
    xml_sim.sys.tlb_cache.share = 0;
    xml_sim.sys.tlb_cache.access_time = 0;
    xml_sim.sys.tlb_cache.size = 0;
    xml_sim.sys.tlb_cache.block_size = 0;
    xml_sim.sys.tlb_cache.num_ways = 0;

    xml_sim.sys.network.net_type = 0;
    xml_sim.sys.network.data_width = 0;
    xml_sim.sys.network.header_flits = 0;
    xml_sim.sys.network.inject_delay = 0;
    xml_sim.sys.network.router_delay = 0;
    xml_sim.sys.network.link_delay = 0;
}

XmlSim* XmlParser::getXmlSim()
{
    return &xml_sim;
}

//Get the xml pointer of a xml file
bool XmlParser::getDoc (const char *docname)
{
	doc = xmlParseFile(docname);

	if (doc == NULL ) {
		cerr << "Document not parsed successfully. \n";
		return false;
	}

	return true;
}

//Get the node set of a xml file
xmlXPathObjectPtr XmlParser::getNodeSet (xmlChar *xpath)
{
	xmlXPathContextPtr context;
	xmlXPathObjectPtr result;

	context = xmlXPathNewContext(doc);
	if (context == NULL) {
		cerr << "Error in xmlXPathNewContext\n";
		return NULL;
	}
	result = xmlXPathEvalExpression(xpath, context);
	xmlXPathFreeContext(context);
	if (result == NULL) {
		cerr << "Error in xmlXPathEvalExpression\n";
		return NULL;
	}
	if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {
		xmlXPathFreeObject(result);
        cerr << "No result\n";
		return NULL;
	}
	return result;
}

//Parse the simulator structure and store the result
bool XmlParser::parseSim()
{
    xmlXPathObjectPtr sim_node;
    sim_node = getNodeSet((xmlChar*) "//simulator");

    if (sim_node->nodesetval->nodeNr != 1) {
        xmlXPathFreeObject(sim_node);
        return false;
    }
    xmlNodePtr cur;
    xmlChar*   key;
    stringstream   convert;
    int        i, item_count = 0;
    for (i = 0; i < sim_node->nodesetval->nodeNr; i++) {
        cur = sim_node->nodesetval->nodeTab[i]->xmlChildrenNode;
	    while (cur != NULL) {
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"max_msg_size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.max_msg_size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"num_recv_threads"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.num_recv_threads;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"thread_sync_interval"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.thread_sync_interval;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"proc_sync_interval"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.proc_sync_interval;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"syscall_cost"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.syscall_cost;
                xmlFree(key);
                item_count++;
 	        }
	    cur = cur->next;
        }
	}
    xmlXPathFreeObject(sim_node);
    //Check if # of items is corret
    return (item_count == 5);
}

//Parse the system structure and store the result
bool XmlParser::parseSys()
{
    xmlXPathObjectPtr sys_node;
    sys_node = getNodeSet((xmlChar*) "//system");

    if (sys_node->nodesetval->nodeNr != 1) {
        xmlXPathFreeObject(sys_node);
        return false;
    }

    xmlNodePtr cur;
    xmlChar*   key;
    stringstream   convert;
    int        i, item_count = 0;
    for (i = 0; i < sys_node->nodesetval->nodeNr; i++) {
        cur = sys_node->nodesetval->nodeTab[i]->xmlChildrenNode;
	    while (cur != NULL) {
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"sys_type"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.sys_type;
                xmlFree(key);
                item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"protocol_type"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.protocol_type;
                xmlFree(key);
                item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"max_num_sharers"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.max_num_sharers;
                xmlFree(key);
                //optional item is not checked
                //item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"page_size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.page_size;
                xmlFree(key);
                item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"tlb_enable"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_enable;
                xmlFree(key);
                item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"shared_llc"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.shared_llc;
                xmlFree(key);
                item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"verbose_report"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.verbose_report;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"cpi_nonmem"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> xml_sim.sys.cpi_nonmem;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"dram_access_time"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.dram_access_time;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"num_levels"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.num_levels;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"num_cores"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.num_cores;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"bus_latency"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.bus_latency;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"page_miss_delay"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.page_miss_delay;
                xmlFree(key);
                item_count++;
 	        }

            if ((!xmlStrcmp(cur->name, (const xmlChar *)"freq"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> xml_sim.sys.freq;
                xmlFree(key);
                item_count++;
 	        }
	    cur = cur->next;
        }
	}
    xml_sim.sys.cache = new XmlCache [xml_sim.sys.num_levels];
    xmlXPathFreeObject(sys_node);
    return (item_count == 13);
}

 //Parse the network structure and store the result
bool XmlParser::parseNetwork()
{
    xmlXPathObjectPtr net_node;
    net_node = getNodeSet((xmlChar*) "//network");

    if (net_node->nodesetval->nodeNr != 1) {
        xmlXPathFreeObject(net_node);
        return false;
    }

    xmlNodePtr cur;
    xmlChar*   key;
    stringstream   convert;
    int        i, item_count = 0;
    for (i = 0; i < net_node->nodesetval->nodeNr; i++) {
        cur = net_node->nodesetval->nodeTab[i]->xmlChildrenNode;
	    while (cur != NULL) {
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"net_type"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.network.net_type;
                xmlFree(key);
                //item_count++;
 	        }
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"data_width"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.network.data_width;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"header_flits"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.network.header_flits;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"router_delay"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.network.router_delay;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"link_delay"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.network.link_delay;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"inject_delay"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.network.inject_delay;
                xmlFree(key);
                //item_count++;
 	        }
 	    cur = cur->next;
        }
	}
    xmlXPathFreeObject(net_node);
    return (item_count == 4);
}

 //Parse the directory cache structure and store the result
bool XmlParser::parseDirectoryCache()
{
    xmlXPathObjectPtr cache_node;
    cache_node = getNodeSet((xmlChar*) "//directory_cache");

    if (cache_node->nodesetval->nodeNr != 1) {
        xmlXPathFreeObject(cache_node);
        return false;
    }

    xmlNodePtr cur;
    xmlChar*   key;
    stringstream   convert;
    int        i, item_count = 0;
    for (i = 0; i < cache_node->nodesetval->nodeNr; i++) {
        cur = cache_node->nodesetval->nodeTab[i]->xmlChildrenNode;
	    while (cur != NULL) {
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"level"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.directory_cache.level;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"share"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.directory_cache.share;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"access_time"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.directory_cache.access_time;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.directory_cache.size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"block_size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.directory_cache.block_size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"num_ways"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.directory_cache.num_ways;
                xmlFree(key);
                item_count++;
 	        }
 	    cur = cur->next;
        }
	}
    xmlXPathFreeObject(cache_node);
    return (item_count == 6);
}

 //Parse the TLB cache structure and store the result
bool XmlParser::parseTlbCache()
{
    xmlXPathObjectPtr cache_node;
    cache_node = getNodeSet((xmlChar*) "//tlb_cache");

    if (cache_node->nodesetval->nodeNr != 1) {
        xmlXPathFreeObject(cache_node);
        return false;
    }

    xmlNodePtr cur;
    xmlChar*   key;
    stringstream   convert;
    int        i, item_count = 0;
    for (i = 0; i < cache_node->nodesetval->nodeNr; i++) {
        cur = cache_node->nodesetval->nodeTab[i]->xmlChildrenNode;
	    while (cur != NULL) {
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"level"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_cache.level;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"share"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_cache.share;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"access_time"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_cache.access_time;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_cache.size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"block_size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_cache.block_size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"num_ways"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.tlb_cache.num_ways;
                xmlFree(key);
                item_count++;
 	        }
 	    cur = cur->next;
        }
	}
    xmlXPathFreeObject(cache_node);
    return (item_count == 6);
}

//Parse the cache structure and store the result
bool XmlParser::parseCache()
{
    xmlXPathObjectPtr cache_node;
    cache_node = getNodeSet((xmlChar*) "//cache");

    if (cache_node->nodesetval->nodeNr != xml_sim.sys.num_levels) {
        xmlXPathFreeObject(cache_node);
        return false;
    }

    xmlNodePtr cur;
    xmlChar*   key;
    stringstream   convert;
    int        i, item_count = 0;
    for (i = 0; i < cache_node->nodesetval->nodeNr; i++) {
        cur = cache_node->nodesetval->nodeTab[i]->xmlChildrenNode;
	    while (cur != NULL) {
	        if ((!xmlStrcmp(cur->name, (const xmlChar *)"level"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.cache[i].level;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"share"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.cache[i].share;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"access_time"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.cache[i].access_time;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.cache[i].size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"block_size"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.cache[i].block_size;
                xmlFree(key);
                item_count++;
 	        }
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"num_ways"))) {
		        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                convert.clear();
                convert.str("");
		        convert << key;
                convert >> dec >> xml_sim.sys.cache[i].num_ways;
                xmlFree(key);
                item_count++;
 	        }
	    cur = cur->next;
        }
	}
    xmlXPathFreeObject(cache_node);
    return (item_count == 6 * xml_sim.sys.num_levels);
}

//Parse the entire xml file and store the result
bool XmlParser::parse(const char *docname)
{
    if(getDoc(docname)){
        if (!parseSim()) {
            cerr << "Error in parsing simulator structure!\n";
            return false;
        }
        else if (!parseSys()) {
            cerr << "Error in parsing system structure!\n";
            return false;
        }
        else if (!parseNetwork()) {
            cerr << "Error in parsing network structure!\n";
            return false;
        }
        else if (!parseDirectoryCache()) {
            cerr << "Error in parsing directory cache structure!\n";
            return false;
        }
        else if (!parseTlbCache()) {
            cerr << "Error in parsing TLB cache structure!\n";
            return false;
        }
        else if (!parseCache()) {
            cerr << "Error in parsing cache structure!\n";
            return false;
        }
        else
            return true;
    }
    else {
        cout << "Error in get xml document!\n";
        return false;
    }
}

XmlParser::~XmlParser()
{
    if (xml_sim.sys.num_levels > 0) {
        delete [] xml_sim.sys.cache;
    }
    xmlFreeDoc(doc);
    xmlCleanupParser();
}


text:
package org.keycloak.authentication.authenticators.broker;

import org.keycloak.Config;
import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.ProviderConfigProperty;

import java.util.List;

/**
 * @author Marek Posolda
 */
public class IdpEmailVerificationAuthenticatorFactory implements AuthenticatorFactory {

    public static final String PROVIDER_ID = "idp-email-verification";
    static IdpEmailVerificationAuthenticator SINGLETON = new IdpEmailVerificationAuthenticator();

    @Override
    public Authenticator create(KeycloakSession session) {
        return SINGLETON;
    }

    @Override
    public void init(Config.Scope config) {

    }

    @Override
    public void postInit(KeycloakSessionFactory factory) {

    }

    @Override
    public void close() {

    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }

    @Override
    public String getReferenceCategory() {
        return "emailVerification";
    }

    @Override
    public boolean isConfigurable() {
        return false;
    }

    public static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
            AuthenticationExecutionModel.Requirement.ALTERNATIVE,
            AuthenticationExecutionModel.Requirement.REQUIRED,
            AuthenticationExecutionModel.Requirement.DISABLED};

    @Override
    public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
        return REQUIREMENT_CHOICES;
    }

    @Override
    public String getDisplayType() {
        return "Verify existing account by Email";
    }

    @Override
    public String getHelpText() {
        return "Email verification of existing Keycloak user, that wants to link his user account with identity provider";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return null;
    }

    @Override
    public boolean isUserSetupAllowed() {
        return false;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Boln Soc. Micol. Madrid 27: 283 (2003)

#### Original name
Armillaria mellea f. rosea Calonge & M. Seq.

### Remarks
null


text:
package com.linkedin.parseq.promise;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import static com.linkedin.parseq.TestUtil.withDisabledLogging;
import static org.testng.AssertJUnit.*;

/**
 * @author Chris Pettitt (cpettitt@linkedin.com)
 */
public class TestSettablePromise {
  private ScheduledExecutorService _scheduler;

  @BeforeMethod
  public void setUp() throws Exception {
    _scheduler = Executors.newSingleThreadScheduledExecutor();
  }

  @AfterMethod
  public void tearDown() throws Exception {
    _scheduler.shutdownNow();
    _scheduler = null;
  }

  @Test
  public void testPromiseInitialState() {
    assertFalse(Promises.settable().isDone());
    assertFalse(Promises.settable().isFailed());
  }

  @Test
  public void testSetAndGet() {
    final SettablePromise<String> promise = Promises.settable();
    promise.done("done!");
    assertEquals("done!", promise.get());
    assertTrue(promise.isDone());
  }

  @Test
  public void testGetWithoutSet() {
    try {
      Promises.settable().get();
      fail("Should have thrown PromiseUnresolvedException");
    } catch (PromiseUnresolvedException e) {
      // Expected case
    }
  }

  @Test
  public void testGetOrDefaultWithSet() {
    final SettablePromise<String> promise = Promises.settable();
    promise.done("done!");
    assertEquals("done!", promise.getOrDefault("default"));
  }

  @Test
  public void testGetOrDefaultWithSetError() {
    final SettablePromise<String> promise = Promises.settable();
    promise.fail(new Exception());
    assertEquals("default", promise.getOrDefault("default"));
  }

  @Test
  public void testSetTwice() {
    final SettablePromise<String> promise = Promises.settable();
    promise.done("done!");

    try {
      promise.done("no, really done!");
      fail("Should have thrown an Exception");
    } catch (PromiseResolvedException e) {
      // Expected case
      assertEquals("done!", promise.get());
    }
  }

  @Test
  public void testSetErrorTwice() {
    final SettablePromise<String> promise = Promises.settable();
    final Exception exception = new Exception();
    promise.fail(exception);

    try {
      promise.fail(new Exception());
      fail("Should have thrown an Exception");
    } catch (PromiseResolvedException e) {
      // Expected case
      assertEquals(exception, promise.getError());
    }
  }

  @Test
  public void testSetThenSetError() {
    final SettablePromise<String> promise = Promises.settable();
    promise.done("done!");

    try {
      promise.fail(new Exception());
      fail("Should have thrown an Exception");
    } catch (PromiseResolvedException e) {
      // Expected case
      assertEquals("done!", promise.get());
    }
  }

  @Test
  public void testSetErrorAndGet() {
    final SettablePromise<String> promise = Promises.settable();
    final Exception error = new Exception();
    promise.fail(error);

    try {
      promise.get();
      fail("Should have thrown an exception");
    } catch (PromiseException e) {
      assertEquals(error, e.getCause());
    }
  }

  @Test
  public void testSetErrorAndGetError() {
    final SettablePromise<String> promise = Promises.settable();
    final Exception error = new Exception();
    promise.fail(error);
    assertEquals(error, promise.getError());
    assertTrue(promise.isDone());
    assertTrue(promise.isFailed());
  }

  @Test
  public void testSetAndGetError() {
    final SettablePromise<String> promise = Promises.settable();
    promise.done("done!");
    assertNull(promise.getError());
  }

  @Test
  public void testGetErrorWithoutSet() {
    try {
      Promises.settable().getError();
      fail("Should have thrown PromiseUnresolvedException");
    } catch (PromiseUnresolvedException e) {
      // Expected case
    }
  }

  @Test
  public void testTimedAwaitWithoutSet() throws InterruptedException {
    assertFalse(Promises.settable().await(50, TimeUnit.MILLISECONDS));
  }

  @Test
  public void testAwaitWithSet() throws InterruptedException {
    final SettablePromise<String> promise = Promises.settable();
    _scheduler.schedule(new Runnable() {
      @Override
      public void run() {
        promise.done("done!");
      }
    }, 10, TimeUnit.MILLISECONDS);

    assertTrue(promise.await(5, TimeUnit.SECONDS));
    assertEquals("done!", promise.get());
  }

  @Test
  public void testAwaitWithSetError() throws InterruptedException {
    final SettablePromise<String> promise = Promises.settable();
    final Exception error = new Exception();
    _scheduler.schedule(new Runnable() {
      @Override
      public void run() {
        promise.fail(error);
      }
    }, 10, TimeUnit.MILLISECONDS);

    assertTrue(promise.await(5, TimeUnit.SECONDS));
    assertEquals(error, promise.getError());
  }

  @Test
  public void testListenerWithSet() throws InterruptedException {
    final SettablePromise<String> promise = Promises.settable();

    final AtomicReference<String> resultRef = new AtomicReference<String>();
    final CountDownLatch latch = new CountDownLatch(1);
    promise.addListener(new PromiseListener<String>() {
      @Override
      public void onResolved(Promise<String> resolvedPromise) {
        resultRef.set(resolvedPromise.get());
        latch.countDown();
      }
    });

    _scheduler.schedule(new Runnable() {
      @Override
      public void run() {
        promise.done("done!");
      }
    }, 10, TimeUnit.MILLISECONDS);

    latch.await();
    assertEquals("done!", resultRef.get());
  }

  @Test
  public void testListenerWithSetError() throws InterruptedException {
    final SettablePromise<String> promise = Promises.settable();

    final Exception error = new Exception();
    final AtomicReference<Throwable> resultRef = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    promise.addListener(new PromiseListener<String>() {
      @Override
      public void onResolved(Promise<String> resolvedPromise) {
        resultRef.set(resolvedPromise.getError());
        latch.countDown();
      }
    });

    _scheduler.schedule(new Runnable() {
      @Override
      public void run() {
        promise.fail(error);
      }
    }, 10, TimeUnit.MILLISECONDS);

    latch.await();
    assertEquals(error, resultRef.get());
  }

  @Test
  public void testListenerAfterSet() throws InterruptedException {
    final SettablePromise<String> promise = Promises.settable();
    promise.done("done!");

    final AtomicReference<String> resultRef = new AtomicReference<String>();
    final CountDownLatch latch = new CountDownLatch(1);
    promise.addListener(new PromiseListener<String>() {
      @Override
      public void onResolved(Promise<String> resolvedPromise) {
        resultRef.set(resolvedPromise.get());
        latch.countDown();
      }
    });

    latch.await();
    assertEquals("done!", resultRef.get());
  }

  @Test
  public void testListenerThrowsException() throws InterruptedException {
    // This test ensures that we properly resolve the promise even when
    // one of its listeners throws an Error.
    final SettablePromise<String> promise = Promises.settable();
    promise.addListener(new PromiseListener<String>() {
      @Override
      public void onResolved(Promise<String> promise) {
        throw new RuntimeException();
      }
    });

    withDisabledLogging(new Runnable() {
      @Override
      public void run() {
        promise.done("Done!");
      }
    });

    assertTrue(promise.await(5, TimeUnit.SECONDS));
    assertEquals("Done!", promise.get());
  }

  @Test
  public void testListenerThrowsError() throws InterruptedException {
    // This test ensures that we properly resolve the promise even when
    // one of its listeners throws an Error.
    final SettablePromise<String> promise = Promises.settable();
    promise.addListener(new PromiseListener<String>() {
      @Override
      public void onResolved(Promise<String> promise) {
        throw new Error();
      }
    });

    withDisabledLogging(new Runnable() {
      @Override
      public void run() {
        promise.done("Done!");
      }
    });

    assertTrue(promise.await(5, TimeUnit.SECONDS));
    assertEquals("Done!", promise.get());
  }

  @Test
  public void testListenerThrowsErrorAfterPromiseDone() throws InterruptedException {
    // This test ensures that we catch and do not rethrow errors from listeners
    // even if they are added after the promise is done.
    final SettablePromise<String> promise = Promises.settable();
    promise.done("Done!");
    assertTrue(promise.await(5, TimeUnit.SECONDS));

    withDisabledLogging(new Runnable() {
      @Override
      public void run() {
        // This should not throw
        promise.addListener(new PromiseListener<String>() {
          @Override
          public void onResolved(Promise<String> promise) {
            throw new Error();
          }
        });
      }
    });
  }
}


text:
Media

                    {% capture imagePath %}{{ page.folderPath }}/images {% endcapture %}
                    {% for image in site.static_files %}
                    {% if image.path contains imagePath %}

                    {% endif %}
                    {% endfor %}

                    {% for vid in page.video %}

                    {% endfor %}


text:
<?php
/**
 * @package limba.interfaces
 * @since 21 janv. 2009
 * @author  Ludovic Reenaers
 * @link http://code.google.com/p/limba
 */
class View
{
	private $Model;
	private $doctype;
	private $head;
	private $title;
	private $content;
	private $footer;
	private $html;
	private $MenuTree;
	private $header;
	private $pathway;
	private $languagePad;
	private $userPad;
	private $wlkm;
	protected $params;

	function __construct($Model,$params,$layout="ERGONOMIC",$doctype="XHTML1.0T",$headertype="BASE")
	{
		$this->params = $params;
		$this->Model =$Model;
	}

	function setContent($str)
	{
		$this->content.=$str;
	}
	function redirect($url){
		$this->setContent('<META HTTP-EQUIV="Refresh" CONTENT="0; URL='.$url.'">');
	}
	function getPage()
	{

		$ret = $this->Model->getData();
		$ret=str_replace("CONTENT",$this->content,$ret);
		return $ret;
	}

}
?>