text:
class VirtualPaths(object):
    def __init__(self, obj, mapping):
        self.obj = obj
        self.mapping = mapping

    def __getitem__(self, item):

        return getattr(self.obj, self.mapping[item])

class CompatibilityLayer(object):
    """
    Ensure backwards compatibility with older versions of Cactus.
    """
    mapping = {}

    @property
    def paths(self):
        return VirtualPaths(self, self.mapping)

class SiteCompatibilityLayer(CompatibilityLayer):
    mapping = {
        'build': 'build_path',
        'pages': 'page_path',
        'plugins': 'plugin_path',
        'templates': 'template_path',
        'static': 'static_path',
        'script': 'script_path',
    }

class PageCompatibilityLayer(CompatibilityLayer):
    mapping = {
        'full': 'full_source_path',
        'full-build': 'full_build_path',
    }

    @property
    def path(self):
        return self.source_path

class StaticCompatibilityLayer(CompatibilityLayer):
    mapping = {
        'full': 'full_source_path',
        'full-build': 'full_build_path',
    }


text:
const argv = require('yargs').argv
const babelify = require('babelify')
const browserify = require('gulp-browserify')
const gulp = require('gulp')
const gulpif = require('gulp-if')
const sass = require('gulp-sass')
const uglify = require('gulp-uglify')

const production = argv.production

const config = {
    sass: {
        input: ['resources/sass/site.scss'],
        output: 'css',
        watch: 'resources/sass/**/*',
        options: {
            includePaths: ['node_modules'],
            outputStyle: production ? 'compressed' : null
        }
    },
    js: {
        input: ['resources/js/site.js'],
        output: 'js',
        watch: 'resources/js/**/*'
    }
}

gulp.task('default', () => {
    gulp.start('sass', 'js')
})

gulp.task('watch', () => {
    gulp.start('default')
    gulp.watch(config.sass.watch, ['sass'])
    gulp.watch(config.js.watch, ['js'])
})

gulp.task('sass', () => {
    gulp.src(config.sass.input)
        .pipe(sass(config.sass.options).on('error', sass.logError))
        .pipe(gulp.dest(config.sass.output))
})

gulp.task('js', () => {
    gulp.src(config.js.input)
        .pipe(browserify({
            transform: babelify.configure({ presets: ['es2015'] })
        }))
        .pipe(gulpif(production, uglify()))
        .pipe(gulp.dest(config.js.output))
})

redpajama_set_name: RedPajamaGithub


text:
#ifndef WorkerAsyncFileSystemChromium_h
#define WorkerAsyncFileSystemChromium_h

#include "AsyncFileSystemChromium.h"
#include "modules/filesystem/FileSystemType.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"

namespace WebKit {
class WebFileSystem;
class WebURL;
class WorkerFileSystemCallbacksBridge;
}

namespace WebCore {

class AsyncFileSystemCallbacks;
class ScriptExecutionContext;
class WorkerGlobalScope;
class WorkerLoaderProxy;

class WorkerAsyncFileSystemChromium : public AsyncFileSystemChromium {
public:
    static PassOwnPtr<AsyncFileSystem> create(ScriptExecutionContext* context, FileSystemSynchronousType synchronousType)
    {
        return adoptPtr(new WorkerAsyncFileSystemChromium(context, synchronousType));
    }

    virtual ~WorkerAsyncFileSystemChromium();

    // Runs one pending operation (to wait for completion in the sync-mode).
    virtual bool waitForOperationToComplete();

