text:
using LandSky.DotNetExt;
using LandSky.MyEnums;
using System.Collections.Generic;
using System.Linq;
using static System.Math;

namespace LandSky.UIComponents
{
    internal class TextBox : UIComponentBase
    {
        private List<char> mAcceptedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ".ToCharArray().ToList();
        private int mCursorLeft;
        private int mCursorTop;

        public TextBox(string Name, int TabIndex, int Top, int Left) : base(Name, TabIndex, Top, Left)
        {
        }

        public TextBox(string Name, int TabIndex, int Top, int Left, string InitText) : base(Name, TabIndex, Top, Left, InitText)
        {
            this.mCursorLeft = Text.Split(new char[] { '\n' }).Last().Length;
            this.mCursorTop = this.Size.Height;
        }

        public TextBox(string Name, int TabIndex, int Top, int Left, string InitText, string AditionalSpecialCharacters) : base(Name, TabIndex, Top, Left, InitText)
        {
            this.mCursorLeft = InitText.Length;
            mAcceptedCharacters.AddRange(AditionalSpecialCharacters.ToCharArray());
        }

        public override bool NewInput(MyConsoleKeyInfo KeyInfo)
        {
            if (mAcceptedCharacters.Any(i => i == KeyInfo.KeyChar))
            {
                InsertCharInText(mCursorTop, mCursorLeft, KeyInfo.KeyChar);

                return true;
            }
            else
            {
                switch (KeyInfo.KeyChar)
                {
                    case (char)SpecialAsciiKeys.Backspace:
                        RemoveCharFormText(1);
                        return true;

                    case (char)SpecialAsciiKeys.Del:
                        RemoveCharFormText(-1);
                        return true;

                    case (char)SpecialAsciiKeys.ArrowUp:
                        MoveCursureVertical(1);
                        return true;

                    case (char)SpecialAsciiKeys.ArrowDown:
                        MoveCursureVertical(-1);
                        return true;

                    case (char)SpecialAsciiKeys.ArrowRight:
                        MoveCursureHorisontal(1);
                        return true;

                    case (char)SpecialAsciiKeys.ArrowLeft:
                        MoveCursureHorisontal(-1);
                        return true;
                }
            }
            return base.NewInput(KeyInfo);
        }

        private void MoveCursureHorisontal(int v)
        {
            mCursorLeft = Max(0, Min(mCursorLeft + v, mLinesOfText[mCursorTop].Length));
        }

        private void MoveCursureVertical(int v)
        {
            mCursorTop = Max(0, Min(mLinesOfText.Count - 1, mCursorTop + v));
            mCursorLeft = Min(mCursorLeft, mLinesOfText[mCursorTop].Length - 1);
        }

        private void RemoveCharFormText(int v)
        {
            string aLine = mLinesOfText[mCursorTop];
            int pointA = Min(aLine.Length, Max(0, mCursorLeft - v));
            int pointB = Min(aLine.Length, Max(0, mCursorLeft));
            mLinesOfText[mCursorTop] = $"{aLine.Substring(0, Min(pointA, pointB))}{aLine.Substring(Max(pointA, pointB))}";
            mCursorLeft -= v;
            LinesUpdated();
        }

        private void InsertCharInText(int top, int left, char c)
        {
            string OutText = string.Empty;
            string before = mLinesOfText[mCursorTop].Substring(0, mCursorLeft);
            string after = mLinesOfText[mCursorTop].Substring(mCursorLeft);
            mLinesOfText[mCursorTop] = $"{before}{c}{after}";
            mCursorLeft++;
            LinesUpdated();
        }

        public override string ToString()
        {
            List<string> Lines = new List<string>();
            if (mLinesOfText.Count > 0 && mLinesOfText[0].Length > 0)
            {
                foreach (var line in mLinesOfText)
                {
                    Lines.Add(line);
                }
            }
            else
            {
                Lines.Add(Hint);
            }
            string aLine = Lines[mCursorTop];
            Lines[mCursorTop] = $"{aLine.Substring(0, mCursorLeft)}|{aLine.Substring(mCursorLeft)}";
            int MaxWitdth = SizeMode == SizeMode.Auto ? Lines.Max(i => i.Length) : this.mSize.Width;
            string OutString = Focus ? ("-" + new string('+', MaxWitdth) + "-\n") : ("+" + new string('-', MaxWitdth) + "+\n");

            foreach (var Line in Lines)
            {
                OutString += $"|{Line}{new string(' ', Max(0, MaxWitdth - Line.Length))}|".Substring(0, SizeMode == SizeMode.Auto ? Line.Length + 2 : Min(Line.Length + 2, mSize.Width)) + '\n';
            }
            if (!Lines.Any())
                OutString += $"|{Hint}{new string(' ', Max(0, MaxWitdth - Hint.Length))}|";

            if (SizeMode == SizeMode.Explicit)
            {
                int currentLine = 0;
                OutString = new string(OutString.ToCharArray().Select(i =>
                {
                    if (i == '\n')
                        currentLine++;
                    return currentLine + 2 < this.mSize.Height ? i : '\0';
                }).ToArray());
            }
            OutString += Focus ? ("-" + new string('+', MaxWitdth) + "-") : ("+" + new string('-', MaxWitdth) + "+");
            return OutString;
        }
    }
}


text:
require File.dirname(__FILE__) + '/../../test_helper'