    virtual void move(const KURL& sourcePath, const KURL& destinationPath, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void copy(const KURL& sourcePath, const KURL& destinationPath, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void remove(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void removeRecursively(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void readMetadata(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void createFile(const KURL& path, bool exclusive, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void createDirectory(const KURL& path, bool exclusive, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void fileExists(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void directoryExists(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void readDirectory(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void createWriter(AsyncFileWriterClient*, const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);
    virtual void createSnapshotFileAndReadMetadata(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>);

private:
    WorkerAsyncFileSystemChromium(ScriptExecutionContext*, FileSystemSynchronousType);

    PassRefPtr<WebKit::WorkerFileSystemCallbacksBridge> createWorkerFileSystemCallbacksBridge(PassOwnPtr<AsyncFileSystemCallbacks>);

    ScriptExecutionContext* m_scriptExecutionContext;
    WorkerLoaderProxy* m_workerLoaderProxy;
    WorkerGlobalScope* m_workerGlobalScope;
    RefPtr<WebKit::WorkerFileSystemCallbacksBridge> m_bridgeForCurrentOperation;
    String m_modeForCurrentOperation;
    FileSystemSynchronousType m_synchronousType;
};

} // namespace WebCore

#endif // WorkerAsyncFileSystemChromium_h


text:
module Naf
  #
  # Things you should know about jobs
  # new jobs older than 1.week will not be searched in the queue.  You should not run programs
  # for more than a 1.week (instead, have them exit and restarted periodically)
  #
  class HistoricalJob < ::Partitioned::ById
    class JobPrerequisiteLoop < StandardError
      def initialize(job)
        super("loop found in prerequisites for #{job}")
      end
    end

    include PgAdvisoryLocker

    # Protect from mass-assignment issue
    attr_accessible :application_id,
                    :application_schedule_id,
                    :application_type_id,
                    :command,
                    :application_run_group_restriction_id,
                    :application_run_group_name,
                    :application_run_group_limit,
                    :priority,
                    :started_on_machine_id,
                    :failed_to_start,
                    :pid,
                    :exit_status,
                    :termination_signal,
                    :state,
                    :request_to_terminate,
                    :marked_dead_by_machine_id,
                    :log_level,
                    :machine_runner_invocation_id

    JOB_STALE_TIME = 1.week
    SYSTEM_TAGS = {
      startup: '$startup',
      pre_work: '$pre-work',
      work: '$work',
      cleanup: '$cleanup'
    }

    #---------------------
    # *** Associations ***
    #+++++++++++++++++++++

    belongs_to :application_schedule,
      class_name: '::Naf::ApplicationSchedule'
    belongs_to :application_type,
      class_name: '::Naf::ApplicationType'
    belongs_to :started_on_machine,
      class_name: '::Naf::Machine',
      foreign_key: 'started_on_machine_id'
    belongs_to :marked_dead_by_machine,
      class_name: '::Naf::Machine',
      foreign_key: 'marked_dead_by_machine_id'
    belongs_to :application,
      class_name: "::Naf::Application"
    belongs_to :application_run_group_restriction,
      class_name: "::Naf::ApplicationRunGroupRestriction"
    belongs_to :machine_runner_invocation,
      class_name: "::Naf::MachineRunnerInvocation"
    has_one :running_job,
      class_name: "::Naf::RunningJob",
      foreign_key: :id
    has_one :queued_job,
      class_name: "::Naf::QueuedJob",
      foreign_key: :id
    # Must access instance methods job_prerequisites through helper methods so we can use partitioning sql
    has_many :historical_job_prerequisites,
      class_name: "::Naf::HistoricalJobPrerequisite",
      dependent: :destroy
    has_many :prerequisites,
      class_name: "::Naf::HistoricalJob",
      through: :historical_job_prerequisites,
      source: :prerequisite_historical_job
    # Access supported through instance methods
    has_many :historical_job_affinity_tabs,
      class_name: "::Naf::HistoricalJobAffinityTab",
      dependent: :destroy
    has_many :affinities,
      class_name: "::Naf::Affinity",
      through: :historical_job_affinity_tabs

    #--------------------
    # *** Validations ***
    #++++++++++++++++++++

    validates :application_type_id,
              :command,
              :application_run_group_restriction_id, presence: true

    validates :command, length: {
                          minimum: 3
                        }
    validates :application_run_group_limit, numericality: {
                                              only_integer: true,
                                              greater_than_or_equal_to: 1,
                                              less_than: 2147483647,
                                              allow_blank: true
                                            }

    #--------------------
    # *** Delegations ***
    #++++++++++++++++++++

    delegate :application_run_group_restriction_name, to: :application_run_group_restriction
    delegate :script_type_name, to: :application_type
    delegate :affinity_name,
             :affinity_classification_name,
             :affinity_short_name, to: :affinity

    #------------------
    # *** Partition ***
    #++++++++++++++++++

    partitioned do |partition|
      partition.foreign_key :application_id, ::Naf::Application.table_name
      partition.foreign_key :application_type_id, ::Naf::ApplicationType.table_name
      partition.foreign_key :application_run_group_restriction_id, ::Naf::ApplicationRunGroupRestriction.table_name
      partition.foreign_key :started_on_machine_id, ::Naf::Machine.table_name
      partition.index :created_at
      partition.index :application_id
      partition.index :started_on_machine_id
      partition.index :command
      partition.index :application_run_group_name
      partition.index :finished_at
      partition.index :exit_status

      partition.janitorial_creates_needed lambda { |model, *partition_key_values|
        sequence_name = model.connection.default_sequence_name(model.table_name)
        current_id = model.find_by_sql("select last_value as id from #{sequence_name}").first.id
        start_range = [0, current_id - (model.partition_table_size * model.partition_num_lead_buffers)].max
        end_range = current_id + (model.partition_table_size * model.partition_num_lead_buffers)
        return model.partition_generate_range(start_range, end_range).reject{|p| model.sql_adapter.partition_exists?(p)}
      }
      partition.janitorial_archives_needed []
      partition.janitorial_drops_needed lambda { |model, *partition_key_values|
        sequence_name = model.connection.default_sequence_name(model.table_name)
        current_id = model.find_by_sql("select last_value as id from #{sequence_name}").first.id
        partition_key_value = current_id - (model.partition_table_size * model.partition_num_lead_buffers)
        partition_key_values_to_drop = []
        while model.sql_adapter.partition_exists?(partition_key_value)
          partition_key_values_to_drop << partition_key_value
          partition_key_value -= model.partition_table_size
        end
        return partition_key_values_to_drop
      }
    end

    #----------------------
    # *** Class Methods ***
    #++++++++++++++++++++++

    def self.connection
      ::Naf::NafBase.connection
    end

    def self.full_table_name_prefix
      ::Naf::NafBase.full_table_name_prefix
    end

    def self.partition_table_size
      100000
    end

    def self.partition_num_lead_buffers
      10
    end

    def self.queued_between(start_time, end_time)
      where(["created_at >= ? AND created_at <= ?", start_time, end_time])
    end

    def self.canceled
      where(request_to_terminate: true)
    end

    def self.application_last_runs
      where("application_schedule_id IS NOT NULL").
        group("application_schedule_id").
        select("application_schedule_id, MAX(finished_at) AS finished_at").
        reject{ |job| job.finished_at.nil? }
    end

    def self.application_last_queued
      where("application_id IS NOT NULL").
        group("application_id").
        select("application_id, MAX(id) AS id, MAX(created_at) AS created_at")
    end

    def self.finished
      where("finished_at IS NOT NULL OR request_to_terminate = true")
    end

    def self.queued_status
      where("(started_at IS NULL AND request_to_terminate = false) OR
             (finished_at > '#{Time.zone.now - 1.minute}') OR
             (started_at IS NOT NULL AND finished_at IS NULL AND request_to_terminate = false)")
    end

    def self.running_status
      where("(started_at IS NOT NULL AND finished_at IS NULL AND request_to_terminate = false) OR
             (finished_at > '#{Time.zone.now - 1.minute}')")
    end

    def self.queued_with_waiting
      where("(started_at IS NULL AND request_to_terminate = false)")
    end

    def self.errored
      where("finished_at IS NOT NULL AND exit_status > 0 OR request_to_terminate = true")
    end

    def self.lock_for_job_queue(&block)
      lock_record(0, &block)
    end

    #-------------------------
    # *** Instance Methods ***
    #+++++++++++++++++++++++++

    def to_s
      components = []

      if started_at.nil?
        components << "QUEUED"
      else
        if finished_at.nil?
          if pid
            extras = []
            extras << pid.to_s
            extras << 'RequestedToTerminate' if request_to_terminate
            components << "RUNNING:#{extras.join(':')}"
          else
            components << "SPAWNING"
          end
        else
          extras = []
          extras << 'RequestedToTerminate' if request_to_terminate
          extras << "FailedToStart" if failed_to_start
          extras << "SIG#{termination_signal}" if termination_signal
          if exit_status && exit_status != 0
            extras << "STATUS=#{exit_status}"
          end
          if extras.length
            extras_str = " (#{extras.join(',')})"
          else
            extras_str = ""
          end
          components << "FINISHED#{extras_str}"
        end
      end
      components << "id: #{id}"
      components << "\"#{command}\""

      return "::Naf::HistoricalJob<#{components.join(', ')}>"
    end

    def title
      application.try(:title)
    end

    def machine_started_on_server_name
      started_on_machine.try(:server_name)
    end

    def machine_started_on_server_address
      started_on_machine.try(:server_address)
    end

    def historical_job_affinity_tabs
      ::Naf::HistoricalJobAffinityTab.
        from_partition(id).
        where(historical_job_id: id)
    end

    def job_affinities
      historical_job_affinity_tabs.map{ |jat| jat.affinity }
    end

    def affinity_ids
      historical_job_affinity_tabs.map{ |jat| jat.affinity_id }
    end

    def historical_job_prerequisites
      ::Naf::HistoricalJobPrerequisite.
        from_partition(id).
        where(historical_job_id: id)
    end

    def prerequisites
      historical_job_prerequisites.
        map{ |hjp| ::Naf::HistoricalJob.from_partition(hjp.prerequisite_historical_job_id).
        find_by_id(hjp.prerequisite_historical_job_id) }.
        reject{ |j| j.nil? }
    end

    # XXX This should go away (it was moved to ConstructionZone::Foreman)

    def verify_prerequisites(these_jobs)
      these_jobs.each do |this_job|
        if this_job.id == id
          raise JobPrerequisiteLoop.new(self)
        else
          verify_prerequisites(this_job.prerequisites)
        end
      end
    end

    def spawn
      application_type.spawn(self)
    end

    def lock_for_runner_use(&block)
      advisory_lock(&block)
    end

    def unlock_for_runner_use
      advisory_unlock
    end

  end
end


text:
import {primaryHost, cdnHost, apiHost, org as defaultOrg, token} from '../constants/github'

/**
 * Get a URL to the file on github.
 */
export const getBlobUrl = (repo, path, tag = 'master', org = defaultOrg) =>
  `https://${primaryHost}/${org}/${repo}/blob/${tag}${path}`

const checkResponse = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return response
  }
  const error = new Error(response.statusText)
  error.response = response
  error.status = response.status
  throw error
}

const getText = (response) => response.text()

const getJson = (response) => response.json()

/**
 * Load tags list.
 */
export const loadTags = (repo, org = defaultOrg) =>
  fetch(`https://${apiHost}/repos/${org}/${repo}/tags?per_page=200`)
    .then(checkResponse)
    .then(getJson)
    .then((tags) => tags.map((tag) => tag.name))

/**
 * Load raw file from the CDN.
 */
export const loadRawFile = (repo, path, tag = 'master', org = defaultOrg) =>
  fetch(`https://${cdnHost}/${org}/${repo}/${tag}${path}`).then(checkResponse).then(getText)

/**
 * Load stars counter.
 */
export const loadStars = (repo) =>
  fetch(`https://${apiHost}/repos/${repo}`)
    .then(checkResponse)
    .then(getJson)
    .then((data) => data.stargazers_count)

/**
 * Parses a github file path and returns meta data.
 */
export const pathToMeta = (path) => {
  const parts = path.split('/')

  return {
    org: parts[1],
    repo: parts[2],
    view: parts[3] || '', // blob, edit, tree
    branch: parts[4] || '', // branch, tag, commit
    path: `/${parts.slice(5).join('/')}`
  }
}

/**
 * Returns `true` if github would show a readme page from a given path.
 */
export const isReadme = (path) => !path || path === '/' || /readme\.md$/i.test(path)


text:
package com.eixox.globalization;

import java.util.Locale;

public class PtBr extends Culture {

	public PtBr() {
		super(new Locale("pt", "BR"));
	}

	@Override
	public final String getLongDateFormat() {
		return "dd 'de' MMMM 'de' yyyy";
	}

	@Override
	public final String getShortDateFormat() {
		return "dd/MM/yyyy";
	}

	@Override
	public final String getDateTimeFormat() {
		return "dd/MM/yyyy HH:mm:ss";
	}

	@Override
	public String getTimeFormat() {
		return "HH:mm:ss";
	}

	@Override
	public final char getDateSeparator() {
		return '/';
	}

	@Override
	public final char getTimeSeparator() {
		return ':';
	}

}


text:
namespace stockcs.HelperForms
{
    partial class CandlestickForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea2 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend2 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();
            this.chCandleStick = new System.Windows.Forms.DataVisualization.Charting.Chart();
            this.btnClose = new System.Windows.Forms.Button();
            this.btnSaveImage = new System.Windows.Forms.Button();
            this.chBarChart = new System.Windows.Forms.DataVisualization.Charting.Chart();
            this.gbInformationPanel = new System.Windows.Forms.GroupBox();
            this.lblTicker = new System.Windows.Forms.Label();
            this.lblPeriod = new System.Windows.Forms.Label();
            this.lblStartDate = new System.Windows.Forms.Label();
            this.lblEndDate = new System.Windows.Forms.Label();
            this.txtTicker = new System.Windows.Forms.TextBox();
            this.txtPeriod = new System.Windows.Forms.TextBox();
            this.txtStartDate = new System.Windows.Forms.TextBox();
            this.txtEndDate = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.chCandleStick)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.chBarChart)).BeginInit();
            this.gbInformationPanel.SuspendLayout();
            this.SuspendLayout();
            //
            // chCandleStick
            //
            chartArea1.Name = "ChartArea1";
            this.chCandleStick.ChartAreas.Add(chartArea1);
            legend1.Name = "Legend1";
            this.chCandleStick.Legends.Add(legend1);
            this.chCandleStick.Location = new System.Drawing.Point(12, 12);
            this.chCandleStick.Name = "chCandleStick";
            series1.ChartArea = "ChartArea1";
            series1.Legend = "Legend1";
            series1.Name = "Series1";
            this.chCandleStick.Series.Add(series1);
            this.chCandleStick.Size = new System.Drawing.Size(1057, 525);
            this.chCandleStick.TabIndex = 0;
            this.chCandleStick.Text = "chCandleStick";
            //
            // btnClose
            //
            this.btnClose.Location = new System.Drawing.Point(1094, 66);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(102, 35);
            this.btnClose.TabIndex = 1;
            this.btnClose.Text = "Close";
            this.btnClose.UseVisualStyleBackColor = true;
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            //
            // btnSaveImage
            //
            this.btnSaveImage.Location = new System.Drawing.Point(1094, 12);
            this.btnSaveImage.Name = "btnSaveImage";
            this.btnSaveImage.Size = new System.Drawing.Size(102, 38);
            this.btnSaveImage.TabIndex = 2;
            this.btnSaveImage.Text = "Save Image";
            this.btnSaveImage.UseVisualStyleBackColor = true;
            this.btnSaveImage.Click += new System.EventHandler(this.btnSaveImage_Click);
            //
            // chBarChart
            //
            chartArea2.Name = "ChartArea1";
            this.chBarChart.ChartAreas.Add(chartArea2);
            legend2.Name = "Legend1";
            this.chBarChart.Legends.Add(legend2);
            this.chBarChart.Location = new System.Drawing.Point(12, 543);
            this.chBarChart.Name = "chBarChart";
            series2.ChartArea = "ChartArea1";
            series2.Legend = "Legend1";
            series2.Name = "Series1";
            this.chBarChart.Series.Add(series2);
            this.chBarChart.Size = new System.Drawing.Size(1057, 278);
            this.chBarChart.TabIndex = 3;
            this.chBarChart.Text = "chBarChart";
            //
            // gbInformationPanel
            //
            this.gbInformationPanel.Controls.Add(this.txtEndDate);
            this.gbInformationPanel.Controls.Add(this.txtStartDate);
            this.gbInformationPanel.Controls.Add(this.txtPeriod);
            this.gbInformationPanel.Controls.Add(this.txtTicker);
            this.gbInformationPanel.Controls.Add(this.lblEndDate);
            this.gbInformationPanel.Controls.Add(this.lblStartDate);
            this.gbInformationPanel.Controls.Add(this.lblPeriod);
            this.gbInformationPanel.Controls.Add(this.lblTicker);
            this.gbInformationPanel.Location = new System.Drawing.Point(1075, 125);
            this.gbInformationPanel.Name = "gbInformationPanel";
            this.gbInformationPanel.Size = new System.Drawing.Size(139, 229);
            this.gbInformationPanel.TabIndex = 4;
            this.gbInformationPanel.TabStop = false;
            this.gbInformationPanel.Text = "Information Panel:";
            //
            // lblTicker
            //
            this.lblTicker.AutoSize = true;
            this.lblTicker.Location = new System.Drawing.Point(7, 22);
            this.lblTicker.Name = "lblTicker";
            this.lblTicker.Size = new System.Drawing.Size(51, 17);
            this.lblTicker.TabIndex = 0;
            this.lblTicker.Text = "Ticker:";
            //
            // lblPeriod
            //
            this.lblPeriod.AutoSize = true;
            this.lblPeriod.Location = new System.Drawing.Point(10, 73);
            this.lblPeriod.Name = "lblPeriod";
            this.lblPeriod.Size = new System.Drawing.Size(53, 17);
            this.lblPeriod.TabIndex = 1;
            this.lblPeriod.Text = "Period:";
            //
            // lblStartDate
            //
            this.lblStartDate.AutoSize = true;
            this.lblStartDate.Location = new System.Drawing.Point(10, 124);
            this.lblStartDate.Name = "lblStartDate";
            this.lblStartDate.Size = new System.Drawing.Size(76, 17);
            this.lblStartDate.TabIndex = 2;
            this.lblStartDate.Text = "Start Date:";
            //
            // lblEndDate
            //
            this.lblEndDate.AutoSize = true;
            this.lblEndDate.Location = new System.Drawing.Point(10, 174);
            this.lblEndDate.Name = "lblEndDate";
            this.lblEndDate.Size = new System.Drawing.Size(71, 17);
            this.lblEndDate.TabIndex = 3;
            this.lblEndDate.Text = "End Date:";
            //
            // txtTicker
            //
            this.txtTicker.Enabled = false;
            this.txtTicker.Location = new System.Drawing.Point(13, 42);
            this.txtTicker.Name = "txtTicker";
            this.txtTicker.Size = new System.Drawing.Size(108, 22);
            this.txtTicker.TabIndex = 4;
            //
            // txtPeriod
            //
            this.txtPeriod.Enabled = false;
            this.txtPeriod.Location = new System.Drawing.Point(13, 93);
            this.txtPeriod.Name = "txtPeriod";
            this.txtPeriod.Size = new System.Drawing.Size(108, 22);
            this.txtPeriod.TabIndex = 5;
            //
            // txtStartDate
            //
            this.txtStartDate.Enabled = false;
            this.txtStartDate.Location = new System.Drawing.Point(13, 144);
            this.txtStartDate.Name = "txtStartDate";
            this.txtStartDate.Size = new System.Drawing.Size(108, 22);
            this.txtStartDate.TabIndex = 6;
            //
            // txtEndDate
            //
            this.txtEndDate.Enabled = false;
            this.txtEndDate.Location = new System.Drawing.Point(13, 194);
            this.txtEndDate.Name = "txtEndDate";
            this.txtEndDate.Size = new System.Drawing.Size(108, 22);
            this.txtEndDate.TabIndex = 7;
            //
            // CandlestickForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1226, 833);
            this.Controls.Add(this.gbInformationPanel);
            this.Controls.Add(this.chBarChart);
            this.Controls.Add(this.btnSaveImage);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.chCandleStick);
            this.Name = "CandlestickForm";
            this.Text = "stockcs";
            ((System.ComponentModel.ISupportInitialize)(this.chCandleStick)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.chBarChart)).EndInit();
            this.gbInformationPanel.ResumeLayout(false);
            this.gbInformationPanel.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataVisualization.Charting.Chart chCandleStick;
        private System.Windows.Forms.Button btnClose;
        private System.Windows.Forms.Button btnSaveImage;
        private System.Windows.Forms.DataVisualization.Charting.Chart chBarChart;
        private System.Windows.Forms.GroupBox gbInformationPanel;
        private System.Windows.Forms.TextBox txtEndDate;
        private System.Windows.Forms.TextBox txtStartDate;
        private System.Windows.Forms.TextBox txtPeriod;
        private System.Windows.Forms.TextBox txtTicker;
        private System.Windows.Forms.Label lblEndDate;
        private System.Windows.Forms.Label lblStartDate;
        private System.Windows.Forms.Label lblPeriod;
        private System.Windows.Forms.Label lblTicker;
    }
}


text:
npm-profile(1)

Change settings on your registry profile

Synopsis

npm profile get [--json|--parseable] [<property>]
npm profile set [--json|--parseable] <property> <value>
npm profile set password
npm profile enable-2fa [auth-and-writes|auth-only]
npm profile disable-2fa

Description

Change your profile information on the registry.  This not be available if
you're using a non-npmjs registry.

npm profile get [<property>]:
Display all of the properties of your profile, or one or more specific
properties.  It looks like:

+-----------------+---------------------------+
| name            | example                   |
+-----------------+---------------------------+
| email           | me@example.com (verified) |
+-----------------+---------------------------+
| two factor auth | auth-and-writes           |
+-----------------+---------------------------+
| fullname        | Example User              |
+-----------------+---------------------------+
| homepage        |                           |
+-----------------+---------------------------+
| freenode        |                           |
+-----------------+---------------------------+
| twitter         |                           |
+-----------------+---------------------------+
| github          |                           |
+-----------------+---------------------------+
| created         | 2015-02-26T01:38:35.892Z  |
+-----------------+---------------------------+
| updated         | 2017-10-02T21:29:45.922Z  |
+-----------------+---------------------------+

npm profile set <property> <value>:
Set the value of a profile property. You can set the following properties this way:
  email, fullname, homepage, freenode, twitter, github

npm profile set password:
Change your password.  This is interactive, you'll be prompted for your
current password and a new password.  You'll also be prompted for an OTP
if you have two-factor authentication enabled.

npm profile enable-2fa [auth-and-writes|auth-only]:
Enables two-factor authentication. Defaults to auth-and-writes mode. Modes are:

auth-only: Require an OTP when logging in or making changes to your
account's authentication.  The OTP will be required on both the website
and the command line.

auth-and-writes: Requires an OTP at all the times auth-only does, and also requires one when
publishing a module, setting the latest dist-tag, or changing access
via npm access and npm owner.

npm profile disable-2fa:
Disables two-factor authentication.

Details

All of the npm profile subcommands accept --json and --parseable and
will tailor their output based on those.  Some of these commands may not be
available on non npmjs.com registries.

See Also

npm config


text:
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.appusagestatistics;

import android.test.ActivityInstrumentationTestCase2;

/**
 * Tests for {@link AppUsageStatisticsActivity}.
 */
public class AppUsageStatisticsActivityTests
        extends ActivityInstrumentationTestCase2<AppUsageStatisticsActivity> {

    private AppUsageStatisticsActivity mTestActivity;
    private AppUsageStatisticsFragment mTestFragment;

    public AppUsageStatisticsActivityTests() {
        super(AppUsageStatisticsActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        // Starts the activity under test using the default Intent with:
        // action = {@link Intent#ACTION_MAIN}
        // flags = {@link Intent#FLAG_ACTIVITY_NEW_TASK}
        // All other fields are null or empty.
        mTestActivity = getActivity();
        mTestFragment = (AppUsageStatisticsFragment)
                mTestActivity.getSupportFragmentManager().getFragments().get(0);
    }

    /**
     * Test if the test fixture has been set up correctly.
     */
    public void testPreconditions() {
        //Try to add a message to add context to your assertions. These messages will be shown if
        //a tests fails and make it easy to understand why a test failed
        assertNotNull("mTestActivity is null", mTestActivity);
        assertNotNull("mTestFragment is null", mTestFragment);
    }
}


text:
ghosttheme
==========

Ghost theme used on my blog.


text:
#include <signal.h>
#include <errno.h>
#include <stdio.h>

int kill(pid_t pid __attribute__((unused)),
    int sig __attribute__((unused)))
{
  printf("kill\n");
  errno = EPERM;
  return -1;
}


text:
package org.keycloak.testsuite.oauth;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ClientTemplateResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.common.enums.SslRequired;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.protocol.oidc.mappers.HardcodedClaim;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ClientTemplateRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.AbstractKeycloakTest;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.ClientManager;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.RealmManager;
import org.keycloak.testsuite.util.RoleBuilder;
import org.keycloak.testsuite.util.UserBuilder;
import org.keycloak.testsuite.util.UserManager;
import org.keycloak.util.BasicAuthHelper;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
import static org.keycloak.testsuite.admin.ApiUtil.findClientByClientId;
import static org.keycloak.testsuite.admin.ApiUtil.findClientResourceByClientId;
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsernameId;
import static org.keycloak.testsuite.util.OAuthClient.AUTH_SERVER_ROOT;
import static org.keycloak.testsuite.util.ProtocolMapperUtil.createAddressMapper;
import static org.keycloak.testsuite.util.ProtocolMapperUtil.createClaimMapper;
import static org.keycloak.testsuite.util.ProtocolMapperUtil.createHardcodedClaim;
import static org.keycloak.testsuite.util.ProtocolMapperUtil.createHardcodedRole;
import static org.keycloak.testsuite.util.ProtocolMapperUtil.createRoleNameMapper;

/**
 * @author Stian Thorgersen
 */
public class AccessTokenTest extends AbstractKeycloakTest {

    @Rule
    public AssertEvents events = new AssertEvents(this);

    @Override
    public void beforeAbstractKeycloakTest() throws Exception {
        super.beforeAbstractKeycloakTest();
    }

    @Before
    public void clientConfiguration() {
        ClientManager.realm(adminClient.realm("test")).clientId("test-app").directAccessGrant(true);
        /*
         * Configure the default client ID. Seems like OAuthClient is keeping the state of clientID
         * For example: If some test case configure oauth.clientId("sample-public-client"), other tests
         * will faile and the clientID will always be "sample-public-client
         * @see AccessTokenTest#testAuthorizationNegotiateHeaderIgnored()
         */
        oauth.clientId("test-app");
    }

    @Override
    public void addTestRealms(List<RealmRepresentation> testRealms) {

        RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);

        UserBuilder user = UserBuilder.create()
                .id(KeycloakModelUtils.generateId())
                .username("no-permissions")
                .addRoles("user")
                .password("password");
        realm.getUsers().add(user.build());

        testRealms.add(realm);

    }

    @Test
    public void accessTokenRequest() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

        assertEquals(200, response.getStatusCode());

        Assert.assertThat(response.getExpiresIn(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
        Assert.assertThat(response.getRefreshExpiresIn(), allOf(greaterThanOrEqualTo(1750), lessThanOrEqualTo(1800)));

        assertEquals("bearer", response.getTokenType());

        AccessToken token = oauth.verifyToken(response.getAccessToken());

        assertEquals(findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId(), token.getSubject());
        Assert.assertNotEquals("test-user@localhost", token.getSubject());

        assertEquals(sessionId, token.getSessionState());

        assertEquals(1, token.getRealmAccess().getRoles().size());
        assertTrue(token.getRealmAccess().isUserInRole("user"));

        assertEquals(1, token.getResourceAccess(oauth.getClientId()).getRoles().size());
        assertTrue(token.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user"));

        EventRepresentation event = events.expectCodeToToken(codeId, sessionId).assertEvent();
        assertEquals(token.getId(), event.getDetails().get(Details.TOKEN_ID));
        assertEquals(oauth.verifyRefreshToken(response.getRefreshToken()).getId(), event.getDetails().get(Details.REFRESH_TOKEN_ID));
        assertEquals(sessionId, token.getSessionState());

    }

    @Test
    public void accessTokenInvalidClientCredentials() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "invalid");
        assertEquals(400, response.getStatusCode());

        AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_client_credentials").clearDetails().user((String) null).session((String) null);
        expectedEvent.assertEvent();
    }

    @Test
    public void accessTokenMissingClientCredentials() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
        assertEquals(400, response.getStatusCode());

        AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_client_credentials").clearDetails().user((String) null).session((String) null);
        expectedEvent.assertEvent();
    }

    @Test
    public void accessTokenInvalidRedirectUri() throws Exception {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        //@TODO This new and was necesssary to not mess up with other tests cases
        String redirectUri = oauth.getRedirectUri();

        oauth.redirectUri("http://invalid");

        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
        assertEquals(400, response.getStatusCode());
        assertEquals("invalid_grant", response.getError());
        assertEquals("Incorrect redirect_uri", response.getErrorDescription());

        events.expectCodeToToken(codeId, loginEvent.getSessionId()).error("invalid_code")
                .removeDetail(Details.TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_TYPE)
                .assertEvent();

        //@TODO Reset back to the original URI. Maybe we should have something to reset to the original state at OAuthClient
        oauth.redirectUri(redirectUri);

    }

    @Test
    public void accessTokenUserSessionExpired() {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String sessionId = loginEvent.getSessionId();

        testingClient.testing().removeUserSession("test", sessionId);
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
        assertEquals(400, tokenResponse.getStatusCode());
        assertNull(tokenResponse.getAccessToken());
        assertNull(tokenResponse.getRefreshToken());

        events.expectCodeToToken(codeId, sessionId)
                .removeDetail(Details.TOKEN_ID)
                .user((String) null)
                .session((String) null)
                .removeDetail(Details.REFRESH_TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_TYPE)
                .error(Errors.INVALID_CODE).assertEvent();

        events.clear();
    }

    @Test
    public void accessTokenCodeExpired() {
        RealmManager.realm(adminClient.realm("test")).accessCodeLifeSpan(1);
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        loginEvent.getSessionId();

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        setTimeOffset(2);

        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
        Assert.assertEquals(400, response.getStatusCode());

        setTimeOffset(0);

        AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, null);
        expectedEvent.error("invalid_code")
                .removeDetail(Details.TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_TYPE)
                .user((String) null);
        expectedEvent.assertEvent();

        events.clear();

        RealmManager.realm(adminClient.realm("test")).accessCodeLifeSpan(60);
    }

    @Test
    public void accessTokenCodeUsed() {
        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        loginEvent.getSessionId();

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
        Assert.assertEquals(200, response.getStatusCode());

        events.clear();

        response = oauth.doAccessTokenRequest(code, "password");
        Assert.assertEquals(400, response.getStatusCode());

        AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, null);
        expectedEvent.error("invalid_code")
                .removeDetail(Details.TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_ID)
                .removeDetail(Details.REFRESH_TOKEN_TYPE)
                .user((String) null);
        expectedEvent.assertEvent();

        events.clear();

        RealmManager.realm(adminClient.realm("test")).accessCodeLifeSpan(60);
    }

    @Test
    public void accessTokenCodeRoleMissing() {
        RealmResource realmResource = adminClient.realm("test");
        RoleRepresentation role = RoleBuilder.create().name("tmp-role").build();
        realmResource.roles().create(role);
        UserResource user = findUserByUsernameId(realmResource, "test-user@localhost");
        UserManager.realm(realmResource).user(user).assignRoles(role.getName());

        oauth.doLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        realmResource.roles().deleteRole("tmp-role");

        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

        Assert.assertEquals(200, response.getStatusCode());

        AccessToken token = oauth.verifyToken(response.getAccessToken());
        Assert.assertEquals(1, token.getRealmAccess().getRoles().size());
        assertTrue(token.getRealmAccess().isUserInRole("user"));

        events.clear();
    }

    @Test
    public void accessTokenCodeHasRequiredAction() {

        UserResource user = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
        UserManager.realm(adminClient.realm("test")).user(user).addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE.toString());

        oauth.doLogin("test-user@localhost", "password");

        String code = driver.getPageSource().split("code=")[1].split("&")[0].split("\"")[0];

        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
        Assert.assertEquals(400, response.getStatusCode());

        EventRepresentation event = events.poll();
        assertNotNull(event.getDetails().get(Details.CODE_ID));

        UserManager.realm(adminClient.realm("test")).user(user).removeRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE.toString());
    }

    @Test
    public void testGrantAccessToken() throws Exception {
        Client client = javax.ws.rs.client.ClientBuilder.newClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);

        {   // test checkSsl
            {
                RealmResource realmsResource = adminClient.realm("test");
                RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
                realmRepresentation.setSslRequired(SslRequired.ALL.toString());
                realmsResource.update(realmRepresentation);
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(403, response.getStatus());
            response.close();

            {
                RealmResource realmsResource = realmsResouce().realm("test");
                RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
                realmRepresentation.setSslRequired(SslRequired.EXTERNAL.toString());
                realmsResource.update(realmRepresentation);
            }

        }

        {   // test null username
            String header = BasicAuthHelper.createHeader("test-app", "password");
            Form form = new Form();
            form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
            form.param("password", "password");
            Response response = grantTarget.request()
                    .header(HttpHeaders.AUTHORIZATION, header)
                    .post(Entity.form(form));
            assertEquals(401, response.getStatus());
            response.close();
        }

        {   // test no password
            String header = BasicAuthHelper.createHeader("test-app", "password");
            Form form = new Form();
            form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
            form.param("username", "test-user@localhost");
            Response response = grantTarget.request()
                    .header(HttpHeaders.AUTHORIZATION, header)
                    .post(Entity.form(form));
            assertEquals(401, response.getStatus());
            response.close();
        }

        {   // test invalid password
            String header = BasicAuthHelper.createHeader("test-app", "password");
            Form form = new Form();
            form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
            form.param("username", "test-user@localhost");
            form.param("password", "invalid");
            Response response = grantTarget.request()
                    .header(HttpHeaders.AUTHORIZATION, header)
                    .post(Entity.form(form));
            assertEquals(401, response.getStatus());
            response.close();
        }
        {   // test no password
            String header = BasicAuthHelper.createHeader("test-app", "password");
            Form form = new Form();
            form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
            form.param("username", "test-user@localhost");
            Response response = grantTarget.request()
                    .header(HttpHeaders.AUTHORIZATION, header)
                    .post(Entity.form(form));
            assertEquals(401, response.getStatus());
            response.close();
        }

        {   //test bearer-only

            {
                ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
                ClientRepresentation clientRepresentation = clientResource.toRepresentation();
                clientRepresentation.setBearerOnly(true);
                clientResource.update(clientRepresentation);
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(400, response.getStatus());
            response.close();

            {
                ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
                ClientRepresentation clientRepresentation = clientResource.toRepresentation();
                clientRepresentation.setBearerOnly(false);
                clientResource.update(clientRepresentation);
            }

        }

        {   // test realm disabled
            {
                RealmResource realmsResource = realmsResouce().realm("test");
                RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
                realmRepresentation.setEnabled(false);
                realmsResource.update(realmRepresentation);
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(403, response.getStatus());
            response.close();

            {
                RealmResource realmsResource = realmsResouce().realm("test");
                RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
                realmRepresentation.setEnabled(true);
                realmsResource.update(realmRepresentation);
            }

        }

        {   // test application disabled

            {
                ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
                ClientRepresentation clientRepresentation = clientResource.toRepresentation();
                clientRepresentation.setEnabled(false);
                clientResource.update(clientRepresentation);
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(400, response.getStatus());
            response.close();

            {
                ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
                ClientRepresentation clientRepresentation = clientResource.toRepresentation();
                clientRepresentation.setEnabled(true);
                clientResource.update(clientRepresentation);

            }

        }

        {   // test user action required

            {
                UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
                UserRepresentation userRepresentation = userResource.toRepresentation();
                userRepresentation.getRequiredActions().add(UserModel.RequiredAction.UPDATE_PASSWORD.toString());
                userResource.update(userRepresentation);
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(400, response.getStatus());
            response.close();

            {
                UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
                UserRepresentation userRepresentation = userResource.toRepresentation();
                userRepresentation.getRequiredActions().remove(UserModel.RequiredAction.UPDATE_PASSWORD.toString());
                userResource.update(userRepresentation);
            }

        }

        {   // test user disabled
            {
                UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
                UserRepresentation userRepresentation = userResource.toRepresentation();
                userRepresentation.setEnabled(false);
                userResource.update(userRepresentation);
            }

            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(400, response.getStatus());
            response.close();

            {
                UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
                UserRepresentation userRepresentation = userResource.toRepresentation();
                userRepresentation.setEnabled(true);
                userResource.update(userRepresentation);
            }

        }

        {
            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            response.close();
        }

        client.close();
        events.clear();
    }

    @Test
    public void testKeycloak2221() throws Exception {
        Client client = javax.ws.rs.client.ClientBuilder.newClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);

        ClientResource clientResource;

        {

            clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
            clientResource.getProtocolMappers().createMapper(createRoleNameMapper("rename-role", "user", "realm-user"));
            clientResource.getProtocolMappers().createMapper(createRoleNameMapper("rename-role2", "admin", "the-admin"));

        }

        {
            Response response = executeGrantRequest(grantTarget, "no-permissions", "password");
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            AccessToken accessToken = getAccessToken(tokenResponse);
            assertEquals(accessToken.getRealmAccess().getRoles().size(), 1);
            assertTrue(accessToken.getRealmAccess().getRoles().contains("realm-user"));

            response.close();
        }

        // undo mappers
        {
            ClientResource app = findClientByClientId(adminClient.realm("test"), "test-app");
            ClientRepresentation clientRepresentation = app.toRepresentation();
            for (ProtocolMapperRepresentation protocolRep : clientRepresentation.getProtocolMappers()) {
                if (protocolRep.getName().startsWith("rename-role")) {
                    clientResource.getProtocolMappers().delete(protocolRep.getId());
                }
            }
        }

        events.clear();

    }

    @Test
    public void testTokenMapping() throws Exception {
        Client client = javax.ws.rs.client.ClientBuilder.newClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        {
            UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
            UserRepresentation user = userResource.toRepresentation();

            user.singleAttribute("street", "5 Yawkey Way");
            user.singleAttribute("locality", "Boston");
            user.singleAttribute("region", "MA");
            user.singleAttribute("postal_code", "02115");
            user.singleAttribute("country", "USA");
            user.singleAttribute("phone", "617-777-6666");

            List<String> departments = Arrays.asList("finance", "development");
            user.getAttributes().put("departments", departments);
            userResource.update(user);

            ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app");

            ProtocolMapperRepresentation mapper = createAddressMapper(true, true);
            app.getProtocolMappers().createMapper(mapper);

            ProtocolMapperRepresentation hard = createHardcodedClaim("hard", "hard", "coded", "String", false, null, true, true);
            app.getProtocolMappers().createMapper(hard);
            app.getProtocolMappers().createMapper(createHardcodedClaim("hard-nested", "nested.hard", "coded-nested", "String", false, null, true, true));
            app.getProtocolMappers().createMapper(createClaimMapper("custom phone", "phone", "home_phone", "String", true, "", true, true, false));
            app.getProtocolMappers().createMapper(createClaimMapper("nested phone", "phone", "home.phone", "String", true, "", true, true, false));
            app.getProtocolMappers().createMapper(createClaimMapper("departments", "departments", "department", "String", true, "", true, true, true));
            app.getProtocolMappers().createMapper(createHardcodedRole("hard-realm", "hardcoded"));
            app.getProtocolMappers().createMapper(createHardcodedRole("hard-app", "app.hardcoded"));
            app.getProtocolMappers().createMapper(createRoleNameMapper("rename-app-role", "test-app.customer-user", "realm-user"));
        }

        {
            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());

            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            IDToken idToken = getIdToken(tokenResponse);
            assertNotNull(idToken.getAddress());
            assertEquals(idToken.getName(), "Tom Brady");
            assertEquals(idToken.getAddress().getStreetAddress(), "5 Yawkey Way");
            assertEquals(idToken.getAddress().getLocality(), "Boston");
            assertEquals(idToken.getAddress().getRegion(), "MA");
            assertEquals(idToken.getAddress().getPostalCode(), "02115");
            assertEquals(idToken.getAddress().getCountry(), "USA");
            assertNotNull(idToken.getOtherClaims().get("home_phone"));
            assertEquals("617-777-6666", idToken.getOtherClaims().get("home_phone"));
            assertEquals("coded", idToken.getOtherClaims().get("hard"));
            Map nested = (Map) idToken.getOtherClaims().get("nested");
            assertEquals("coded-nested", nested.get("hard"));
            nested = (Map) idToken.getOtherClaims().get("home");
            assertEquals("617-777-6666", nested.get("phone"));
            List<String> departments = (List<String>) idToken.getOtherClaims().get("department");
            assertEquals(2, departments.size());
            assertTrue(departments.contains("finance") && departments.contains("development"));

            AccessToken accessToken = getAccessToken(tokenResponse);
            assertEquals(accessToken.getName(), "Tom Brady");
            assertNotNull(accessToken.getAddress());
            assertEquals(accessToken.getAddress().getStreetAddress(), "5 Yawkey Way");
            assertEquals(accessToken.getAddress().getLocality(), "Boston");
            assertEquals(accessToken.getAddress().getRegion(), "MA");
            assertEquals(accessToken.getAddress().getPostalCode(), "02115");
            assertEquals(accessToken.getAddress().getCountry(), "USA");
            assertNotNull(accessToken.getOtherClaims().get("home_phone"));
            assertEquals("617-777-6666", accessToken.getOtherClaims().get("home_phone"));
            assertEquals("coded", accessToken.getOtherClaims().get("hard"));
            nested = (Map) accessToken.getOtherClaims().get("nested");
            assertEquals("coded-nested", nested.get("hard"));
            nested = (Map) accessToken.getOtherClaims().get("home");
            assertEquals("617-777-6666", nested.get("phone"));
            departments = (List<String>) idToken.getOtherClaims().get("department");
            assertEquals(2, departments.size());
            assertTrue(departments.contains("finance") && departments.contains("development"));
            assertTrue(accessToken.getRealmAccess().getRoles().contains("hardcoded"));
            assertTrue(accessToken.getRealmAccess().getRoles().contains("realm-user"));
            Assert.assertFalse(accessToken.getResourceAccess("test-app").getRoles().contains("customer-user"));
            assertTrue(accessToken.getResourceAccess("app").getRoles().contains("hardcoded"));

            response.close();
        }

        // undo mappers
        {
            ClientResource app = findClientByClientId(adminClient.realm("test"), "test-app");
            ClientRepresentation clientRepresentation = app.toRepresentation();
            for (ProtocolMapperRepresentation model : clientRepresentation.getProtocolMappers()) {
                if (model.getName().equals("address")
                        || model.getName().equals("hard")
                        || model.getName().equals("hard-nested")
                        || model.getName().equals("custom phone")
                        || model.getName().equals("departments")
                        || model.getName().equals("nested phone")
                        || model.getName().equals("rename-app-role")
                        || model.getName().equals("hard-realm")
                        || model.getName().equals("hard-app")
                        ) {
                    app.getProtocolMappers().delete(model.getId());
                }
            }
        }

        events.clear();

        {
            Response response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            IDToken idToken = getIdToken(tokenResponse);
            assertNull(idToken.getAddress());
            assertNull(idToken.getOtherClaims().get("home_phone"));
            assertNull(idToken.getOtherClaims().get("hard"));
            assertNull(idToken.getOtherClaims().get("nested"));
            assertNull(idToken.getOtherClaims().get("department"));

            response.close();
        }

        events.clear();
        client.close();

    }

    @Test
    public void testClientTemplate() throws Exception {
        RealmResource realm = adminClient.realm("test");
        RoleRepresentation realmRole = new RoleRepresentation();
        realmRole.setName("realm-test-role");
        realm.roles().create(realmRole);
        realmRole = realm.roles().get("realm-test-role").toRepresentation();
        RoleRepresentation realmRole2 = new RoleRepresentation();
        realmRole2.setName("realm-test-role2");
        realm.roles().create(realmRole2);
        realmRole2 = realm.roles().get("realm-test-role2").toRepresentation();

        List<UserRepresentation> users = realm.users().search("test-user@localhost", -1, -1);
        assertEquals(1, users.size());
        UserRepresentation user = users.get(0);

        List<RoleRepresentation> addRoles = new LinkedList<>();
        addRoles.add(realmRole);
        addRoles.add(realmRole2);
        realm.users().get(user.getId()).roles().realmLevel().add(addRoles);

        ClientTemplateRepresentation rep = new ClientTemplateRepresentation();
        rep.setName("template");
        rep.setProtocol("oidc");
        Response response = realm.clientTemplates().create(rep);
        assertEquals(201, response.getStatus());
        URI templateUri = response.getLocation();
        response.close();
        ClientTemplateResource templateResource = adminClient.proxy(ClientTemplateResource.class, templateUri);
        ProtocolMapperModel hard = HardcodedClaim.create("hard", "hard", "coded", "String", false, null, true, true);
        ProtocolMapperRepresentation mapper = ModelToRepresentation.toRepresentation(hard);
        response = templateResource.getProtocolMappers().createMapper(mapper);
        assertEquals(201, response.getStatus());
        response.close();
        List<ClientRepresentation> clients = realm.clients().findAll();
        ClientRepresentation clientRep = null;
        for (ClientRepresentation c : clients) {
            if (c.getClientId().equals("test-app")) {
                clientRep = c;
                break;
            }

        }
        clientRep.setClientTemplate("template");
        clientRep.setFullScopeAllowed(false);
        clientRep.setUseTemplateMappers(true);
        clientRep.setUseTemplateScope(true);
        clientRep.setUseTemplateConfig(true);
        realm.clients().get(clientRep.getId()).update(clientRep);

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            IDToken idToken = getIdToken(tokenResponse);
            assertEquals("coded", idToken.getOtherClaims().get("hard"));

            AccessToken accessToken = getAccessToken(tokenResponse);
            assertEquals("coded", accessToken.getOtherClaims().get("hard"));

            // check zero scope for template
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));

            response.close();
            client.close();
        }

        // test that scope is added
        List<RoleRepresentation> addRole1 = new LinkedList<>();
        addRole1.add(realmRole);
        templateResource.getScopeMappings().realmLevel().add(addRole1);

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            AccessToken accessToken = getAccessToken(tokenResponse);
            // check zero scope for template
            assertNotNull(accessToken.getRealmAccess());
            assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));

            response.close();
            client.close();
        }

        // test combined scopes
        List<RoleRepresentation> addRole2 = new LinkedList<>();
        addRole2.add(realmRole2);
        realm.clients().get(clientRep.getId()).getScopeMappings().realmLevel().add(addRole2);

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);

            AccessToken accessToken = getAccessToken(tokenResponse);

            // check zero scope for template
            assertNotNull(accessToken.getRealmAccess());
            assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
            assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));

            response.close();
            client.close();
        }

        // remove scopes and retest
        templateResource.getScopeMappings().realmLevel().remove(addRole1);
        realm.clients().get(clientRep.getId()).getScopeMappings().realmLevel().remove(addRole2);

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);

            AccessToken accessToken = getAccessToken(tokenResponse);
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));

            response.close();
            client.close();
        }

        // test full scope on template
        rep.setFullScopeAllowed(true);
        templateResource.update(rep);

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);

            AccessToken accessToken = getAccessToken(tokenResponse);

            // check zero scope for template
            assertNotNull(accessToken.getRealmAccess());
            assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
            assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));

            response.close();
            client.close();
        }

        // test don't use template scope
        clientRep.setUseTemplateScope(false);
        realm.clients().get(clientRep.getId()).update(clientRep);

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);

            AccessToken accessToken = getAccessToken(tokenResponse);
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
            Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));

            response.close();
            client.close();
        }

        // undo mappers
        clientRep.setClientTemplate(ClientTemplateRepresentation.NONE);
        clientRep.setFullScopeAllowed(true);
        realm.clients().get(clientRep.getId()).update(clientRep);
        realm.users().get(user.getId()).roles().realmLevel().remove(addRoles);
        realm.roles().get(realmRole.getName()).remove();
        realm.roles().get(realmRole2.getName()).remove();
        templateResource.remove();

        {
            Client client = javax.ws.rs.client.ClientBuilder.newClient();
            UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
            URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
            WebTarget grantTarget = client.target(grantUri);

            response = executeGrantAccessTokenRequest(grantTarget);
            assertEquals(200, response.getStatus());
            org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
            IDToken idToken = getIdToken(tokenResponse);
            assertNull(idToken.getOtherClaims().get("hard"));

            AccessToken accessToken = getAccessToken(tokenResponse);
            assertNull(accessToken.getOtherClaims().get("hard"));

            response.close();
            client.close();
        }
        events.clear();

    }

    // KEYCLOAK-1595 Assert that public client is able to retrieve token even if header "Authorization: Negotiate something" was used (parameter client_id has preference in this case)
    @Test
    public void testAuthorizationNegotiateHeaderIgnored() throws Exception {

        adminClient.realm("test").clients().create(ClientBuilder.create()
                .clientId("sample-public-client")
                .authenticatorType("client-secret")
                .redirectUris("http://localhost:8180/auth/realms/master/app/*")
                .publicClient()
                .build());

        oauth.clientId("sample-public-client");
        oauth.doLogin("test-user@localhost", "password");
        EventRepresentation loginEvent = events.expectLogin().client("sample-public-client").assertEvent();

        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);

        CloseableHttpClient client = new DefaultHttpClient();
        try {
            HttpPost post = new HttpPost(oauth.getAccessTokenUrl());

            List<NameValuePair> parameters = new LinkedList<NameValuePair>();
            parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
            parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
            parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
            parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, oauth.getClientId()));
            post.setHeader("Authorization", "Negotiate something-which-will-be-ignored");

            UrlEncodedFormEntity formEntity = null;
            formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            post.setEntity(formEntity);

            OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post));
            Assert.assertEquals(200, response.getStatusCode());
            AccessToken token = oauth.verifyToken(response.getAccessToken());
            events.expectCodeToToken(codeId, sessionId).client("sample-public-client").assertEvent();
        } finally {
            oauth.closeClient(client);
        }
    }

    private IDToken getIdToken(org.keycloak.representations.AccessTokenResponse tokenResponse) throws JWSInputException {
        JWSInput input = new JWSInput(tokenResponse.getIdToken());
        return input.readJsonContent(IDToken.class);
    }

    private AccessToken getAccessToken(org.keycloak.representations.AccessTokenResponse tokenResponse) throws JWSInputException {
        JWSInput input = new JWSInput(tokenResponse.getToken());
        return input.readJsonContent(AccessToken.class);
    }

    protected Response executeGrantAccessTokenRequest(WebTarget grantTarget) {
        String username = "test-user@localhost";
        String password = "password";
        return executeGrantRequest(grantTarget, username, password);
    }

    protected Response executeGrantRequest(WebTarget grantTarget, String username, String password) {
        String header = BasicAuthHelper.createHeader("test-app", "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
                .param("username", username)
                .param("password", password);
        return grantTarget.request()
                .header(HttpHeaders.AUTHORIZATION, header)
                .post(Entity.form(form));
    }
}