class HasManyExistingViewTest < Test::Unit::TestCase

  attr_reader :singular_name
  attr_reader :attributes
  attr_reader :plural_name
  attr_reader :has_many_through_models
  attr_reader :hmt_model
  attr_reader :class_name
  attr_reader :migration_name
  attr_reader :table_name
  attr_reader :options

  context "When a target model and a through model exist" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      ClassFactory :assignment
    end

    should "detect the existing hmt models when no parent is specified" do
      gen = new_generator_for_test_model('view_for', ['--view', 'has_many_existing'], 'programmer')
      has_many_through_models = gen.has_many_through_models
      assert_equal 1, has_many_through_models.size
      assert_equal 'Project', has_many_through_models[0].name
      assert_equal 'Assignment', has_many_through_models[0].through_model.name
    end

    should "use find the specified valid child model if provided" do
      gen = new_generator_for_test_model('view_for', ['--view', 'has_many_existing:projects'], 'programmer')
      has_many_through_models = gen.has_many_through_models
      assert_equal 1, has_many_through_models.size
      assert_equal 'Project', has_many_through_models[0].name
      assert_equal 'Assignment', has_many_through_models[0].through_model.name
    end

    should "return an error message with a bad child model param" do
      Rails::Generator::Base.logger.expects('error').with('Class \'blah\' does not exist or contains a syntax error and could not be loaded.')
      gen = new_generator_for_test_model('view_for', ['--view', 'has_many_existing:blah'], 'programmer')
      assert_equal [], gen.has_many_through_models
    end
  end

  context "A test model with no hmt associations" do
    setup do
      ClassFactory :test_model
    end

    should "return a error when run with view_for and not run any actions" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('error').with('No has_many through associations exist in class TestModel.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing']))
    end

    should "return a error when run with scaffold_for_view and not run any actions" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('error').with('No has_many through association specified.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('scaffold_for_view', ['--view', 'has_many_existing']))
    end
  end

  context "A through model with a belongs_to association for an hmt model for which it does not have a name virtual attribute" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
through_model_code = <<SRC
belongs_to :project
belongs_to :programmer
SRC
      ClassFactory :assignment, :class_eval => through_model_code
    end

    should "return a warning and stop when the problem model is specified" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Assignment does not have a method project_name.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A through model with a belongs_to association for an hmt model which does not have a name method or column" do
    setup do
      ClassFactory :project do |p|
        p.string :not_the_name_column
      end
      ClassFactory :assignment
      ClassFactory :programmer
    end

    should "return a warning and stop when the problem model is specified" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Project does not have a name attribute.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A through model with a belongs_to association for an hmt model which has a name method but not a name column" do
    setup do
      parent_code_with_name_method = <<SRC
        has_many :programmers, :through => :assignments
        has_many :assignments
        def name
          'the name'
        end
SRC
      ClassFactory :project, :class_eval => parent_code_with_name_method do |p|
        p.string :not_the_name_column
      end
      ClassFactory :assignment
      ClassFactory :programmer
    end

    should "continue to generate as usual" do
      stub_actions
      Rails::Generator::Commands::Create.any_instance.expects(:directory).with('app/controllers/')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A through model with a belongs_to association for an hmt model for which it does not have a foreign key" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      ClassFactory :assignment do |a|
        a.integer :not_the_project_id
        a.integer :programmer_id
      end
    end

    should "return a warning and stop when the problem model is specified" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Assignment does not contain a foreign key for Project.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A through model with a belongs_to association for an hmt model for which it does not have a foreign key for the source model" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      ClassFactory :assignment do |a|
        a.integer :project_id
        a.integer :not_the_programmer_id
      end
    end

    should "return a warning and stop when the problem model is specified" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Assignment does not contain a foreign key for Programmer.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A Rails generator script with an hmt model without a has_many association for the through model" do
    setup do
      @generator_script = Rails::Generator::Scripts::Generate.new
      has_many_through_code = <<SRC
has_many :programmers, :through => :assignments
SRC
      ClassFactory :project, :class_eval => has_many_through_code
      ClassFactory :programmer
      ClassFactory :assignment
    end

    should "return a warning when run with view_for and not run any actions" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Project does not contain a has_many association for Assignment.')
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A Rails generator script with an hmt model without a has_many association for the source model" do
    setup do
      @generator_script = Rails::Generator::Scripts::Generate.new
      has_many_through_code = <<SRC
has_many :assignments
SRC
      ClassFactory :project, :class_eval => has_many_through_code
      ClassFactory :programmer
      ClassFactory :assignment
    end

    should "return a warning when run with view_for and not run any actions" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Project does not contain a has_many through association for Programmer.')
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A Rails generator script with a child model without a belongs_to association for the source model" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      through_model_code = <<SRC
belongs_to :project
def project_name
  'something'
end
def project_name=
end
SRC
      ClassFactory :assignment, :class_eval => through_model_code
      @generator_script = Rails::Generator::Scripts::Generate.new
    end

    should "return a warning when run with view_for and not run any actions" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Assignment does not contain a belongs_to association for Programmer.')
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A Rails generator script with a child model without a belongs_to association for the hmt model" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      through_model_code = <<SRC
belongs_to :programmer
def project_name
  'something'
end
def project_name=
end
SRC
      ClassFactory :assignment, :class_eval => through_model_code
      @generator_script = Rails::Generator::Scripts::Generate.new
    end

    should "return a warning when run with view_for and not run any actions" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Assignment does not belong to model Project.')
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "A test model with a has_many through association with a through model for which it does not accept nested attributes" do
    setup do
      missing_nested_attribute_code = <<SRC
has_many :projects, :through => :assignments
has_many :assignments
SRC
      ClassFactory :project
      ClassFactory :programmer, :class_eval => missing_nested_attribute_code
      ClassFactory :assignment
    end

    should "return a warning and stop when the problem model is specified" do
      expect_no_actions
      Rails::Generator::Base.logger.expects('warning').with('Model Programmer does not accept nested attributes for model Assignment.')
      @generator_script = Rails::Generator::Scripts::Generate.new
      @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
    end
  end

  context "When a target model and a through model exist" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      ClassFactory :assignment
    end

    context "A Rails generator script" do
      setup do
        @generator_script = Rails::Generator::Scripts::Generate.new
      end

      should "return a warning when run with view_for on an invalid child model and not run any actions" do
        expect_no_actions
        Rails::Generator::Base.logger.expects('error').with('Class \'blah\' does not exist or contains a syntax error and could not be loaded.')
        @generator_script = Rails::Generator::Scripts::Generate.new
        @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:blah'], 'programmer'))
      end

      should "create the correct manifest when the view_for generator is run with valid htm models" do

        expect_no_warnings

        directories = [
          'app/controllers/',
          'app/helpers/',
          'app/views/programmers',
          'app/views/layouts/',
          'test/functional/',
          'test/unit/',
          'test/unit/helpers/',
          'public/stylesheets/'
        ].each { |path| Rails::Generator::Commands::Create.any_instance.expects(:directory).with(path) }

        templates = {
          'view_index.html.erb'  => 'app/views/programmers/index.html.erb',
          'view_new.html.erb'    => 'app/views/programmers/new.html.erb',
          'view_edit.html.erb'   => 'app/views/programmers/edit.html.erb',
          'view_form.html.erb'   => 'app/views/programmers/_form.html.erb',
          'layout.html.erb'      => 'app/views/layouts/programmers.html.erb',
          'style.css'            => 'public/stylesheets/scaffold.css',
          'controller.rb'        => 'app/controllers/programmers_controller.rb',
          'functional_test.rb'   => 'test/functional/programmers_controller_test.rb',
          'helper.rb'            => 'app/helpers/programmers_helper.rb',
          'helper_test.rb'       => 'test/unit/helpers/programmers_helper_test.rb'
        }.each { |template, target| Rails::Generator::Commands::Create.any_instance.expects(:template).with(template, target) }

        project_model_info = ViewMapper::ModelInfo.new('project')
        assignment_model_info = ViewMapper::ModelInfo.new('assignment')
        programmer_info = ViewMapper::ModelInfo.new('Programmer')
        ViewMapper::ModelInfo.stubs(:new).with('project').returns(project_model_info)
        ViewMapper::ModelInfo.stubs(:new).with('programmer').returns(programmer_info)
        ViewMapper::ModelInfo.stubs(:new).with('Programmer').returns(programmer_info)
        ViewMapper::ModelInfo.stubs(:new).with('assignment').returns(assignment_model_info)
        Rails::Generator::Commands::Create.any_instance.expects(:template).with(
          'view_show.html.erb',
          'app/views/programmers/show.html.erb',
          { :assigns => { :has_many_through_models => [ project_model_info ] } }
        )
        Rails::Generator::Commands::Create.any_instance.expects(:template).with(
          'view_child_form.html.erb',
          'app/views/programmers/_assignment.html.erb',
          { :assigns => { :hmt_model => project_model_info } }
        )
        Rails::Generator::Commands::Create.any_instance.expects(:file).with(
          'nested_attributes.js', 'public/javascripts/nested_attributes.js'
        )
        Rails::Generator::Commands::Create.any_instance.expects(:route_resources).with('programmers')
        Rails::Generator::Commands::Create.any_instance.expects(:file).never
        Rails::Generator::Commands::Create.any_instance.expects(:dependency).never

        @generator_script.run(generator_script_cmd_line('view_for', ['--view', 'has_many_existing:projects'], 'programmer'))
      end

      should "create the correct manifest when the scaffold_for_view generator is run with valid htm models" do

        expect_no_warnings

        directories = [
          'app/models/',
          'app/controllers/',
          'app/helpers/',
          'app/views/programmers',
          'app/views/layouts/',
          'test/functional/',
          'test/unit/',
          'test/unit/helpers/',
          'test/fixtures/',
          'public/stylesheets/'
        ].each { |path| Rails::Generator::Commands::Create.any_instance.expects(:directory).with(path) }

        templates = {
          'view_index.html.erb'  => 'app/views/programmers/index.html.erb',
          'view_new.html.erb'    => 'app/views/programmers/new.html.erb',
          'view_edit.html.erb'   => 'app/views/programmers/edit.html.erb',
          'view_form.html.erb'   => 'app/views/programmers/_form.html.erb',
          'layout.html.erb'      => 'app/views/layouts/programmers.html.erb',
          'style.css'            => 'public/stylesheets/scaffold.css',
          'controller.rb'        => 'app/controllers/programmers_controller.rb',
          'functional_test.rb'   => 'test/functional/programmers_controller_test.rb',
          'helper.rb'            => 'app/helpers/programmers_helper.rb',
          'helper_test.rb'       => 'test/unit/helpers/programmers_helper_test.rb',
          'model.rb'             => 'app/models/programmer.rb',
          'unit_test.rb'         => 'test/unit/programmer_test.rb',
          'fixtures.yml'         => 'test/fixtures/programmers.yml'
        }.each { |template, target| Rails::Generator::Commands::Create.any_instance.expects(:template).with(template, target) }

        project_model_info = ViewMapper::ModelInfo.new('project')
        assignment_model_info = ViewMapper::ModelInfo.new('assignment')
        programmer_info = ViewMapper::ModelInfo.new('Programmer')
        ViewMapper::ModelInfo.stubs(:new).with('project').returns(project_model_info)
        ViewMapper::ModelInfo.stubs(:new).with('programmer').returns(programmer_info)
        ViewMapper::ModelInfo.stubs(:new).with('Programmer').returns(programmer_info)
        ViewMapper::ModelInfo.stubs(:new).with('assignment').returns(assignment_model_info)
        Rails::Generator::Commands::Create.any_instance.expects(:template).with(
          'view_show.html.erb',
          'app/views/programmers/show.html.erb',
          { :assigns => { :has_many_through_models => [ project_model_info ] } }
        )
        Rails::Generator::Commands::Create.any_instance.expects(:template).with(
          'view_child_form.html.erb',
          'app/views/programmers/_assignment.html.erb',
          { :assigns => { :hmt_model => project_model_info } }
        )
        Rails::Generator::Commands::Create.any_instance.expects(:file).with(
          'nested_attributes.js', 'public/javascripts/nested_attributes.js'
        )
        Rails::Generator::Commands::Create.any_instance.expects(:route_resources).with('programmers')
        Rails::Generator::Commands::Create.any_instance.expects(:file).never
        Rails::Generator::Commands::Create.any_instance.expects(:dependency).never

        Rails::Generator::Commands::Create.any_instance.expects(:migration_template).with(
          'migration.rb',
          'db/migrate',
          :assigns => { :migration_name => "CreateProgrammers" },
          :migration_file_name => "create_programmers"
        )

        @generator_script.run(generator_script_cmd_line('scaffold_for_view', ['--view', 'has_many_existing:projects'], 'programmer'))
      end

    end
  end

  context "When a target model and a through model exist" do
    setup do
      ClassFactory :project
      ClassFactory :programmer
      ClassFactory :assignment do |a|
        a.string  :name
        a.integer :project_id
        a.integer :programmer_id
      end
    end

    context "A view_for generator" do
      setup do
        @gen = new_generator_for_test_model('view_for', ['--view', 'has_many_existing:projects'], 'programmer')
      end

      should "return the proper source root" do
        assert_equal File.expand_path(File.dirname(__FILE__) + '/../../..//lib/view_mapper/views/has_many_existing/templates'), ViewMapper::HasManyExistingView.source_root
      end

      view_for_templates = %w{ new edit show index }
      view_for_templates.each do | template |
        should "render the #{template} template as expected" do
          @attributes = @gen.attributes
          @singular_name = @gen.singular_name
          @plural_name = @gen.plural_name
          @child_models = @gen.child_models
          @has_many_through_models = @gen.has_many_through_models
          template_file = File.open(@gen.source_path("view_#{template}.html.erb"))
          result = ERB.new(template_file.read, nil, '-').result(binding)
          expected_file = File.open(File.join(File.dirname(__FILE__), "expected_templates/#{template}.html.erb"))
          assert_equal expected_file.read, result
        end
      end

      should "render the form partial as expected" do
        @attributes = @gen.attributes
        @singular_name = @gen.singular_name
        @plural_name = @gen.plural_name
        @child_models = @gen.child_models
        @has_many_through_models = @gen.has_many_through_models
        template_file = File.open(@gen.source_path("view_form.html.erb"))
        result = ERB.new(template_file.read, nil, '-').result(binding)
        expected_file = File.open(File.join(File.dirname(__FILE__), "expected_templates/_form.html.erb"))
        assert_equal expected_file.read, result
      end

      should "render the child model partial as expected" do
        @hmt_model = @gen.has_many_through_models[0]
        template_file = File.open(@gen.source_path("view_child_form.html.erb"))
        result = ERB.new(template_file.read, nil, '-').result(binding)
        expected_file = File.open(File.join(File.dirname(__FILE__), "expected_templates/_assignment.html.erb"))
        assert_equal expected_file.read, result
      end
    end

    context "A scaffold_for_view generator" do
      setup do
        @gen = new_generator_for_test_model('scaffold_for_view', ['--view', 'has_many_existing:projects'], 'programmer')
      end

      should "render the model template as expected" do
        @has_many_through_models = @gen.has_many_through_models
        @class_name = @gen.class_name
        @attributes = @gen.attributes
        template_file = File.open(@gen.source_path("model.rb"))
        result = ERB.new(template_file.read, nil, '-').result(binding)
        expected_file = File.open(File.join(File.dirname(__FILE__), "expected_templates/programmer.rb"))
        assert_equal expected_file.read, result
      end

      should "render the migration template as expected" do
        @class_name = @gen.class_name
        @attributes = @gen.attributes
        @migration_name = 'CreateProgrammers'
        @table_name = @gen.table_name
        @options = {}
        template_file = File.open(@gen.source_path("migration.rb"))
        result = ERB.new(template_file.read, nil, '-').result(binding)
        expected_file = File.open(File.join(File.dirname(__FILE__), "expected_templates/create_programmers.rb"))
        assert_equal expected_file.read, result
      end
    end
  end

  def field_for(parent_model)
    @gen.field_for(parent_model)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package it.uniba.di.itps.asd.exams.Lab20090907;

import java.util.HashMap;

/**
 * Created by acidghost on 01/09/14.
 */
public class AlberoDecisione {
    private HashMap<String, Integer> attributi = new HashMap<String, Integer>();
    {
        attributi.put("Tempo", 0);
        attributi.put("Temperatura", 1);
        attributi.put("Umidita", 2);
        attributi.put("Vento", 3);
        attributi.put("Ideale", 4);
    }

    private String[][] tabella = {
            {"soleggiato", "alta", "elevata", "debole", "no"},
            {"soleggiato", "bassa", "normale", "debole", "si"},
            {"coperto", "bassa", "elevata", "debole", "si"},
            {"coperto", "bassa", "elevata", "forte", "no"}
    };

    public String classifica(ABE alberoDecisione, int i) {
        String[] row = tabella[i];
        Nodo r = alberoDecisione.radice();
        while (r != null) {
            if(r.etichettaNodo().equals("si") || r.etichettaNodo().equals("no")) {
                return r.etichettaNodo();
            } else {
                if(attributi.containsKey(r.etichettaNodo())) {
                    String value = row[attributi.get(r.etichettaNodo())];
                    if(value.equals(r.etichettaRamoSin())) {
                        r = alberoDecisione.sin(r);
                    } else { // r.etichettaRamoDes().equals(value)
                        r = alberoDecisione.des(r);
                    }
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        ABE albero = new ABEPF();
        albero.aggiungiRadice("Vento");
        ABE temperatura = new ABEPF();
        temperatura.aggiungiRadice("Temperatura");
        ABE no1 = new ABEPF();
        no1.aggiungiRadice("no");
        albero.innestaDes(albero.radice(), no1, "forte");
        ABE no2 = new ABEPF(), si = new ABEPF();
        no2.aggiungiRadice("no");
        si.aggiungiRadice("si");
        temperatura.innestaSin(temperatura.radice(), no2, "alta");
        temperatura.innestaDes(temperatura.radice(), si, "bassa");
        albero.innestaSin(albero.radice(), temperatura, "debole");

        AlberoDecisione alberoDecisione = new AlberoDecisione();
        for(int i=0; i<alberoDecisione.tabella.length; i++) {
            System.out.print("Classifico esempio " + i + ": ");
            for (int j = 0; j < alberoDecisione.tabella[i].length; j++) {
                System.out.print(alberoDecisione.tabella[i][j]);
                if(j != alberoDecisione.tabella[i].length-1)
                    System.out.print(", ");
            }
            System.out.println();
            System.out.println("Classificato: " + alberoDecisione.classifica(albero, i));
        }
    }
}


text:
package com.intellij.codeInsight.actions;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.lang.LanguageImportStatements;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import org.jetbrains.annotations.NonNls;

public class OptimizeImportsAction extends AnAction {
  private static final @NonNls String HELP_ID = "editing.manageImports";

  public void actionPerformed(AnActionEvent event) {
    actionPerformedImpl(event.getDataContext());
  }

  public static void actionPerformedImpl(final DataContext dataContext) {
    final Project project = PlatformDataKeys.PROJECT.getData(dataContext);
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final Editor editor = BaseCodeInsightAction.getInjectedEditor(project, PlatformDataKeys.EDITOR.getData(dataContext));

    final VirtualFile[] files = (VirtualFile[])dataContext.getData(DataConstants.VIRTUAL_FILE_ARRAY);

    PsiFile file = null;
    PsiDirectory dir;

    if (editor != null){
      file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (file == null) return;
      dir = file.getContainingDirectory();
    }
    else if (ReformatCodeAction.areFiles(files)) {
      final ReadonlyStatusHandler.OperationStatus operationStatus = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(files);
      if (!operationStatus.hasReadonlyFiles()) {
        new OptimizeImportsProcessor(project, ReformatCodeAction.convertToPsiFiles(files, project), null).run();
      }
      return;
    }
    else{
      Project projectContext = PlatformDataKeys.PROJECT_CONTEXT.getData(dataContext);
      Module moduleContext = (Module)dataContext.getData(DataConstants.MODULE_CONTEXT);

      if (projectContext != null || moduleContext != null) {
        final String text;
        if (moduleContext != null) {
          text = CodeInsightBundle.message("process.scope.module", moduleContext.getName());
        }
        else {
          text = CodeInsightBundle.message("process.scope.project", projectContext.getPresentableUrl());
        }
        LayoutProjectCodeDialog dialog = new LayoutProjectCodeDialog(project, CodeInsightBundle.message("process.optimize.imports"), text, false);
        dialog.show();
        if (!dialog.isOK()) return;
        if (moduleContext != null) {
          new OptimizeImportsProcessor(project, moduleContext).run();
        }
        else {
          new OptimizeImportsProcessor(projectContext).run();
        }
        return;
      }

      PsiElement element = LangDataKeys.PSI_ELEMENT.getData(dataContext);
      if (element == null) return;
      if (element instanceof PsiDirectoryContainer) {
        dir = ((PsiDirectoryContainer)element).getDirectories()[0];
      }
      else if (element instanceof PsiDirectory) {
        dir = (PsiDirectory)element;
      }
      else{
        file = element.getContainingFile();
        if (file == null) return;
        dir = file.getContainingDirectory();
      }
    }

    boolean processDirectory;
    boolean includeSubdirectories;

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      includeSubdirectories = processDirectory = false;
    } else {
      final LayoutCodeDialog dialog = new LayoutCodeDialog(project, CodeInsightBundle.message("process.optimize.imports"), file, dir, null, HELP_ID);
      dialog.show();
      if (!dialog.isOK()) return;
      processDirectory = dialog.isProcessDirectory();
      includeSubdirectories = dialog.isIncludeSubdirectories();
    }

    if (processDirectory){
      new OptimizeImportsProcessor(project, dir, includeSubdirectories).run();
    }
    else{
      new OptimizeImportsProcessor(project, file).run();
    }
  }

  public void update(AnActionEvent event){
    if (!LanguageImportStatements.INSTANCE.hasAnyExtensions()) {
      event.getPresentation().setVisible(false);
      return;
    }

    Presentation presentation = event.getPresentation();
    DataContext dataContext = event.getDataContext();
    Project project = PlatformDataKeys.PROJECT.getData(dataContext);
    if (project == null){
      presentation.setEnabled(false);
      return;
    }

    final VirtualFile[] files = (VirtualFile[])dataContext.getData(DataConstants.VIRTUAL_FILE_ARRAY);

    final Editor editor = BaseCodeInsightAction.getInjectedEditor(project, PlatformDataKeys.EDITOR.getData(dataContext), false);
    if (editor != null){
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (file == null || !isOptimizeImportsAvailable(file)){
        presentation.setEnabled(false);
        return;
      }
    }
    else if (files != null && ReformatCodeAction.areFiles(files)) {
      boolean anyHasOptimizeImports = false;
      for (VirtualFile virtualFile : files) {
        PsiFile file = PsiManager.getInstance(project).findFile(virtualFile);
        if (file == null) {
          presentation.setEnabled(false);
          return;
        }
        if (isOptimizeImportsAvailable(file)) {
          anyHasOptimizeImports = true;
        }
      }
      if (!anyHasOptimizeImports) {
        presentation.setEnabled(false);
        return;
      }
    }
    else if (files != null && files.length == 1) {
      // skip. Both directories and single files are supported.
    }
    else if (dataContext.getData(DataConstants.MODULE_CONTEXT) == null &&
             dataContext.getData(DataConstants.PROJECT_CONTEXT) == null) {
      PsiElement element = LangDataKeys.PSI_ELEMENT.getData(dataContext);
      if (element == null){
        presentation.setEnabled(false);
        return;
      }

      if (!(element instanceof PsiDirectory)){
        PsiFile file = element.getContainingFile();
        if (file == null || !isOptimizeImportsAvailable(file)){
          presentation.setEnabled(false);
          return;
        }
      }
    }

    presentation.setEnabled(true);
  }

  private static boolean isOptimizeImportsAvailable(final PsiFile file) {
    return LanguageImportStatements.INSTANCE.forFile(file) != null;
  }
}


text:
{% extends 'federation/base.html' %}

{% load common ui %}

{% block head_title %}Providers{% endblock %}

{% block nav_providers %}active{% endblock %}

{% block subnav %}

Providers

Create Provider

{% endblock %}

{% block breadcrumbs %}
{% url federation_providers as url %}{% breadcrumb 'Providers' url %}{{ block.super }}
{% endblock %}


text:
#include <iomanip>
#include "spdlog/fmt/fmt.h"

#include "LIEF/PE/hash.hpp"

#include "LIEF/PE/DelayImportEntry.hpp"

namespace LIEF {
namespace PE {
DelayImportEntry::DelayImportEntry(const DelayImportEntry&) = default;
DelayImportEntry& DelayImportEntry::operator=(const DelayImportEntry&) = default;

DelayImportEntry::DelayImportEntry(DelayImportEntry&&) = default;
DelayImportEntry& DelayImportEntry::operator=(DelayImportEntry&&) = default;

DelayImportEntry::~DelayImportEntry() = default;

DelayImportEntry::DelayImportEntry() = default;

DelayImportEntry::DelayImportEntry(uint64_t data, PE_TYPE type) :
  data_{data},
  type_{type}
{}

bool DelayImportEntry::is_ordinal() const {
  // See: https://docs.microsoft.com/en-us/windows/desktop/debug/pe-format#the-idata-section
  const uint64_t ORDINAL_MASK = type_ == PE_TYPE::PE32 ? 0x80000000 : 0x8000000000000000;
  bool ordinal_bit_is_set = static_cast<bool>(data_ & ORDINAL_MASK);

  // Check that bit 31 / 63 is set
  if (!ordinal_bit_is_set) {
    return false;
  }
  // Check that bits 30-15 / 62-15 are set to 0.
  uint64_t val = (data_ & ~ORDINAL_MASK) >> 15;
  return val == 0;
}

uint16_t DelayImportEntry::ordinal() const {
  return data_ & 0xFFFF;
}

uint16_t DelayImportEntry::hint() const {
  return hint_;
}

uint64_t DelayImportEntry::iat_value() const {
  return iat_value_;
}

uint64_t DelayImportEntry::hint_name_rva() const {
  return data();
}

uint64_t DelayImportEntry::data() const {
  return data_;
}

void DelayImportEntry::data(uint64_t data) {
  data_ = data;
}

void DelayImportEntry::accept(LIEF::Visitor& visitor) const {
  visitor.visit(*this);
}

bool DelayImportEntry::operator==(const DelayImportEntry& rhs) const {
  if (this == &rhs) {
    return true;
  }
  size_t hash_lhs = Hash::hash(*this);
  size_t hash_rhs = Hash::hash(rhs);
  return hash_lhs == hash_rhs;
}

bool DelayImportEntry::operator!=(const DelayImportEntry& rhs) const {
  return !(*this == rhs);
}

std::ostream& operator<<(std::ostream& os, const DelayImportEntry& entry) {
  if (entry.is_ordinal()) {
    os << "#" << entry.ordinal();
  } else {
    os << fmt::format("{:<20}", entry.name());
  }

  os << fmt::format(": 0x{:x}", entry.iat_value());
  return os;
}

} // namespace PE
} // namepsace LIEF


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _pure = require('recompose/pure');

var _pure2 = _interopRequireDefault(_pure);

var _SvgIcon = require('../../SvgIcon');

var _SvgIcon2 = _interopRequireDefault(_SvgIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var ActionLineWeight = function ActionLineWeight(props) {
  return _react2.default.createElement(
    _SvgIcon2.default,
    props,
    _react2.default.createElement('path', { d: 'M3 17h18v-2H3v2zm0 3h18v-1H3v1zm0-7h18v-3H3v3zm0-9v4h18V4H3z' })
  );
};
ActionLineWeight = (0, _pure2.default)(ActionLineWeight);
ActionLineWeight.displayName = 'ActionLineWeight';
ActionLineWeight.muiName = 'SvgIcon';

exports.default = ActionLineWeight;


text:
package org.iternine.jeppetto.dao.test;

public enum SimpleEnum {
    EnumValue,
}


text:
"""Python 2.x/3.x compatibility utilities.

This module defines a collection of functions that allow the same Python
source code to be used in both Python 2.x and Python 3.x.

 - prnt() prints its arguments to a file, with given separator and ending.
 - to_long() creates a (long) integer object from its input parameter.
 - u() allows string literals involving non-ASCII characters to be
   used in both Python 2.x / 3.x, e.g. u("\u0101 is a-with-macron")
 - uchr() generates a single character Unicode string whose point code
   is the given (integer) argument, e.g. uchr(257).
 - unicod() forces its argument to a Unicode string.
 - rpr() generates a representation of a string that can be parsed in either
   Python 2.x or 3.x, assuming use of the u() function above.

>>> from .util import prnt, u, uchr, rpr
>>> prnt("hello")
hello
>>> prnt("hello", "world")
hello world
>>> prnt("hello", "world", sep=":")
hello:world
>>> prnt("hello", "world", sep=":", end='!\\n')
hello:world!
>>> u('\u0101') == uchr(0x0101)
True
>>> u('\u0101') == u('\U00000101')
True
>>> u('\u0101') == u('\N{LATIN SMALL LETTER A WITH MACRON}')
True
>>> a_macron = u('\u0101')
>>> rpr(a_macron)
"u('\\\\u0101')"
>>> rpr(u('abc')) == "'abc'"  # In Python 2, LHS is Unicode but RHS is string
True
>>> rpr("'")
"'\\\\''"
"""
import sys

if sys.version_info >= (3, 0):  # pragma no cover
    import builtins
    print3 = builtins.__dict__['print']

    unicod = str
    u = str
    uchr = chr
    to_long = int

    def prnt(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        file = kwargs.get('file', None)
        print3(*args, **{'sep': sep, 'end': end, 'file': file})

    class UnicodeMixin(object):
        """Mixin class to define a __str__ method in terms of __unicode__ method"""
        __str__ = lambda x: x.__unicode__()

else:  # pragma no cover
    unicod = unicode

    import unicodedata
    import re
    # \N{name} = character named name in the Unicode database
    _UNAME_RE = re.compile(r'\\N\{(?P<name>[^}]+)\}')
    # \uxxxx = character with 16-bit hex value xxxx
    _U16_RE = re.compile(r'\\u(?P<hexval>[0-9a-fA-F]{4})')
    # \Uxxxxxxxx = character with 32-bit hex value xxxxxxxx
    _U32_RE = re.compile(r'\\U(?P<hexval>[0-9a-fA-F]{8})')

    def u(s):
        """Generate Unicode string from a string input, encoding Unicode characters.

        This is expected to work in the same way as u'<string>' would work in Python
        2.x (although it is not completely robust as it is based on a simple set of
        regexps).
        """
        us = re.sub(_U16_RE, lambda m: unichr(int(m.group('hexval'), 16)), unicode(s))
        us = re.sub(_U32_RE, lambda m: unichr(int(m.group('hexval'), 16)), us)
        us = re.sub(_UNAME_RE, lambda m: unicodedata.lookup(m.group('name')), us)
        return us

    uchr = unichr
    to_long = long

    def prnt(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        file = kwargs.get('file', None)
        if file is None:
            file = sys.stdout
        print >> file, sep.join([str(arg) for arg in args]) + end,

    class UnicodeMixin(object):  # pragma no cover
        """Mixin class to define a __str__ method in terms of __unicode__ method"""
        __str__ = lambda x: unicode(x).encode('utf-8')

# Constants for Unicode strings
U_EMPTY_STRING = unicod("")
U_SPACE = unicod(" ")
U_DASH = unicod("-")
U_TILDE = unicod("~")
U_ZERO = unicod("0")
U_SLASH = unicod("/")
U_SEMICOLON = unicod(";")
U_X_LOWER = unicod("x")
U_X_UPPER = unicod("X")
U_PERCENT = unicod("%")

def rpr(s):
    """Create a representation of a Unicode string that can be used in both
    Python 2 and Python 3k, allowing for use of the u() function"""
    if s is None:
        return 'None'
    seen_unicode = False
    results = []
    for cc in s:
        ccn = ord(cc)
        if ccn >= 32 and ccn < 127:
            if cc == "'":  # escape single quote
                results.append('\\')
                results.append(cc)
            elif cc == "\\":  # escape backslash
                results.append('\\')
                results.append(cc)
            else:
                results.append(cc)
        else:
            seen_unicode = True
            if ccn <= 0xFFFF:
                results.append('\\u')
                results.append("%04x" % ccn)
            else:  # pragma no cover
                results.append('\\U')
                results.append("%08x" % ccn)
    result = "'" + "".join(results) + "'"
    if seen_unicode:
        return "u(" + result + ")"
    else:
        return result

def force_unicode(s):
    """Force the argument to be a Unicode string, preserving None"""
    if s is None:
        return None
    else:
        return unicod(s)

class ImmutableMixin(object):
    """Mixin class to make objects of subclasses immutable"""
    _mutable = False

    def __setattr__(self, name, value):
        if self._mutable or name == "_mutable":
            object.__setattr__(self, name, value)
        else:
            raise TypeError("Can't modify immutable instance")

    def __delattr__(self, name):
        if self._mutable:
            object.__delattr__(self, name)
        else:
            raise TypeError("Can't modify immutable instance")

def mutating_method(func):
    """Decorator for methods that are allowed to modify immutable objects"""
    def wrapper(self, *__args, **__kwargs):
        old_mutable = self._mutable
        self._mutable = True
        try:
            # Call the wrapped function
            return func(self, *__args, **__kwargs)
        finally:
            self._mutable = old_mutable
    return wrapper

if __name__ == '__main__':  # pragma no cover
    import doctest
    doctest.testmod()


text:
 One possible counterexample is during initialization: if the library truly cannot set itself up, it might be reasonable to panic, so to speak.

 When panic is called, including implicitly for run-time errors such as indexing a slice out of bounds or failing a type assertion, it immediately stops execution of the current function and begins unwinding the stack of the goroutine, running any deferred functions along the way. If that unwinding reaches the top of the goroutine's stack, the program dies.

 A call to recover stops the unwinding and returns the argument passed to panic.
**Because the only code that runs while unwinding is inside deferred functions, recover is only useful inside deferred functions**

One application of recover is to shut down a failing goroutine inside a server without killing the other executing goroutines.

```go
func server(workChan <-chan *Work) {
    for work := range workChan {
        go safelyDo(work)
    }
}

func safelyDo(work *Work) {
    defer func() {
        if err := recover(); err != nil {
            log.Println("work failed:", err)
        }
    }()
    do(work)
}
```
In this example, if do(work) panics, the result will be logged and the goroutine will exit cleanly without disturbing the others. There's no need to do anything else in the deferred closure; calling recover handles the condition completely.

## context

## Go HTTP server
- create flag
```go
import "flag"

var addr = flag.String("addr", ":8080", "description)
func main(){
flag.Parse()
fmt.Println(*addr)
}
```
- create server
```go
import "net/http"

func main(){
  http.Handle("/", http.HandlerFunc(MyFunc))
  err := http.ListenAndServe(":8080", nil)
  if err != nil{
    log.Fatalf(err)
  }
}
func MyFunc(w http.ResponseWriter, r *http.Request){
}

```

```go

package main

import (
    "flag"
    "html/template"
    "log"
    "net/http"
)

var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18

var templ = template.Must(template.New("qr").Parse(templateStr))

func main() {
    flag.Parse()
    http.Handle("/", http.HandlerFunc(QR))
    err := http.ListenAndServe(*addr, nil)
    if err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}
func QR(w http.ResponseWriter, req *http.Request) {
    templ.Execute(w, req.FormValue("s"))
}

const templateStr = `
<html>
<head>
<title>QR Link Generator</title>
</head>
<body>
{{if .}}
<img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl={{.}}" />
<br>
{{.}}
<br>
<br>
{{end}}
<form action="/" name=f method="GET">
    <input maxLength=1024 size=70 name=s value="" title="Text to QR Encode">
    <input type=submit value="Show QR" name=qr>
</form>
</body>
</html>
`
```

## interface

## inheritance

## embedded types

## pass by value Vs reference

## error
```
type error interface {
    Error() string
}
```


text:
package org.dcm4chee.web.war.folder.webviewer;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.wicket.Page;
import org.apache.wicket.PageMap;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.link.PopupSettings;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WebRequestCycle;
import org.apache.wicket.protocol.http.WebResponse;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.protocol.http.request.WebClientInfo;
import org.apache.wicket.request.target.basic.EmptyRequestTarget;
import org.dcm4che2.data.UID;
import org.dcm4chee.archive.entity.StudyPermission;
import org.dcm4chee.icons.ImageManager;
import org.dcm4chee.icons.behaviours.ImageSizeBehaviour;
import org.dcm4chee.web.common.behaviours.TooltipBehaviour;
import org.dcm4chee.web.common.markup.ModalWindowLink;
import org.dcm4chee.web.common.webview.link.WebviewerLinkProvider;
import org.dcm4chee.web.war.StudyPermissionHelper;
import org.dcm4chee.web.war.common.model.AbstractDicomModel;
import org.dcm4chee.web.war.config.delegate.WebCfgDelegate;
import org.dcm4chee.web.war.folder.model.InstanceModel;
import org.dcm4chee.web.war.folder.model.PatientModel;
import org.dcm4chee.web.war.folder.model.SeriesModel;
import org.dcm4chee.web.war.folder.model.StudyModel;
import org.dcm4chee.web.war.tc.TCModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Franz Willer <franz.willer@gmail.com>
 * @version $Revision: 18453 $ $Date: 2015-05-24 00:41:04 +0800 (周日, 24 5月 2015) $
 * @since May 24, 2011
 */
public class Webviewer  {

    private static final String WEBVIEW_ID = "webview";
    private static Logger log = LoggerFactory.getLogger(Webviewer.class);

    public static AbstractLink getLink(final AbstractDicomModel model, final WebviewerLinkProvider[] providers,
            final StudyPermissionHelper studyPermissionHelper, TooltipBehaviour tooltip, ModalWindow modalWindow) {
    	return getLink(model, providers, studyPermissionHelper, tooltip, modalWindow, null);
    }

    @SuppressWarnings("serial")
	public static AbstractLink getLink(final AbstractDicomModel model, final WebviewerLinkProvider[] providers,
            final StudyPermissionHelper studyPermissionHelper, TooltipBehaviour tooltip, ModalWindow modalWindow,
            final WebviewerLinkClickedCallback callback) {
        final WebviewerLinkProvider[] p = {null};
        AbstractLink link = null;
        if (providers != null)
            for (int i = 0 ; i < providers.length ; i++) {
                if (isLevelSupported(model, providers[i])) {
                    if (p[0] == null) {
                        p[0] = providers[i];
                    } else {
                        link = getWebviewerSelectionPageLink(model, providers, modalWindow, callback);
                        break;
                    }
                }
            }
        if (p[0] == null) {
            link = new ExternalLink(WEBVIEW_ID, "http://dummy");
            link.setVisible(false);
        } else {
            if (link == null) {
                if (p[0].hasOwnWindow()) {
                    String url = getUrlForModel(model, p[0]);
                    link = new ExternalLink(WEBVIEW_ID, url);
                	((ExternalLink)link).setPopupSettings(getPopupSettingsForDirectGET(url));
                } else if (p[0].supportViewingAllSelection()) {
                    link = new Link<Object>(WEBVIEW_ID) {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public void onClick() {
                            try {
                                ExportDicomModel dicomModel = new ExportDicomModel(model);

                                RequestCycle.get().setRequestTarget(EmptyRequestTarget.getInstance());

                                HttpServletRequest request =
                                    ((WebRequestCycle) RequestCycle.get()).getWebRequest().getHttpServletRequest();
                                HttpServletResponse response =
                                    ((WebResponse) getRequestCycle().getResponse()).getHttpServletResponse();
                                String result =p[0].viewAllSelection(dicomModel.getPatients(), request, response);
                                if (!p[0].notWebPageLinkTarget()){
                                    ViewerPage page = new ViewerPage();
                                    page.add(new Label("viewer", new Model<String>(result)).setEscapeModelStrings(false));
                                    this.setResponsePage(page);
                                }
                            } catch (Exception e) {
                                log.error("Cannot view the selection!", e);
                                if (p[0].notWebPageLinkTarget()) {
                                    setResponsePage(getPage());
                                }
                            }
                        }
                    };

                    WebClientInfo clientInfo = (WebClientInfo)WebRequestCycle.get().getClientInfo();
                    String browser = clientInfo.getUserAgent();

                    if (!p[0].notWebPageLinkTarget() || (browser != null && browser.contains("Firefox"))){
                        ((Link) link).setPopupSettings(new PopupSettings(PageMap.forName("webviewPage"),
                            PopupSettings.RESIZABLE|PopupSettings.SCROLLBARS));
                    }
                } else {
                    link =  new Link<Object>(WEBVIEW_ID) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        public void onClick() {
                            setResponsePage(new WebviewerRedirectPage(model, p[0]));
                        }
                    };
                    ((Link) link).setPopupSettings(new PopupSettings(PageMap.forName("webviewPage"),
                        PopupSettings.RESIZABLE|PopupSettings.SCROLLBARS));
                }
                if (callback!=null) {
                	link.add(new AjaxEventBehavior("onclick") {
						@Override
						public void onEvent(AjaxRequestTarget target) {
                			callback.linkClicked(target);
                		}
						// just for the case, if the link is rendered as a <button> element
						@Override
						protected void onComponentTag(ComponentTag tag) {
							String current = tag.getAttribute("onclick");

							super.onComponentTag(tag);

							if (current!=null) {
								tag.put("onclick", new StringBuilder(tag.getAttribute("onclick"))
									.append(";").append(current));
							}
						}
                	});
                }
            }
            if (model instanceof PatientModel) {
                link.setVisible(studyPermissionHelper.checkPermission(model.getDicomModelsOfNextLevel(),
                        StudyPermission.READ_ACTION, false));
            } else {
                link.setVisible(studyPermissionHelper.checkPermission(model, StudyPermission.READ_ACTION));
            }
        }
        Image image = new Image("webviewImg",ImageManager.IMAGE_FOLDER_VIEWER);
        image.add(new ImageSizeBehaviour("vertical-align: middle;"));
        if (tooltip != null) image.add(tooltip);
        link.add(image);
        return link;
    }

    public static PopupSettings getPopupSettingsForDirectGET(final String url) {
		PopupSettings ps = new PopupSettings(){
			@Override
			public String getPopupJavaScript(){
				return getSendHttpRequestJavascript(url)+"return false;";
			}
		};
		return ps;
	}
    public static String getSendHttpRequestJavascript(final String url) {
			StringBuilder sb = new StringBuilder();
			sb.append("xmlHttp = new XMLHttpRequest();")
			.append("xmlHttp.open( 'GET', '").append(url).append("&zz=").append("'+new Date().getTime(), true );")
			.append("xmlHttp.send( null );");
			return sb.toString();
	}

	private static AbstractLink getWebviewerSelectionPageLink(final AbstractDicomModel model, final WebviewerLinkProvider[] providers, final ModalWindow modalWindow,
    		final WebviewerLinkClickedCallback callback) {
        log.debug("Use SelectionLINK for model:{}", model);
        if (modalWindow == null) {
            Link<Object> link =  new Link<Object>(WEBVIEW_ID) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick() {
                    setResponsePage(new WebviewerSelectionPage(model, providers, null, callback));
                }
            };
            link.setPopupSettings(new PopupSettings(PageMap.forName("webviewPage"),
                    PopupSettings.RESIZABLE|PopupSettings.SCROLLBARS));
            return link;
        } else {
            int[] winSize = WebCfgDelegate.getInstance().getWindowSize("webviewer");
            return new ModalWindowLink(WEBVIEW_ID, modalWindow, winSize[0], winSize[1]) {

                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(AjaxRequestTarget target) {

                    modalWindow.setPageCreator(new ModalWindow.PageCreator() {

                        private static final long serialVersionUID = 1L;

                        @Override
                        public Page createPage() {
                            return new WebviewerSelectionPage(model, providers, modalWindow, callback);
                        }
                    });
                    modalWindow.setTitle("");
                    modalWindow.show(target);
                }

            };
        }
    }

	public static boolean isLevelSupported(AbstractDicomModel model, WebviewerLinkProvider provider) {
        switch (model.levelOfModel()) {
        case AbstractDicomModel.PATIENT_LEVEL:
            return provider.supportPatientLevel();
        case AbstractDicomModel.STUDY_LEVEL:
        	return provider.supportStudyLevel();
        case AbstractDicomModel.SERIES_LEVEL:
        	return provider.supportSeriesLevel();
        case AbstractDicomModel.INSTANCE_LEVEL:
        	if ( model instanceof TCModel && !provider.supportStructuredReport() ) {
        		return provider.supportStudyLevel();
        	} else {
        		return provider.supportInstanceLevel();
            }
        default:
            log.warn("Level of Model not supported by this Webviewer Selection Page! model:"+
                    model.getClass().getName()+" level:"+model.levelOfModel());
            return false;
        }
	}

    public static String getUrlForModel(AbstractDicomModel model, WebviewerLinkProvider provider) {
        switch (model.levelOfModel()) {
            case AbstractDicomModel.PATIENT_LEVEL:
                if (provider.supportPatientLevel()) {
                    PatientModel pat = (PatientModel) model;
                    return provider.getUrlForPatient(pat.getId(), pat.getIssuer());
                }
                break;
            case AbstractDicomModel.STUDY_LEVEL:
                if (provider.supportStudyLevel()) {
                    return provider.getUrlForStudy(((StudyModel) model).getStudyInstanceUID());
                }
                break;
            case AbstractDicomModel.SERIES_LEVEL:
                if (provider.supportSeriesLevel()) {
                    return provider.getUrlForSeries(((SeriesModel) model).getSeriesInstanceUID());
                }
                break;
            case AbstractDicomModel.INSTANCE_LEVEL:
            	// WEB-1109: if we want to open a teaching-file (i.e referenced images) within
            	// an external viewer but the viewer doesn't support SR parsing/loading, just
            	// open whole study
            	if ( model instanceof TCModel &&
            			!provider.supportStructuredReport() )
            	{
            		if ( provider.supportStudyLevel() )
            		{
            			return provider.getUrlForStudy( ((TCModel)model).getStudyInstanceUID() );
            		}
            	}
                if (provider.supportInstanceLevel()) {
                    String iuid = ((InstanceModel) model).getSOPInstanceUID();
                    String cuid = ((InstanceModel) model).getSopClassUID();
                    if (UID.KeyObjectSelectionDocumentStorage.equals(cuid) && provider.supportKeySelectionObject()) {
                        return provider.getUrlForKeyObjectSelection(iuid);
                    }
                    int type = WebCfgDelegate.getInstance().checkCUID(cuid);
                    if (type == 1 && provider.supportStructuredReport()) {
                        return provider.getUrlForStructuredReport(iuid);
                    } else if (type == 5 && provider.supportPresentationState()) {
                        return provider.getUrlForPresentationState(iuid);
                    }
                    return provider.getUrlForInstance(iuid);
                }
                break;
            default:
                log.warn("Level of Model not supported by this Webviewer Selection Page! model:"+
                        model.getClass().getName()+" level:"+model.levelOfModel());
                return null;
        }
        log.debug("WebviewerProvider {} doesn't support DICOM model with level:{}", provider.getName(), model.levelOfModel());
        return null;
    }

    public static interface WebviewerLinkClickedCallback extends Serializable {
    	public void linkClicked(AjaxRequestTarget target);
    }
}


text:
from dateutil.parser import parse
import os
import json

"""
We must prevent CashupUrlGenerator from being imported when we only want to
generated documentation of the classes in this file.
"""
if not os.environ.get('DOC'):
    from kounta.cashup import CashupUrlGenerator

class BaseObject:
    """
    Used as the parent for all objects returned from the API. It main purpose is
    to allow documentation to be built into the object instead of using plain
    `dict`s.
    """

    def __init__(self, obj, client, company):
        """
        :type company: Company|None
        :type client: kounta.client.BasicClient
        :type obj: dict
        """

        assert isinstance(company, Company) or company is None

        self.obj = obj
        self._client = client
        self._company = company

    def __getattr__(self, item):
        """
        Returns an attribute as it was originally set in the raw object.
        :type item: str
        """
        return self.obj[item]

    def __str__(self):
        """
        When converting any API object to a string the original JSON fetched
        will be returned.

        It is important to recognise that this JSON may not represent the actual
        state of the object behind it because some calls may make further API
        requests.
        """
        return json.dumps(self.obj)

    def _make_address(self, field):
        """
        Test if a `field` is not None and return an Address object. Otherwise
        return None
        :type field: str
        """
        address = self.obj[field]
        if address:
            return Address(address, self._client, self._company)
        return None

    def _get_addresses(self, url):
        """
        :return: Address[]
        """
        url = '/v1/companies/%d/%s' % (self._company.id, url)
        addresses = self._client.get_url(url)
        return [Address(address, self._client, self._company) for address in
                addresses]

    def _get_cashups(self, url, **kwargs):
        """
        :return: Cashup[]
        """
        generator = CashupUrlGenerator()
        url = '%s/%s' % (url, generator.get_url(**kwargs))
        cashups = self._client.get_url(url)
        return [Cashup(cashup, self._client, self._company) for cashup
                in cashups]

    def _get_categories(self, url):
        """
        :return: Category[]
        """
        categories = self._client.get_url(url)
        return [Category(category, self._client, self._company) for category in
                categories]

class Address(BaseObject):
    """
    Addresses are physical or postal locations belonging to a staff member,
    customer, company or site.
    """

    @property
    def id(self):
        """
        Address ID.
        :return: int
        """
        return self.obj['id']

    @property
    def city(self):
        """
        City/suburb.
        :return: str
        """
        return self.obj['city']

    @property
    def lines(self):
        """
        Address lines.
        :return: str[]
        """
        return self.obj['lines']

    @property
    def zone(self):
        """
        Zone/state.
        :return: str
        """
        return self.obj['zone']

    @property
    def postal_code(self):
        """
        Postal code.
        :return: str
        """
        return self.obj['postal_code']

    @property
    def country(self):
        """
        Country.
        :return: str
        """
        return self.obj['country']

class Company(BaseObject):
    """
    Companies are businesses who use Kounta at their points of sale. A company
    may have one or more registers running Kounta on one or more sites.
    """

    @property
    def id(self):
        """
        Company ID.
        :return: int
        """
        return self.obj['id']

    @property
    def name(self):
        """
        Company name.
        :return: str
        """
        return self.obj['name']

    @property
    def shipping_address(self):
        """
        Shipping address.
        :return: Address
        """
        return self._make_address('shipping_address')

    @property
    def postal_address(self):
        """
        Postal address.
        :return: Address
        """
        return self._make_address('postal_address')

    @property
    def addresses(self):
        """
        All addresses attached to this company.
        :return: Address[]
        """
        url = '/v1/companies/%d/addresses.json' % self.id
        addresses = self._client.get_url(url)
        return [Address(address, self._client, self) for address in addresses]

    @property
    def business_number(self):
        """
        ABN, ACN or whatever is applicable as the business number.
        :return: str
        """
        return self.obj['business_number']

    @property
    def contact_staff_member(self):
        """
        Contact staff member.
        :return: Staff
        """
        return Staff(self.obj['contact_staff_member'], self._client, self)

    @property
    def image(self):
        """
        Avatar image.
        :return: str
        """
        return self.obj['image']

    @property
    def website(self):
        """
        Website.
        :return: str
        """
        return self.obj['website']

    @property
    def currency(self):
        """
        Currency code.
        :return: str
        """
        return self.obj['currency']

    @property
    def timezone(self):
        """
        Timezone information.
        :return: Timezone
        """
        return Timezone(self.obj['timezone'], self._client, self)

    @property
    def sites(self):
        """
        Fetch all sites for this company.
        :return: Site[]
        """
        sites = self._client.get_url('/v1/companies/%d/sites.json' % self.id)
        return [Site(site, self._client, self) for site in sites]

    @property
    def registers(self):
        """
        Fetch all registers for this company.
        :return: Register[]
        """
        url = '/v1/companies/%d/registers.json' % self.id
        registers = self._client.get_url(url)
        return [Register(register, self._client, self._company) for register in
                registers]

    @property
    def created_at(self):
        """
        When the company was created.
        :return: datetime
        """
        return parse(self.obj['created_at'])

    @property
    def updated_at(self):
        """
        When the company was last modified.
        :return: datetime
        """
        return parse(self.obj['updated_at'])

    def cashups(self, **kwargs):
        """
        Fetch cashups for a company. Refer to documentation for Cashups for more
        information.
        :rtype : Cashup[]
        """
        return self._get_cashups('/v1/companies/%d' % self.id, **kwargs)

    @property
    def categories(self):
        """
        All categories for this company.
        :rtype : Category[]
        """
        url = '/v1/companies/%d/categories.json' % self.id
        return self._get_categories(url)

class Permission(BaseObject):
    @property
    def code(self):
        """
        :rtype : str
        """
        return self.obj['code']

    @property
    def name(self):
        """
        :rtype : str
        """
        return self.obj['name']

    @property
    def domain(self):
        """
        :rtype : str
        """
        return self.obj['domain']

class Timezone(BaseObject):
    """
    A timezone represents a time offset at a geographical location.
    """

    @property
    def offset(self):
        """
        :rtype : str
        """
        return self.obj['offset']

    @property
    def name(self):
        """
        :rtype : str
        """
        return self.obj['name']

class Staff(BaseObject):
    """
    Staff members are people who work for the authenticated company.
    """

    @property
    def id(self):
        """
        :rtype: int
        """
        return self.obj['id']

    @property
    def first_name(self):
        """
        :rtype: str
        """
        return self.obj['first_name']

    @property
    def last_name(self):
        """
        :rtype: str
        """
        return self.obj['last_name']

    @property
    def is_admin(self):
        """
        :rtype: boolean
        """
        return self.obj['is_admin']

    @property
    def primary_email_address(self):
        """
        :rtype: str
        """
        return self.obj['primary_email_address']

    @property
    def email_addresses(self):
        """
        :rtype: str[]
        """
        return self.obj['email_addresses']

    @property
    def phone(self):
        """
        :rtype: str
        """
        return self.obj['phone']

    @property
    def mobile(self):
        """
        :rtype: str
        """
        return self.obj['mobile']

    @property
    def fax(self):
        """
        :rtype: str
        """
        return self.obj['fax']

    @property
    def shipping_address(self):
        """
        :return: Address
        """
        return self._make_address('shipping_address')

    @property
    def postal_address(self):
        """
        :return: Address
        """
        return self._make_address('postal_address')

    @property
    def permissions(self):
        """
        :return: Permission[]
        """
        return [Permission(p, self._client, self._company) for p in
                self.obj['permissions']]

    @property
    def image(self):
        """
        :rtype: str
        """
        return self.obj['image']

    @property
    def created_at(self):
        """
        :rtype: str
        """
        return parse(self.obj['created_at'])

    @property
    def updated_at(self):
        """
        :rtype: str
        """
        return parse(self.obj['updated_at'])

    @property
    def addresses(self):
        """
        All addresses attached to this staff member.
        :return: Address[]
        """
        return self._get_addresses('staff/%d/addresses.json' % self.id)

class Site(BaseObject):
    """
    Sites are physical locations, such as outlets, offices etc, at which one or
    more Kountas will be used.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def name(self):
        """
        :return: str
        """
        return self.obj['name']

    @property
    def code(self):
        """
        :return: str
        """
        return self.obj['code']

    @property
    def contact_person(self):
        """
        :return: Staff
        """
        return Staff(self.obj['contact_person'], self._client, self._company)

    @property
    def business_number(self):
        """
        :return: str
        """
        return self.obj['business_number']

    @property
    def shipping_address(self):
        """
        :return: Address
        """
        return self._make_address('shipping_address')

    @property
    def postal_address(self):
        """
        :return: Address
        """
        return self._make_address('postal_address')

    @property
    def email(self):
        """
        :return: str
        """
        return self.obj['email']

    @property
    def mobile(self):
        """
        :return: str
        """
        return self.obj['mobile']

    @property
    def phone(self):
        """
        :return: str
        """
        return self.obj['phone']

    @property
    def fax(self):
        """
        :return: str
        """
        return self.obj['fax']

    @property
    def location(self):
        """
        :return: Location
        """
        return Location(self.obj['location'], self._client, self._company)

    @property
    def image(self):
        """
        :return: str
        """
        return self.obj['image']

    @property
    def website(self):
        """
        :return: str
        """
        return self.obj['website']

    @property
    def register_level_reconciliation(self):
        """
        :return: boolean
        """
        return self.obj['register_level_reconciliation']

    @property
    def price_list(self):
        """
        :return: PriceList
        """
        return PriceList(self.obj['price_list'], self._client, self._company)

    @property
    def created_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['created_at'])

    @property
    def updated_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['updated_at'])

    @property
    def addresses(self):
        """
        All addresses attached to this site.
        :return: Address[]
        """
        return self._get_addresses('sites/%d/addresses.json' % self.id)

    def cashups(self, **kwargs):
        """
        Fetch cashups for a register. Refer to documentation for Cashups for
        more information.
        :rtype : Cashup[]
        """
        url = '/v1/companies/%d/sites/%d' % (self._company.id, self.id)
        return self._get_cashups(url, **kwargs)

    @property
    def categories(self):
        """
        All categories for this site.
        :rtype : Category[]
        """
        url = '/v1/companies/%d/sites/%d/categories.json' % (self._company.id,
                                                            self.id)
        return self._get_categories(url)

    @property
    def checkins(self):
        """
        All checkins for this site.
        :rtype : Checkin[]
        """
        url = '/v1/companies/%d/sites/%d/checkins.json' % (self._company.id, self.id)
        checkins = self._client.get_url(url)
        return [Checkin(checkin, self._client, self._company) for checkin in
                checkins]

class Category(BaseObject):
    """
    Each product will belong to one or more categories.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def name(self):
        """
        :return: int
        """
        return self.obj['name']

    @property
    def description(self):
        """
        :return: str
        """
        return self.obj['description']

    @property
    def image(self):
        """
        :return: str
        """
        return self.obj['image']

class Product(BaseObject):
    """
    Products are saleable items in your inventory, including modifier products.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def name(self):
        """
        :return: int
        """
        return self.obj['name']

    @property
    def description(self):
        """
        :return: str
        """
        return self.obj['description']

    @property
    def code(self):
        """
        :return: str
        """
        return self.obj['code']

    @property
    def barcode(self):
        """
        :return: str
        """
        return self.obj['barcode']

    @property
    def categories(self):
        """
        All categories for this product.
        :rtype : Category[]
        """
        url = '/v1/companies/%d/products/%d/categories.json' % \
              (self._company.id, self.id)
        return self._get_categories(url)

class Checkin(BaseObject):
    """
    Authenticated customers can use checkin service.
    """

    @property
    def customer_id(self):
        """
        :return: int
        """
        return self.obj['customer_id']

    @property
    def start_time(self):
        """
        :return: datetime
        """
        return parse(self.obj['start_time'])

    @property
    def duration(self):
        """
        :return: int
        """
        return self.obj['duration']

class Customer(BaseObject):
    """
    Customers are people who buy from the authenticated company.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def first_name(self):
        """
        :return: str
        """
        return self.obj['first_name']

    @property
    def last_name(self):
        """
        :return: str
        """
        return self.obj['last_name']

    @property
    def primary_email_address(self):
        """
        :return: str
        """
        return self.obj['primary_email_address']

    @property
    def image(self):
        """
        :return: str
        """
        return self.obj['image']

    @property
    def reference_id(self):
        """
        :return: str
        """
        return self.obj['reference_id']

    @property
    def addresses(self):
        """
        All addresses attached to this customer.
        :return: Address[]
        """
        return self._get_addresses('customer/%d/addresses.json' % self.id)

class Inventory(BaseObject):
    """
    Inventory indicates the quantity for a given product.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def stock(self):
        """
        :return: int
        """
        return self.obj['stock']

class Line(BaseObject):
    """
    Lines (also called order lines, sale lines or line items) describe the
    products included in an order.
    """

    @property
    def number(self):
        """
        The line number. This will start with `1`.
        :return: int
        """
        return self.obj['number']

    @property
    def product_id(self):
        """
        :return: int
        """
        return self.obj['product_id']

    @property
    def quantity(self):
        """
        :return: int
        """
        return self.obj['quantity']

    @property
    def notes(self):
        """
        :return: str
        """
        return self.obj['notes']

    @property
    def unit_price(self):
        """
        :return: float
        """
        return self.obj['unit_price']

    @property
    def price_variation(self):
        """
        :return: float
        """
        return self.obj['price_variation']

    @property
    def modifiers(self):
        """
        :return: int[]
        """
        return self.obj['modifiers']

class Order(BaseObject):
    """
    Orders are also sometimes called sales or invoices.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def status(self):
        """
        :return: str
        """
        return self.obj['status']

    @property
    def total(self):
        """
        :return: float
        """
        return self.obj['total']

    @property
    def total_tax(self):
        """
        :return: float
        """
        return self.obj['total_tax']

    @property
    def paid(self):
        """
        :return: float
        """
        return self.obj['paid']

    @property
    def created_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['created_at'])

    @property
    def updated_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['updated_at'])

class PaymentMethod(BaseObject):
    """
    Payment methods are assigned to order payments.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def name(self):
        """
        :return: str
        """
        return self.obj['name']

    @property
    def ledger_code(self):
        """
        :return: str
        """
        return self.obj['ledger_code']

class Payment(BaseObject):
    """
    Payments (also called transactions) are financial transactions related to an
    order.
    """

    @property
    def method_id(self):
        """
        :return: int
        """
        return self.obj['method_id']

    @property
    def amount(self):
        """
        :return: float
        """
        return self.obj['amount']

    @property
    def ref(self):
        """
        :return: str
        """
        return self.obj['ref']

class PriceList(BaseObject):
    """
    Each site will be assigned a price list that determines ex tax unit prices
    of each item on sale.

    Price lists work by overriding prices in their parent lists (just like
    subclassing in object-oriented programming). The base price list has a
    parent_id of null.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def name(self):
        """
        :return: str
        """
        return self.obj['name']

    @property
    def parent_id(self):
        """
        :return: int
        """
        return self.obj['parent_id']

class Register(BaseObject):
    """
    Registers are iPads or other computers running Kounta.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def code(self):
        """
        :return: str
        """
        return self.obj['code']

    @property
    def name(self):
        """
        :return: str
        """
        return self.obj['name']

    @property
    def site_id(self):
        """
        :return: int
        """
        return self.obj['site_id']

    def cashups(self, **kwargs):
        """
        Fetch cashups for a register. Refer to documentation for Cashups for
        more information.
        :rtype : Cashup[]
        """
        url = '/v1/companies/%d/registers/%d' % (self._company.id, self.id)
        return self._get_cashups(url, **kwargs)

class ShiftPeriod(BaseObject):
    """
    Represents a block of time when dealing with `Shift`s.
    """

    @property
    def started_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['started_at'])

    @property
    def finished_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['finished_at'])

    @property
    def period(self):
        """
        The timedelta between the start anf finish time.
        :return: timedelta
        """
        return self.started_at - self.finished_at

class Shift(ShiftPeriod):
    """
    Shifts record staff check-ins, check-outs and breaks.
    """

    @property
    def staff_member(self):
        """
        :return: Staff
        """
        return Staff(self.obj['staff_member'], self._client, self._company)

    @property
    def site(self):
        """
        :return: Site
        """
        return Site(self.obj['site'], self._client, self._company)

    @property
    def breaks(self):
        """
        :return: Shift[]
        """
        return [Shift(shift, self._client, self._company) for shift in
                self.obj['breaks']]

class Location(BaseObject):
    """
    A geographical location with a latitude and longitude.
    """

    @property
    def latitude(self):
        """
        :return: float
        """
        return self.obj['latitude']

    @property
    def longitude(self):
        """
        :return: float
        """
        return self.obj['longitude']

class Tax(BaseObject):
    """
    Each product can be assigned one or more tax, defined as a code, name, and
    rate.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def code(self):
        """
        :return: str
        """
        return self.obj['code']

    @property
    def name(self):
        """
        :return: str
        """
        return self.obj['name']

    @property
    def rate(self):
        """
        :return: float
        """
        return self.obj['rate']

class IncomeAccountAmount(BaseObject):
    """
    An amount for a given tax type.
    """

    @property
    def tax_id(self):
        """
        :return: int
        """
        return self.obj['tax_id']

    @property
    def net(self):
        """
        :return: float
        """
        return self.obj['net']

    @property
    def tax(self):
        """
        :return: float
        """
        return self.obj['tax']

class Takings(BaseObject):
    """
    Daily takings.
    """

    @property
    def recorded(self):
        """
        :return: float
        """
        return self.obj['recorded']

    @property
    def counted(self):
        """
        :return: float
        """
        return self.obj['counted']

class Adjustments(BaseObject):
    """
    Adjustments to a reconciliation.
    """

    @property
    def cash_in(self):
        """
        :return: float
        """
        return self.obj['cash_in']

    @property
    def cash_out(self):
        """
        :return: float
        """
        return self.obj['cash_out']

class IncomeAccount(BaseObject):
    """
    Income account.
    """

    @property
    def ledger_code(self):
        """
        :return: string
        """
        return self.obj['ledger_code']

    @property
    def amounts(self):
        """
        :return: IncomeAccountAmount[]
        """
        return [IncomeAccountAmount(amount, self._client, self._company)
                for amount in self.obj['amounts']]

class Reconciliation(BaseObject):
    """
    End-of-day reconciliation.
    """

    @property
    def payment_method(self):
        """
        :return: PaymentMethod
        """
        return PaymentMethod(self.obj['payment_method'], self._client,
                             self._company)

    @property
    def takings(self):
        """
        :return: Takings
        """
        return Takings(self.obj['takings'], self._client, self._company)

    @property
    def adjustments(self):
        """
        :return: Adjustments
        """
        return Adjustments(self.obj['adjustments'], self._client, self._company)

class Cashup(BaseObject):
    """
    Cash-ups are end-of-day cash reconcilliations.
    """

    @property
    def id(self):
        """
        :return: int
        """
        return self.obj['id']

    @property
    def number(self):
        """
        :return: int
        """
        return self.obj['number']

    @property
    def processed(self):
        """
        :return: boolean
        """
        return self.obj['processed']

    @property
    def register_level_reconciliation(self):
        """
        :return: boolean
        """
        return self.obj['register_level_reconciliation']

    @property
    def register(self):
        """
        :return: Register
        """
        return Register(self.obj['register'], self._client, self._company)

    @property
    def site(self):
        """
        :return: Site
        """
        return Site(self.obj['site'], self._client, self._company)

    @property
    def staff_member(self):
        """
        :return: Staff
        """
        return Staff(self.obj['staff_member'], self._client, self._company)

    @property
    def income_accounts(self):
        """
        :return: IncomeAccount[]
        """
        return [IncomeAccount(account, self._client, self._company) for account
                in self.obj['income_accounts']]

    @property
    def reconciliations(self):
        """
        :return: Reconciliation[]
        """
        return [Reconciliation(account, self._client, self._company) for account
                in self.obj['reconciliations']]

    @property
    def created_at(self):
        """
        :return: datetime
        """
        return parse(self.obj['created_at'])


text:
module Jekyll
  module Converters
    class Markdown
      class RDiscountParser
        def initialize(config)
          unless defined?(RDiscount)
            Jekyll::External.require_with_graceful_fail "rdiscount"
          end
          @config = config
          @rdiscount_extensions = @config["rdiscount"]["extensions"].map(&:to_sym)
        end

        def convert(content)
          rd = RDiscount.new(content, *@rdiscount_extensions)
          html = rd.to_html
          if @config["rdiscount"]["toc_token"]
            html = replace_generated_toc(rd, html, @config["rdiscount"]["toc_token"])
          end
          html
        end

        private
        def replace_generated_toc(rd_instance, html, toc_token)
          if rd_instance.generate_toc && html.include?(toc_token)
            utf8_toc = rd_instance.toc_content
            utf8_toc.force_encoding("utf-8") if utf8_toc.respond_to?(:force_encoding)
            html.gsub(toc_token, utf8_toc)
          else
            html
          end
        end
      end
    end
  end
end


text:
class TraceTree
  class Point
    class Threadend < Point

      def self.event_class_method
        [:thread_end, nil, nil]
      end

      def class_name
        ''
      end

      def method_name
        :thread_run
      end

      def call_symbol
        ''
      end
    end
  end
end


text:
//
//  Copyright (c) 2014 VK.com
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//  the Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

package com.vk.sdk.api.httpClient;

import android.util.Pair;
import android.webkit.MimeTypeMap;

import com.vk.sdk.api.model.VKAttachments;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import java.util.Random;

import static com.vk.sdk.api.model.VKAttachments.Type.DOC;

/**
 * Class used for build upload multipart data for VK servers
 */
public class VKMultipartEntity {

    private static final String VK_BOUNDARY = "Boundary(======VK_SDK_%d======)";

    private final String mBoundary;
    private final File[] mFiles;
    private String mType;

    public VKMultipartEntity(File[] files) {
        mBoundary = String.format(Locale.US, VK_BOUNDARY, new Random().nextInt());
        mFiles = files;
    }

    public VKMultipartEntity(File[] files, String type) {
        mBoundary = String.format(Locale.US, VK_BOUNDARY, new Random().nextInt());
        mFiles = files;
        mType = type;
    }

    public long getContentLength() {
        long length = 0;
        for (int i = 0; i < mFiles.length; i++) {
            File f = mFiles[i];
            length += f.length();
            length += getFileDescription(f, i).length();
        }
        length += getBoundaryEnd().length();
        return length;
    }

    public Pair<String, String> getContentType() {
        return new Pair<>("Content-Type", String.format("multipart/form-data; boundary=%s", mBoundary));
    }

    public InputStream getContent() throws IOException, IllegalStateException {
        throw new UnsupportedOperationException("Multipart form entity does not implement #getContent()");
    }

    protected String getFileDescription(File uploadFile, int i) {
        String fileName;
        if (mType != null && mType.equals(DOC.getTypeStr())) {
            fileName = "file";
        } else {
            fileName = String.format(Locale.US, "file%d", i + 1);
        }
        String extension = MimeTypeMap.getFileExtensionFromUrl(uploadFile.getAbsolutePath());
        return String.format("\r\n--%s\r\n", mBoundary) +
                String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s.%s\"\r\n", fileName, fileName, extension) +
                String.format("Content-Type: %s\r\n\r\n", getMimeType(uploadFile.getAbsolutePath()));
    }

    private String getBoundaryEnd() {
        return String.format("\r\n--%s--\r\n", mBoundary);
    }

    public void writeTo(OutputStream outputStream) throws IOException {
        for (int i = 0; i < mFiles.length; i++) {
            File uploadFile = mFiles[i];
            outputStream.write(getFileDescription(uploadFile, i).getBytes("UTF-8"));
            FileInputStream reader = new FileInputStream(uploadFile);
            byte[] fileBuffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = reader.read(fileBuffer)) != -1) {
                outputStream.write(fileBuffer, 0, bytesRead);
            }
            reader.close();
        }
        outputStream.write(getBoundaryEnd().getBytes("UTF-8"));
    }

    protected static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }
        return type;
    }
}