text:
namespace pdalboost
{
  namespace system
  {
    //  To construct an error_code after a API error:
    //
    //      error_code( errno, system_category() )

    //  User code should use the portable "posix" enums for POSIX errors; this
    //  allows such code to be portable to non-POSIX systems. For the non-POSIX
    //  errno values that POSIX-based systems typically provide in addition to
    //  POSIX values, use the system specific enums below.

    namespace linux_error
    {
      enum linux_errno
      {
        advertise_error = EADV,
        bad_exchange = EBADE,
        bad_file_number = EBADFD,
        bad_font_format = EBFONT,
        bad_request_code = EBADRQC,
        bad_request_descriptor = EBADR,
        bad_slot = EBADSLT,
        channel_range = ECHRNG,
        communication_error = ECOMM,
        dot_dot_error = EDOTDOT,
        exchange_full = EXFULL,
        host_down = EHOSTDOWN,
        is_named_file_type= EISNAM,
        key_expired = EKEYEXPIRED,
        key_rejected = EKEYREJECTED,
        key_revoked = EKEYREVOKED,
        level2_halt= EL2HLT,
        level2_no_syncronized= EL2NSYNC,
        level3_halt = EL3HLT,
        level3_reset = EL3RST,
        link_range = ELNRNG,
        medium_type = EMEDIUMTYPE,
        no_anode= ENOANO,
        no_block_device = ENOTBLK,
        no_csi = ENOCSI,
        no_key = ENOKEY,
        no_medium = ENOMEDIUM,
        no_network = ENONET,
        no_package = ENOPKG,
        not_avail = ENAVAIL,
        not_named_file_type= ENOTNAM,
        not_recoverable = ENOTRECOVERABLE,
        not_unique = ENOTUNIQ,
        owner_dead = EOWNERDEAD,
        protocol_no_supported = EPFNOSUPPORT,
        remote_address_changed = EREMCHG,
        remote_io_error = EREMOTEIO,
        remote_object = EREMOTE,
        restart_needed = ERESTART,
        shared_library_access = ELIBACC,
        shared_library_bad = ELIBBAD,
        shared_library_execute = ELIBEXEC,
        shared_library_max_ = ELIBMAX,
        shared_library_section= ELIBSCN,
        shutdown = ESHUTDOWN,
        socket_type_not_supported = ESOCKTNOSUPPORT,
        srmount_error = ESRMNT,
        stream_pipe_error = ESTRPIPE,
        too_many_references = ETOOMANYREFS,
        too_many_users = EUSERS,
        unattached = EUNATCH,
        unclean = EUCLEAN
      };
    }  // namespace linux_error

# ifndef BOOST_SYSTEM_NO_DEPRECATED
    namespace Linux = linux_error;
# endif

    template<> struct is_error_code_enum<linux_error::linux_errno>
      { static const bool value = true; };

    namespace linux_error
    {
      inline error_code make_error_code( linux_errno e )
        { return error_code( e, system_category() ); }
    }

  }  // namespace system
}  // namespace pdalboost

#endif  // Linux

#endif  // BOOST_LINUX_ERROR_HPP


text:
package apple.coreanimation;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.coreimage.*;
import apple.coretext.*;
import apple.opengles.*;

/*<javadoc>*/
/*</javadoc>*/
@Library("QuartzCore/QuartzCore.h")
public class CAEmitterMode
    extends Object
     {

    /**
     * @since Available in iOS 5.0 and later.
     */
    @GlobalConstant("kCAEmitterLayerPoints")
    public static native NSString PointsValue();
    /**
     * @since Available in iOS 5.0 and later.
     */
    @GlobalConstant("kCAEmitterLayerOutline")
    public static native NSString OutlineValue();
    /**
     * @since Available in iOS 5.0 and later.
     */
    @GlobalConstant("kCAEmitterLayerSurface")
    public static native NSString SurfaceValue();
    /**
     * @since Available in iOS 5.0 and later.
     */
    @GlobalConstant("kCAEmitterLayerVolume")
    public static native NSString VolumeValue();

}