text: I am from Ngee Ann Polytechnic


text:
from rauth import OAuth1Service, OAuth2Service
from flask import current_app, url_for, request, redirect, session
import json

class OAuthSignIn(object):
    providers = None

    def __init__(self, provider_name):
        self.provider_name = provider_name
        credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
        self.consumer_id = credentials['id']
        self.consumer_secret = credentials['secret']

    def authorize(self):
        pass

    def callback(self):
        pass

    def get_callback_url(self):
        return url_for('oauth_callback', provider=self.provider_name,
                       _external=True)

    @classmethod
    def get_provider(self, provider_name):
        if self.providers is None:
            self.providers = {}
            for provider_class in self.__subclasses__():
                provider = provider_class()
                self.providers[provider.provider_name] = provider
        return self.providers[provider_name]

class StravaSignIn(OAuthSignIn):
    def __init__(self):
        super(StravaSignIn, self).__init__('strava')
        self.service = OAuth2Service(
            name='strava',
            client_id=self.consumer_id,
            client_secret=self.consumer_secret,
            authorize_url='https://www.strava.com/oauth/authorize',
            access_token_url='https://www.strava.com/oauth/token',
            base_url='https://www.strava.com/api/v3/',
        )

    def authorize(self):
        return redirect(self.service.get_authorize_url(
            scope='view_private',
            response_type='code',
            redirect_uri=self.get_callback_url())
        )

    def callback(self):
        if 'code' not in request.args:
            return None, None, None

        oauth_session = self.service.get_auth_session(
            data={'code': request.args['code'],
                  'grant_type': 'authorization_code',
                  'redirect_uri': self.get_callback_url()},
            # params={'format': 'json'},
            decoder=json.loads

        )
        access_token = oauth_session.access_token
        me = oauth_session.get('athlete?').json()

        athlete_id = me.get('id')
        email = me.get('email')
        return (athlete_id, email, access_token)


text:
from expproc.ExperienceProcessor import ExperienceProcessor

epProc = ExperienceProcessor()