text:
parte: 2
capitulo: Capítulo 13
capituloSlug: capitulo-13
pagina: Exercício 2

title: Exercício 2

page-layout: exercise
---

<img src="{{site.baseurl}}/assets/graphics/content/2_6_1_2.png"/>


text:
require File.expand_path('../../lib/utilitylib.rb', __FILE__)
require File.expand_path('../../cisco_bgp/bgplib.rb', __FILE__)

# Test hash top-level keys
tests = {
  agent:         agent,
  master:        master,
  resource_name: 'cisco_bgp_af',
}

# Test hash test cases
tests[:default] = {
  desc:           '1.1 Default Properties',
  title_pattern:  '2 default ipv4 unicast',
  manifest_props: {
    additional_paths_install:      'default',
    additional_paths_receive:      'default',
    additional_paths_selection:    'default',
    additional_paths_send:         'default',
    advertise_l2vpn_evpn:          'default',
    client_to_client:              'default',
    dampen_igp_metric:             'default',
    dampening_state:               'default',
    dampening_half_time:           'default',
    dampening_max_suppress_time:   'default',
    dampening_reuse_time:          'default',
    dampening_suppress_time:       'default',
    default_information_originate: 'default',
    default_metric:                'default',
    distance_ebgp:                 'default',
    distance_ibgp:                 'default',
    distance_local:                'default',
    inject_map:                    'default',
    maximum_paths:                 'default',
    maximum_paths_ibgp:            'default',
    next_hop_route_map:            'default',
    networks:                      'default',
    redistribute:                  'default',
    suppress_inactive:             'default',
    table_map:                     'default',
    table_map_filter:              'default',
  },
  resource:       {
    'additional_paths_install'      => 'false',
    'additional_paths_receive'      => 'false',
    'additional_paths_send'         => 'false',
    'advertise_l2vpn_evpn'          => 'true',
    'client_to_client'              => 'true',
    'dampen_igp_metric'             => '600',
    'dampening_state'               => 'true',
    'dampening_half_time'           => '15',
    'dampening_max_suppress_time'   => '45',
    'dampening_reuse_time'          => '750',
    'dampening_suppress_time'       => '2000',
    'default_information_originate' => 'false',
    'distance_ebgp'                 => '20',
    'distance_ibgp'                 => '200',
    'distance_local'                => '220',
    'maximum_paths'                 => '1',
    'maximum_paths_ibgp'            => '1',
    'suppress_inactive'             => 'false',
    'table_map_filter'              => 'false',
  },
}

# Special case: When dampening_routemap is set to default
# it means that dampening is enabled without routemap.
tests[:default_dampening_routemap] = {
  desc:           '1.2 Default dampening_routemap',
  title_pattern:  '2 default ipv4 unicast',
  manifest_props: {
    dampening_routemap: 'default'
  },
  resource:       {
    'dampening_state'             => 'true',
    'dampening_half_time'         => '15',
    'dampening_max_suppress_time' => '45',
    'dampening_reuse_time'        => '750',
    'dampening_suppress_time'     => '2000',
  },
}

#
# non_default_properties
#
tests[:non_default] = {
  desc:           '2.1 Non Default Properties',
  title_pattern:  '2 default ipv4 unicast',
  manifest_props: {
    additional_paths_install:      'true',
    additional_paths_receive:      'true',
    additional_paths_selection:    'RouteMap',
    additional_paths_send:         'true',
    advertise_l2vpn_evpn:          'true',
    client_to_client:              'false',
    dampen_igp_metric:             '200',
    dampening_half_time:           '1',
    dampening_max_suppress_time:   '4',
    dampening_reuse_time:          '2',
    dampening_suppress_time:       '3',
    default_information_originate: 'true',
    default_metric:                '50',
    distance_ebgp:                 '30',
    distance_ibgp:                 '60',
    distance_local:                '90',
    maximum_paths:                 '9',
    maximum_paths_ibgp:            '9',
    next_hop_route_map:            'RouteMap',
    suppress_inactive:             'true',
    table_map:                     'RouteMap',
    table_map_filter:              'true',
  },
}

injectmap = Array[%w(nyc sfo), %w(sjc sfo copy-attributes)]
networks = Array[%w(192.168.5.0/24 RouteMap), %w(192.168.6.0/32)]
redistribute = Array[%w(lisp RouteMap), %w(static RouteMap)]
tests[:non_default_arrays] = {
  desc:           '2.2 Non Default Properties: Arrays',
  title_pattern:  '2 default ipv4 unicast',
  manifest_props: {
    inject_map:   injectmap,
    networks:     networks,
    redistribute: redistribute,
  },
  resource:       {
    inject_map:   "#{injectmap}",
    networks:     "#{networks}",
    redistribute: "#{redistribute}",
  },
}

# Special case: When dampening_routemap is mutually exclusive
# with other dampening properties.
tests[:non_default_dampening_routemap] = {
  desc:           '2.3 Non-Default dampening_routemap',
  title_pattern:  '2 default ipv4 unicast',
  manifest_props: { dampening_routemap: 'RouteMap' },
}

tests[:title_patterns_1] = {
  desc:          'T.1 Title Pattern',
  title_pattern: 'new_york',
  title_params:  { asn: '2', vrf: 'red', afi: 'ipv4', safi: 'unicast' },
  resource:      { 'ensure' => 'present' },
}

tests[:title_patterns_2] = {
  desc:          'T.2 Title Pattern',
  title_pattern: '2',
  title_params:  { vrf: 'blue', afi: 'ipv4', safi: 'unicast' },
  resource:      { 'ensure' => 'present' },
}

tests[:title_patterns_3] = {
  desc:          'T.3 Title Pattern',
  title_pattern: '2 cyan ipv4',
  title_params:  { safi: 'unicast' },
  resource:      { 'ensure' => 'present' },
}

tests[:l2vpn_evpn] = {
  desc:             '3.1 Address-family l2evpn/evpn',
  operating_system: 'nexus',
  platform:         'n(5|6|7|9)k',
  title_pattern:    '2 default l2vpn evpn',
  resource:         { 'ensure' => 'present' },
}

# class to contain the test_dependencies specific to this test case
class TestBgpAf < BaseHarness
  def self.unsupported_properties(ctx, tests, id)
    unprops = []

    vrf = ctx.vrf(tests[id])
    if ctx.operating_system == 'ios_xr'
      # IOS-XR does not support these properties
      unprops <<
        :additional_paths_install <<
        :advertise_l2vpn_evpn <<
        :dampen_igp_metric <<
        :default_information_originate <<
        :default_metric <<
        :inject_map <<
        :next_hop_route_map <<
        :suppress_inactive <<
        :table_map_filter

      if vrf != 'default'
        # IOS-XR does not support these properties under a non-default vrf
        unprops <<
          :client_to_client <<
          :dampening_state <<
          :dampening_half_time <<
          :dampening_max_suppress_time <<
          :dampening_reuse_time <<
          :dampening_routemap <<
          :dampening_suppress_time
      end
    else
      unprops << :advertise_l2vpn_evpn if vrf == 'default' || ctx.platform[/n(3|6)k$/]

      unprops << :additional_paths_install if ctx.platform[/n(3|9)k/]
      unprops << :additional_paths_selection if ctx.platform[/n9k$/] && (ctx.nexus_image[/I5.3/] || ctx.nexus_image[/I5.2/])
      unprops << :additional_paths_selection if ctx.platform[/n9k/] && ctx.nexus_image[/F2.1/]
    end
    unprops
  end

  # Overridden to properly handle dependencies for this test file.
  def self.dependency_manifest(ctx, tests, id)
    extra_config = ''
    if ctx.operating_system == 'ios_xr'
      vrf = ctx.vrf(tests[id])

      # XR requires the following before a vrf AF can be configured:
      #   1. a global router_id
      #   2. a global address family
      #   3. route_distinguisher configured on the vrf
      extra_config = "
        cisco_bgp { '2 default':
          ensure              => present,
          router_id           => '1.2.3.4',
        }"

      parent_title = '2 default vpnv4 unicast'
      if parent_title != tests[id][:title_pattern]
        extra_config += "
          cisco_bgp_af { '#{parent_title}':
            ensure            => present,
          }"
      end

      # Ensure any needed route-policies are present.
      # TODO: Replace this with cisco_route_policy config,
      # when/if that is available.
      extra_config += "
        cisco_command_config { 'policy_config':
          command => '
            route-policy RouteMap
              end-policy'
        }"

      if vrf != 'default'
        extra_config += "
        cisco_bgp { '2 #{vrf}':
          ensure              => present,
          route_distinguisher => auto,
        }"
      end
    end
    extra_config
  end
end

def test_harness_bgp_af_run(tests, id)
  test_harness_run(tests, id, harness_class: TestBgpAf) # test in default vrf
  test_harness_bgp_vrf(tests, id, 'blue', harness_class: TestBgpAf) # test in non-default vrf
end

def cleanup(agent)
  if operating_system == 'nexus'
    test_set(agent, 'no feature bgp')
  else
    resource_absent_cleanup(agent, 'cisco_bgp')
  end
end

#################################################################
# TEST CASE EXECUTION
#################################################################
test_name "TestCase :: #{tests[:resource_name]}" do
  teardown { cleanup(agent) }
  cleanup(agent)

  # -----------------------------------
  logger.info("\n#{'-' * 60}\nSection 1. Default Property Testing")
  id = :default
  test_harness_run(tests, id, harness_class: TestBgpAf)

  tests[id][:ensure] = :absent
  test_harness_run(tests, id, harness_class: TestBgpAf)
  test_harness_run(tests, :default_dampening_routemap, harness_class: TestBgpAf)

  # -------------------------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 2. Non Default Property Testing")
  cleanup(agent)
  test_harness_bgp_af_run(tests, :non_default)
  test_harness_bgp_af_run(tests, :non_default_arrays)
  test_harness_bgp_af_run(tests, :non_default_dampening_routemap)

  # -------------------------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 3. Title Pattern Testing")
  cleanup(agent)
  test_harness_run(tests, :title_patterns_1, harness_class: TestBgpAf)
  test_harness_run(tests, :title_patterns_2, harness_class: TestBgpAf)
  test_harness_run(tests, :title_patterns_3, harness_class: TestBgpAf)
  test_harness_run(tests, :l2vpn_evpn, harness_class: TestBgpAf) unless nexus_image['I2']
end
logger.info("TestCase :: #{tests[:resource_name]} :: End")


text:
snake_game: snake_game.c
	gcc snake_game.c -lncurses -lpthread -o snake_game