text:
Lab 1 - Cross-Account Authentication

Overview

This lab will demonstrate how to delegate access to resources that are in different AWS accounts. In this way, you can share resources in one account with users in a different account. There is no need to create individual IAM users in each account, nor will users have to sign out of one account and sign into another. This could be a great way to help manage a small team of people who would need access to a small number of accounts. The concepts introduced in this lab act as a starting point for managing cross account access, and can be extended to decrease operational overhead as the number of users and accounts grow with the addition of federation.

Objectives

After completing this lab, you will be able to:

Create IAM roles that allow you to delegate access across AWS Accounts

Switch between roles using either the AWS console or the AWS CLI in order to access resources within a different AWS account

Prerequisites

This lab requires:

Access to a notebook computer with Wi-Fi running Microsoft Windows, Mac OS X, or Linux (Ubuntu, SuSE, or Red Hat)

For Microsoft Windows users: Administrator access to the computer

An Internet browser such as Chrome, Firefox, or IE9 (previous versions of Internet Explorer are not supported)

An SSH client such as PuTTY

Duration

This lab will take approximately 30 minutes to complete.

Accessing the AWS Management Console

Click Start Lab to launch the lab.

Click Open Console

Sign in to the AWS Management Console using the credentials shown to the left of these instructions.

 Please do not change the Region during this lab.

Before you begin

In order to complete this lab, you will need access to two AWS accounts. The easiest way to accomplish this is to partner up with another student. You and your partner will be completing the following steps simultaneously, each in your own account. So, take a minute to find a person near you to work with throughout this lab.

Task 1: Create a cross-account role

First, you will use the AWS Management Console to establish trust with your partner's account. You do this by creating an IAM role and specifying a permissions policy that allows trusted users to access your account.

Exchange account numbers with your partner.

Note: You and your partner must be using different account numbers, otherwise you will not be able to successfully complete this lab. If you happen to pick a partner with the same account number, you will need to find another partner.

In the AWS Management Console, under the Services menu, click IAM.

In the navigation pane, click Roles.

Click the Create role button.

In the Select type of trusted entity section, click on Another AWS account.

In the Specify accounts that can use this role section, enter your partner's account number for Account ID.

Click on the Next: Permissions button.

In the Attach permissions policies section, select the <input readonly="" class="copyable-inline-input" size="13" type="text" value="SecurityAudit"> policy.

Note: You may want to use the filter option to search for <input readonly="" class="copyable-inline-input" size="13" type="text" value="SecurityAudit"> in order to quickly locate the policy.

Take a moment to view the SecurityAudit policy. What are the allowed actions that this policy facilitates? Discuss this with your lab partner if possible.

Click on the Next: Tags button.

Click on the Next: Review button.

In the Review section, enter <input readonly="" class="copyable-inline-input" size="19" type="text" value="RemoteSecurityAudit"> for Role name.

Click on the Create role button.

Once the role RemoteSecurityAudit has been created, click on it to view it's details.

Note: You may want to use the filter option to search for <input readonly="" class="copyable-inline-input" size="19" type="text" value="RemoteSecurityAudit"> in order to quickly locate the role.

In the Summary section, click on the Trust relationships tab.

Observe that your partner's account is a trusted entity. Only a trusted account will be allowed to assume this role.

In the AWS Management Console, under the Services menu, click EC2.

In the navigation pane, click Instances.

Edit the name of the JumpServer instance by hovering your mouse cursor over the name and clicking on the pencil icon that appears.

Change the name of your instance to be <input readonly="" class="copyable-inline-input" size="20" type="text" value="JumpServer-YOUR_NAME"> where you replace <input readonly="" class="copyable-inline-input" size="9" type="text" value="YOUR_NAME"> with your first name. You will use this custom-named server later to prove that you have successfully switched accounts.

Wait for your partner to finish Task 1 before proceeding to Task 2.

Task 2: Assume the role from the console

Now that you and your partner have created cross-account roles, it is time to test them out. In this task, you will use the AWS Management console to sign into each other's account.

In the AWS Management Console, click on your login name (awsstudent) in the title bar and click Switch Role.

In the Account field, enter your partner's account number.

In the Role field, enter <input readonly="" class="copyable-inline-input" size="19" type="text" value="RemoteSecurityAudit">

Click the Switch Role button.

You have now switched roles. Instead of seeing awsstudent in the title bar, you should see RemoteSecurityAudit instead.

In the AWS Management Console, under the Services menu, click EC2.

In the navigation pane, click Instances.

You should see the JumpServer instance, but this time it should have your partner's name instead of your own.

Go ahead and navigate around in your partner's account if you wish. The role you are using is limited to read-only access, so attempting to create or change anything should result in an authentication error.

Once you are done exploring, it is time to switch back to your original account.

In the AWS Management Console, click on your login name (RemoteSecurityAudit) in the title bar and click Back to awsstudent.

Wait for your partner to finish Task 2 before proceeding to Task 3.

So now you can access another AWS account by using the management console. But what if you need cross-account access for an automated task? For the next task, you will learn how to access your partner's account using the AWS CLI.

Task 3: Create a policy to allow switching roles

Lets explore another way to access a second account. AWS resources like EC2 instances are able to assume a role as well. The instance will handle the key rotation several times per day. To setup this up, you are going to create another IAM policy, and attach that to a new role with a trust policy to the EC2 service.

In the AWS Management Console, under the Services menu, click IAM.

In the navigation pane, click Policies.

Click the Create policy button.

In the Create policy section, click on the JSON tab and paste the following policy into the box:

Note: Make sure to either delete or to overwrite the default generated empty policy.

{
            "Version": "2012-10-17",
            "Statement": [{
                    "Sid": "VisualEditor0",
                    "Effect": "Allow",
                    "Action": "sts:AssumeRole",
                    "Resource": "arn:aws:iam::*:role/RemoteSecurityAudit"
                }
            ]
}
<button class="button button--copy js-copy-button-0"></button>

This policy will allow for the EC2 instance to assume the role RemoteSecurityAudit in any account. If you changed the *
to the account number of your partners lab account, you could further scope down this permissions.

Click the Review policy button.

On the Create policy page, in the Name field enter <input readonly="" class="copyable-inline-input" size="19" type="text" value="CLIAssumeRolePolicy">

Click the Create policy button.

Task 4: Create a role for your EC2 instance

You are now going to create the role, and attach the policy you created in the last task.

In the navigation pane, click Roles.

Click the Create role button.

In the Choose the service that will use this role section, click on EC2.

Click on the Next: Permissions button.

In the Attach permissions policies section, select the <input readonly="" class="copyable-inline-input" size="19" type="text" value="CLIAssumeRolePolicy"> policy.

Note: You may want to use the filter option to search for <input readonly="" class="copyable-inline-input" size="19" type="text" value="CLIAssumeRolePolicy"> in order to quickly locate the role.

Click on the Next: Tags button.

Click on the Next: Review button.

In the Review section, for Role name enter <input readonly="" class="copyable-inline-input" size="13" type="text" value="CLIAssumeRole">

Click on the Create role button.

Task 5: Attach the new role to your EC2 instance

Now that the role is established and the EC2 service has access you can associate the role with individual instances.

In the AWS Management Console, under the Services menu, click EC2.

In the navigation pane, click Instances.

Select the JumpServer EC2 instance, and click on Actions.

Under the Instance Settings category, click on Attach/Replace IAM Role.

In the Attach/Replace IAM Role section, for IAM role select <input readonly="" class="copyable-inline-input" size="13" type="text" value="CLIAssumeRole">

Click on the Apply button.

Click on the Close button.

Now that our JumpServer is configured to access the role that grants it access to STS:AssumeRole, you need to update the trust policy for the role in your partner's account.

Important Your partner must have finished this step before you can proceed to the next step. If they have not associated their Jumphost with the role you will get an access denied error in later steps.

Navigate back to the IAM Service in the management console

In the navigation pane, click Roles.

Click on RemoteSecurityAudit to view the details of the role.

Note: You may want to use the filter option to search for <input readonly="" class="copyable-inline-input" size="19" type="text" value="RemoteSecurityAudit"> in order to quickly locate the role.

In the Summary section, click on the Trust relationships tab.

Observe that your partner's account is a trusted entity. Lets update the trust policy to scope down access a little more then just to any one in the account.

Click on the Edit trust relationship button.

In the editor, update the json to look like this, replacing <input readonly="" class="copyable-inline-input" size="19" type="text" value="PARTNER_INSTANCE_ID"> and <input readonly="" class="copyable-inline-input" size="22" type="text" value="PARTNER_ACCOUNT_NUMBER"> where appropriate. This policy will allow a single instance to assume this role. <input readonly="" class="copyable-inline-input" size="19" type="text" value="PARTNER_INSTANCE_ID"> is the EC2 instance ID of JumpServer in your partners account, not the one that is running in your account.

{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "AWS": [
                    "arn:aws:sts::PARTNER_ACCOUNT_NUMBER:assumed-role/CLIAssumeRole/PARTNER_INSTANCE_ID",
                    "arn:aws:iam::PARTNER_ACCOUNT_NUMBER:root"
                    ]
                },
                "Action": "sts:AssumeRole"
            }
        ]
}
<button class="button button--copy js-copy-button-1"></button>

Click the Update Trust Policy button.

Task 6: Connect to your Amazon Linux EC2 Instance

You have now attached the role to your instance, this will grant the role permissions to any shell user or program running on that host. In this task, you will run a remote shell and execute AWS CLI commands against your partners account.

In the AWS Management Console, under the Services menu, click EC2.

In the navigation pane, click on Instances.

From the list of EC2 Instances, select JumpServer and note the Public DNS (IPv4) address. The Public DNS is available in the bottom pane.

Access to a Linux EC2 instance requires a secure connection using an SSH client. The following directions walk you through the process of connecting to your Amazon Linux EC2 instance.

Choose one of the following guides:

- Connecting from a Windows Machine
- Connecting from a macOS or Linux Machine
<button class="button button--copy js-copy-button-2"></button>

Connecting from a Windows Machine

Note: Only perform the following steps if you are connecting from a Windows machine, otherwise skip ahead to "Connecting from a macOS or Linux Machine".

To the left of the instructions you are currently reading, click  Download PPK.

If it is not already installed, download the PuTTY.exe client to a folder of your choice from the following URL: <input readonly="" class="copyable-inline-input" size="63" type="text" value="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">

Open PuTTY.exe.

In the Basic options for your PuTTY Session pane, for Host Name (or IP address), type <input readonly="" class="copyable-inline-input" size="19" type="text" value="ec2-user@PUBLIC_DNS">, where <input readonly="" class="copyable-inline-input" size="10" type="text" value="PUBLIC_DNS"> is the Public DNS address of your Amazon EC2 instance that you copied earlier.

This will log you in to the remote server as the user <input readonly="" class="copyable-inline-input" size="8" type="text" value="ec2-user">, which is the default user on Amazon Linux on EC2.

In the navigation pane, click Connection.

Set the following options to keep your SSH connection active as you complete the lab:

For Seconds between keepalives (0 to turn off), set the value to <input readonly="" class="copyable-inline-input" size="2" type="text" value="50">

For Enable TCP keepalives (SO_KEEPALIVE option), enable the checkbox.

In the navigation pane, click Connection -> SSH -> Auth.

For Private key file for authentication, click Browse.

Select the PPK file you downloaded earlier and click Open.

This file is usually located in the Downloads folder on your PC.

Click Open to initiate the remote session.

PuTTY will ask whether you wish to cache the server's host key. Click Yes.

Result

You are now connected to the JumpServer. When lab instructions in subsequent sections require a command window, continue using your SSH terminal window.

Connecting from a macOS or Linux Machine

Note: Only perform the following steps if you are connecting from a macOS or Linux machine, otherwise skip ahead to the next task.

To the left of the instructions you are currently reading, click  Download PEM.

Open the Terminal application.

Complete the remaining connection steps in the terminal window.

Change directory to the folder where the PEM file has been downloaded (i.e. <input readonly="" class="copyable-inline-input" size="14" type="text" value="cd ~/Downloads">).

Change the permissions on the PEM file using the command below.

Replace <input readonly="" class="copyable-inline-input" size="8" type="text" value="PEM_FILE"> with the name of the PEM file you downloaded.

chmod 400 PEM_FILE
<button class="button button--copy js-copy-button-3"></button>

Use the command below to log in to the remote instance as user <input readonly="" class="copyable-inline-input" size="8" type="text" value="ec2-user">

Replace <input readonly="" class="copyable-inline-input" size="8" type="text" value="PEM_FILE"> with the name of the PEM file you downloaded and replace <input readonly="" class="copyable-inline-input" size="10" type="text" value="PUBLIC_DNS"> with the Public DNS address of your EC2 instance.

ssh -i PEM_FILE ec2-user@PUBLIC_DNS
<button class="button button--copy js-copy-button-4"></button>

Upon prompt enter yes

Result

You are now connected to the JumpServer. When lab instructions in subsequent sections require a command window, continue using your SSH terminal window.

Task 7: Connect to your partner's account using AWS CLI

In order to configure the AWS CLI tool, run the following in your command window:

aws configure
<button class="button button--copy js-copy-button-5"></button>

Enter the following information:

AWS Access Key ID: Press Enter

AWS Secret Access Key: Press Enter

Default region name: Enter the DefaultRegionName shown to the left of the             instructions you are currently reading

Default output format: Press Enter

By not typing in a Access Key ID or a Secret Access Key, the EC2 Instance will look to the IAM role that you assigned to the EC2 instance back in Task 5. Remember that this policy was only allowing STS:AssumeRole.

Use this command to assume the role your partner prepared for you in their account:

Replace <input readonly="" class="copyable-inline-input" size="22" type="text" value="PARTNER_ACCOUNT_NUMBER"> with your partner's account number before running the command.

aws sts assume-role --role-arn arn:aws:iam::PARTNER_ACCOUNT_NUMBER:role/RemoteSecurityAudit --role-session-name RemoteSecurityAudit
<button class="button button--copy js-copy-button-6"></button>

Note: The command will produce temporary credentials (an Access Key, Secret Access Key, and Session Token) that can be used to access your partner's account.

You then set the shell user environment variables the temporary credential of your partner account. The CLI will select environmental variables over instance profile.

Set the relevant AWS environment variables to point to the credentials that'll give you access to the other account:

Replace <input readonly="" class="copyable-inline-input" size="13" type="text" value="ACCESS_KEY_ID">, <input readonly="" class="copyable-inline-input" size="19" type="text" value="SECURITY_ACCESS_KEY"> and <input readonly="" class="copyable-inline-input" size="13" type="text" value="SESSION_TOKEN"> with the values provided from the previous step before running the commands.

export AWS_ACCESS_KEY_ID=ACCESS_KEY_ID
<button class="button button--copy js-copy-button-7"></button>

export AWS_SECRET_ACCESS_KEY=SECURITY_ACCESS_KEY
<button class="button button--copy js-copy-button-8"></button>

export AWS_SESSION_TOKEN=SESSION_TOKEN
<button class="button button--copy js-copy-button-9"></button>

Display the list of EC2 instances in the other account using this command:

aws ec2 describe-instances --output table --query 'Reservations[].Instances[].[Tags[?Key==`Name`] | [0].Value,InstanceId,InstanceType]'
<button class="button button--copy js-copy-button-10"></button>

The instance name should contain your partner's name. If you see the correct name, then your CLI command is returning results from the other account and your cross-account role is working!

Lab Complete

 Congratulations! You have completed the lab.

Click End Lab at the top of this page to clean up your lab environment.


text:
angular.module('app', ['angularFileUpload'])

  // The example of the full functionality
  .controller('TestController',function ($scope, $fileUploader) {
    'use strict';

    // create a uploader with options
    var uploader = $scope.uploader = $fileUploader.create({
      scope: $scope,                          // to automatically update the html. Default: $rootScope
      url: '/api/containers/container1/upload',
      formData: [
        { key: 'value' }
      ],
      filters: [
        function (item) {                    // first user filter
          console.info('filter1');
          return true;
        }
      ]
    });

    // ADDING FILTERS

    uploader.filters.push(function (item) { // second user filter
      console.info('filter2');
      return true;
    });

    // REGISTER HANDLERS

    uploader.bind('afteraddingfile', function (event, item) {
      console.info('After adding a file', item);
    });

    uploader.bind('whenaddingfilefailed', function (event, item) {
      console.info('When adding a file failed', item);
    });

    uploader.bind('afteraddingall', function (event, items) {
      console.info('After adding all files', items);
    });

    uploader.bind('beforeupload', function (event, item) {
      console.info('Before upload', item);
    });

    uploader.bind('progress', function (event, item, progress) {
      console.info('Progress: ' + progress, item);
    });

    uploader.bind('success', function (event, xhr, item, response) {
      console.info('Success', xhr, item, response);
      $scope.$broadcast('uploadCompleted', item);
    });

    uploader.bind('cancel', function (event, xhr, item) {
      console.info('Cancel', xhr, item);
    });

    uploader.bind('error', function (event, xhr, item, response) {
      console.info('Error', xhr, item, response);
    });

    uploader.bind('complete', function (event, xhr, item, response) {
      console.info('Complete', xhr, item, response);
    });

    uploader.bind('progressall', function (event, progress) {
      console.info('Total progress: ' + progress);
    });

    uploader.bind('completeall', function (event, items) {
      console.info('Complete all', items);
    });

  }
).controller('FilesController', function ($scope, $http) {

    $scope.load = function () {
      $http.get('/api/containers/container1/files').success(function (data) {
        console.log(data);
        $scope.files = data;
      });
    };

    $scope.delete = function (index, id) {
      $http.delete('/api/containers/container1/files/' + encodeURIComponent(id)).success(function (data, status, headers) {
        $scope.files.splice(index, 1);
      });
    };

    $scope.$on('uploadCompleted', function(event) {
      console.log('uploadCompleted event received');
      $scope.load();
    });

  });

redpajama_set_name: RedPajamaGithub


text:
/*jslint node: true */
"use strict";

var mongodb = require('mongodb').MongoClient;
var objectId = require('mongodb').ObjectID;

var bookController = function (bookService, nav) {

    var middleware = function (req, res, next) {
        if (!req.user) {
            res.redirect('/'); // if you are not logged in - go back to slash / ;-)
        }
        next();
    };

    var getIndex = function (req, res) {

        var url = 'mongodb://localhost:27017/libraryApp';

        mongodb.connect(url, function (err, db) {
            var collection = db.collection('books');
            collection.find({}).toArray(function (err, results) {
                // TODO: check if not error and then:
                res.render('bookListView', {
                    title: 'Books',
                    nav: nav,
                    books: results
                });
            });
        });
    };

    var getById = function (req, res) {
        var id = new objectId(req.params.id);
        var url = 'mongodb://localhost:27017/libraryApp';

        mongodb.connect(url, function (err, db) {
            var collection = db.collection('books');
            collection.findOne({
                _id: id
            }, function (err, results) {
                // TODO: check if not error and then:
                if (results.bookId) {
                    bookService.getBookById(results.bookId, function (err, book) {
                        results.book = book;
                        res.render('bookView', {
                            title: 'Book',
                            nav: nav,
                            book: results
                        });
                    });
                } else {
                    res.render('bookView', {
                        title: 'Book',
                        nav: nav,
                        book: results
                    });
                }
            });
        });
    };

    return {
        getIndex: getIndex,
        getById: getById,
        middleware: middleware
    };
};

module.exports = bookController;


text:
'use strict';

var config    = require('../config/config');
var express   = require('express');
var router    = express.Router();
var request   = require('request');

/* GET home page. */
router.get('/', function (req, res, next) {
	return res.render('index', { view: { dashboard: 0 } });
});

router.get('/dashboard', function (req, res, next) {
	return res.render('dashboard', { view: { dashboard: 1 } });
});

router.get('/user/:userid', function (req, res, next) {
	console.dir(req.params.userid);
	return res.render('user', { view: { dashboard: 0 } });
});

router.get('/groups', function (req, res, next) {
	req.pipe(request('https://cv-sharing-hackaton.herokuapp.com/groups')).pipe(res);
});

router.post('/savecv', function (req, res, next) {
	request.post({
		url: config.addAPI,
		json: true,
		body: req.body
	}, function (error, response, body) {
		if (error)
			return res.status(500).send(error);
		return res.status(200).send({ id: body });
	});
});

router.post('/share/:userId', function (req, res, next) {
	var url = config.shareAPI.split(/{id}/)[0] + req.params.userId + config.shareAPI.split(/{id}/)[1];
	request.post({
		url: url,
		qs: { groupId: req.query.groupId },
		json: true
	}, function (error, response, body) {
		if (error)
			return res.status(500).send(error);
		return res.status(200).send({ 'url': body });
	});
});

module.exports = router;


text:
require "#{File.dirname(File.dirname(File.expand_path(__FILE__)))}/spec_helper"

describe "Sinatra" do

  describe "Tags" do

    class MyTestApp
      register(Sinatra::Tags)
    end

    class MyCustomTestApp < Sinatra::Base
      register(Sinatra::Tags)
      set :tags_add_newlines_after_tags, false
      set :tags_output_format_is_xhtml, true
    end

    # convenience shared spec that sets up MyTestApp and tests it's OK,
    # without it you will get "stack level too deep" errors
    it_should_behave_like "MyTestApp"

    describe "VERSION" do

      it "should return the VERSION string" do
        Sinatra::Tags::VERSION.should be_a_kind_of(String)
        Sinatra::Tags::VERSION.should match(/\d\.\d+\.\d+(\.\d)?/)
      end

    end #/ VERSION

    describe "#self.version" do

      it "should return a version of the Sinatra::Tags VERSION string" do
        Sinatra::Tags.version.should be_a_kind_of(String)
        Sinatra::Tags.version.should match(/Sinatra::Tags v\d\.\d+\.\d+(\.\d)?/)
      end

    end #/ #self.version

    describe "Configuration" do

      describe "with Default settings" do

        it "should set the :tags_add_newlines_after_tags to 'true'" do
          MyTestApp.tags_add_newlines_after_tags.should == true
        end

        it "should set the :tags_output_format_is_xhtml to 'false'" do
          MyTestApp.tags_output_format_is_xhtml.should == false
        end

      end #/ with Default settings

      describe "with Custom Settings" do

        it "should set the :tags_add_newlines_after_tags to 'true'" do
          MyCustomTestApp.tags_add_newlines_after_tags.should == false
        end

        it "should set the :tags_output_format_is_xhtml to 'false'" do
          MyCustomTestApp.tags_output_format_is_xhtml.should == true
        end

      end #/ with Custom Settings

    end #/ Configuration

    describe "Helpers" do

      describe "#tag" do

        it "should return nothing when block tag <% tag(:div) %> is used without a block" do
          erb_app '<% tag(:div) %>'
          body.should == ''

          haml_app '- tag(:div)'
          body.should == "\n"
        end

        describe "multi line tags " do

          %w(
            a address applet bdo big blockquote body button caption center
            colgroup dd dir div dl dt fieldset form frameset head html iframe
            map noframes noscript object ol optgroup pre script select small
            style table tbody td tfoot th thead title tr tt ul
          ).each do |t|

            describe "like <#{t}>" do

              it "should have a '\\n' after the opening tag and before the closing tag" do
                erb_app "<%= tag(:#{t},'contents') %>"
                body.should == "<#{t}>\ncontents\n</#{t}>\n"

                haml_app "= tag(:#{t},'contents')"
                body.should == "<#{t}>\ncontents\n</#{t}>\n"
              end

              it "should work without contents passed in" do
                erb_app "<%= tag(:#{t},nil) %>"
                body.should == "<#{t}>\n\n</#{t}>\n"

                haml_app "= tag(:#{t},nil)"
                body.should == "<#{t}>\n\n</#{t}>\n"
              end

              it "should allow a hash of attributes to be passed" do
                erb_app "<%= tag(:#{t},'contents', :id => 'tag-id', :class => 'tag-class') %>"
                body.should have_tag("#{t}#tag-id.tag-class","\ncontents\n")

                haml_app "= tag(:#{t},'contents', :id => 'tag-id', :class => 'tag-class')"
                body.should have_tag("#{t}#tag-id.tag-class","\ncontents\n")
              end

              it "with ':newline => false' should NOT add '\\n' around the contents" do
                erb_app "<%= tag(:#{t},'content', :id => 'tag-id', :newline => false) %>"
                body.should == "<#{t} id=\"tag-id\">content</#{t}>\n"

                haml_app "= tag(:#{t},'content', :id => 'tag-id', :newline => false)"
                body.should == "<#{t} id=\"tag-id\">content</#{t}>\n"
              end

            end #/ like ##{t}

          end #/ loop

          describe "like <textarea>" do

            it "should NOT have a '\\n' after the opening tag and before the closing tag" do
              erb_app "<%= tag(:textarea,'contents') %>"
              body.should == "<textarea>contents</textarea>\n"

              haml_app "= tag(:textarea,'contents')"
              body.should == "<textarea>contents</textarea>\n"
            end

            it "should work without contents passed in" do
              erb_app "<%= tag(:textarea,nil) %>"
              body.should == "<textarea></textarea>\n"

              haml_app "= tag(:textarea,nil)"
              body.should == "<textarea></textarea>\n"
            end

            it "should allow a hash of attributes to be passed" do
              erb_app "<%= tag(:textarea,'contents', :id => 'tag-id', :class => 'tag-class') %>"
              body.should have_tag("textarea#tag-id.tag-class","contents")

              haml_app "= tag(:textarea,'contents', :id => 'tag-id', :class => 'tag-class')"
              body.should have_tag("textarea#tag-id.tag-class","contents")
            end

            it "with ':newline => false' should NOT add '\\n' around the contents" do
              erb_app "<%= tag(:textarea,'content', :id => 'tag-id', :newline => false) %>"
              body.should == "<textarea id=\"tag-id\">content</textarea>\n"

              haml_app "= tag(:textarea,'content', :id => 'tag-id', :newline => false)"
              body.should == "<textarea id=\"tag-id\">content</textarea>\n"
            end

          end #/ like #textarea

        end #/ multi line tags

        describe "self-closing tags " do

          %w( area base br col frame hr img input link meta param ).each do |t|

            describe "like <#{t}>" do

              it "should be self-closed and with a trailing '\\n'" do
                erb_app "<%= tag(:#{t}) %>"
                body.should == "<#{t}>\n"

                haml_app "= tag(:#{t})"
                body.should == "<#{t}>\n"
              end

              it "should ignore the content passed in" do
                erb_app "<%= tag(:#{t},'content') %>"
                body.should == "<#{t}>\n"

                haml_app "= tag(:#{t},'content')"
                body.should == "<#{t}>\n"
              end

              it "should allow a hash of attributes to be passed" do
                erb_app "<%= tag(:#{t}, :id => 'tag-id', :class => 'tag-class') %>"
                body.should have_tag("#{t}#tag-id.tag-class")

                haml_app "= tag(:#{t}, :id => 'tag-id', :class => 'tag-class')"
                body.should have_tag("#{t}#tag-id.tag-class")
              end

              it "with ':newline => false' ERB does NOT add a '\\n' after the tag" do
                erb_app "<%= tag(:#{t},:id => 'tag-id', :newline => false) %>"
                body.should == "<#{t} id=\"tag-id\">"
              end

              it "with ':newline => false' Haml DOES add a '\\n' after the tag" do
                haml_app "= tag(:#{t},:id => 'tag-id', :newline => false)"
                body.should == "<#{t} id=\"tag-id\">\n"
              end

            end #/ #{t}

          end #/loop

        end #/ self-closing tag

        describe "single line tags " do

          %w(
            abbr acronym b cite code del dfn em h1 h2 h3 h4 h5 h6 i kbd
            label legend li option p q samp span strong sub sup var
          ).each do |t|

          describe "like <#{t}>" do

            it "should strip the '\\n' around the content" do
              erb_app "<%= tag(:#{t}, 'content', :id => 'tag-id') %>"
              body.should have_tag("#{t}#tag-id", 'content')
              body.should == "<#{t} id=\"tag-id\">content</#{t}>\n"

              haml_app "= tag(:#{t}, 'content', :id => 'tag-id')"
              body.should have_tag("#{t}#tag-id", 'content')
              body.should == "<#{t} id=\"tag-id\">content</#{t}>\n"
            end

            it "should work without contents passed in" do
              erb_app "<%= tag(:#{t},nil) %>"
              body.should == "<#{t}></#{t}>\n"

              haml_app "= tag(:#{t},nil)"
              body.should == "<#{t}></#{t}>\n"
            end

            it "should allow a hash of attributes to be passed" do
              erb_app "<%= tag(:#{t},'content', :id => 'tag-id', :class => 'tag-class') %>"
              body.should have_tag("#{t}#tag-id.tag-class","content")

              haml_app "= tag(:#{t},'content', :id => 'tag-id', :class => 'tag-class') "
              body.should have_tag("#{t}#tag-id.tag-class","content")
            end

            it "should be made multi-line tags with ':newline => true'" do
              erb_app "<%= tag(:#{t},'content',:id => 'tag-id', :newline => true) %>"
              body.should == "<#{t} id=\"tag-id\">\ncontent\n</#{t}>\n"

              haml_app "= tag(:#{t},'content',:id => 'tag-id', :newline => true)"
              body.should == "<#{t} id=\"tag-id\">\ncontent\n</#{t}>\n"
            end

          end #/ like #{t}

          end #/loop

        end #/ single line tags

        describe "with Boolean attributes " do

          %w(selected checked disabled readonly multiple).each do |attr|

          describe "like ##{attr}" do

            it "should set '#{attr}=\"#{attr}\"' when '#{attr} => true'" do
              erb_app "<%= tag(:input, :type => :dummy, :#{attr} => true) %>"
              body.should have_tag("input[@#{attr}=#{attr}]")

              haml_app "= tag(:input, :type => :dummy, :#{attr} => true)"
              body.should have_tag("input[@#{attr}=#{attr}]")
            end

            it "should NOT set '#{attr}=\"#{attr}\"' when '#{attr} => false'" do
              erb_app "<%= tag(:input, :type => :dummy, :#{attr} => false) %>"
              body.should_not have_tag("input[@#{attr}=#{attr}]")

              haml_app "= tag(:input, :type => :dummy, :#{attr} => false) "
              body.should_not have_tag("input[@#{attr}=#{attr}]")
            end

            it "should NOT set '#{attr}=\"#{attr}\"' when '#{attr} => nil'" do
              erb_app "<%= tag(:input, :type => :dummy, :#{attr} => nil) %>"
              body.should_not have_tag("input[@#{attr}=#{attr}]")

              haml_app "= tag(:input, :type => :dummy, :#{attr} => nil)"
              body.should_not have_tag("input[@#{attr}=#{attr}]")
            end

            it "should NOT set '#{attr}=\"#{attr}\"' when '#{attr} => [empty]'" do
              erb_app "<%= tag(:input, :type => :dummy, :#{attr} => '') %>"
              body.should_not have_tag("input[@#{attr}=#{attr}]")

              haml_app "= tag(:input, :type => :dummy, :#{attr} => '')"
              body.should_not have_tag("input[@#{attr}=#{attr}]")
            end

          end #/ ##{attr}

          end #/ boolean loop

        end #/ with Boolean attribute

        describe "with Blocks" do

          it "should buffer the tag contents within an ERB block" do
block = %Q[
<% tag(:div, :class => :list) do %>
  <% tag(:ol) do %>
    <%= tag(:li, 'A') %>
    <%= tag(:li, 'B') %>
  <% end %>
<% end  %>]
            erb_app block
            body.should have_tag('div.list > ol > li', "A")
            body.should have_tag('div.list > ol > li', "B")
          end

          it "should buffer the tag contents within a Haml block" do
block = %Q[
- tag(:div, :class => :list) do
  - tag(:ol) do
    = tag(:li, 'A')
    = tag(:li, 'B')
]
            haml_app block
            body.should have_tag('div.list > ol > li', "A")
            body.should have_tag('div.list > ol > li', "B")
          end

          it "should buffer content within nested ERB blocks" do
            block =  %Q[<% tag( :div, :id => 'comments') do  %>]
            block << %Q[ <% tag(:fieldset) do  %>]
            block << %Q[  <%= tag( :legend, 'Comments')  %>]
            block << %Q[  <%= tag( :textarea, 'test', :id => 'field-comments')  %>]
            block << %Q[  <%= tag(:span, 'Some description')  %>]
            block << %Q[ <% end  %>]
            block << %Q[ <% tag(:fieldset, :id => 'form-details') do  %>]
            block << %Q[  <%= tag(:legend, 'Details') %>]
            block << %Q[  <%= tag(:input, :type => :text, :value => 'City')  %>]
            block << %Q[ <% end  %>]
            block << %Q[<% end  %>]

            erb_app block
            # body.should have_tag(:debug)
            body.should have_tag('div#comments')
            body.should have_tag('div#comments > fieldset > legend', 'Comments')
            body.should have_tag('div#comments > fieldset > textarea#field-comments', "test")
            body.should have_tag('div#comments > fieldset > span', "Some description")
            #
            body.should have_tag('div#comments > fieldset#form-details')
            body.should have_tag('div#comments > fieldset#form-details > legend', 'Details')
            body.should have_tag('div#comments > fieldset#form-details > input[@type=text]')

          end

          it "should buffer content within nested Haml blocks" do
block =  %Q[
- tag( :div, :id => 'comments') do
  - tag(:fieldset) do
    = tag( :legend, 'Comments')
    = tag( :textarea, 'test', :id => 'field-comments')
    = tag(:span, 'Some description')

  - tag(:fieldset, :id => 'form-details') do
    = tag(:legend, 'Details')
    = tag(:input, :type => :text, :value => 'City')

]

            haml_app block
            # body.should have_tag(:debug)
            body.should have_tag('div#comments')
            body.should have_tag('div#comments > fieldset > legend', 'Comments')
            body.should have_tag('div#comments > fieldset > textarea#field-comments', "test")
            body.should have_tag('div#comments > fieldset > span', "Some description")
            #
            body.should have_tag('div#comments > fieldset#form-details')
            body.should have_tag('div#comments > fieldset#form-details > legend', 'Details')
            body.should have_tag('div#comments > fieldset#form-details > input[@type=text]')

          end

          it "should buffer simple HTML content within nested ERB blocks" do
            block =  %Q[<% tag( :div, :id => 'comments') do  %>]
            block << %Q[
Just plain HTML content
\n]
            block << %Q[ <% tag(:fieldset) do  %>]
            block << %Q[  <%= tag( :legend, 'Comments')  %>]
            block << %Q[
Even more plain HTML content
\n]
            block << %Q[  <%= tag( :textarea, 'test', :id => 'field-comments')  %>]
            block << %Q[  <%= tag(:span, 'Some description')  %>]
            block << %Q[ <% end  %>]
            block << %Q[
Loads of plain HTML content
\n]
            block << %Q[ <% tag(:fieldset, :id => 'form-details') do  %>]
            block << %Q[  <%= tag(:legend, 'Details') %>]
            block << %Q[  <%= tag(:input, :type => :text, :value => 'City')  %>]
            block << %Q[ <% end  %>]
            block << %Q[<% end  %>]

            erb_app block
            # body.should have_tag(:debug)
            body.should have_tag('div#comments')
            body.should have_tag('div#comments > p', 'Just plain HTML content')
            body.should have_tag('div#comments > fieldset > legend', 'Comments')
            body.should have_tag('div#comments > fieldset > p', 'Even more plain HTML content')
            body.should have_tag('div#comments > fieldset > textarea#field-comments', "test")
            body.should have_tag('div#comments > fieldset > span', "Some description")
            body.should have_tag('div#comments > p', 'Loads of plain HTML content')
            #
            body.should have_tag('div#comments > fieldset#form-details')
            body.should have_tag('div#comments > fieldset#form-details > legend', 'Details')
            body.should have_tag('div#comments > fieldset#form-details > input[@type=text]')

          end

          it "should buffer simple HTML content within nested Haml blocks" do
block =  %Q[
- tag( :div, :id => 'comments') do
  %p Just plain HTML content
  - tag(:fieldset) do
    = tag( :legend, 'Comments')
    %p Even more plain HTML content
    = tag( :textarea, 'test', :id => 'field-comments')
    = tag(:span, 'Some description')
  %p Loads of plain HTML content
  - tag(:fieldset, :id => 'form-details') do
    = tag(:legend, 'Details')
    = tag(:input, :type => :text, :value => 'City')
]

            haml_app block
            body.should have_tag('div#comments')
            body.should have_tag('div#comments > p', 'Just plain HTML content')
            body.should have_tag('div#comments > fieldset > legend', 'Comments')
            body.should have_tag('div#comments > fieldset > p', 'Even more plain HTML content')
            body.should have_tag('div#comments > fieldset > textarea#field-comments', "test")
            body.should have_tag('div#comments > fieldset > span', "Some description")
            body.should have_tag('div#comments > p', 'Loads of plain HTML content')
            #
            body.should have_tag('div#comments > fieldset#form-details')
            body.should have_tag('div#comments > fieldset#form-details > legend', 'Details')
            body.should have_tag('div#comments > fieldset#form-details > input[@type=text]')

          end

          it "should NOT prepend contents when both contents and block are present" do
block = %Q[
<% tag(:div, 'tag-content') do  %>
  <%= tag(:label, 'Comments:', :for => :comments)  %>
  <%= tag(:textarea,'This works', :id => :comments)  %>
<% end  %>]

            erb_app block
            body.should_not have_tag('div', /tag-content/)
            body.should have_tag('label[@for=comments]', 'Comments:')
            body.should have_tag('textarea[@id=comments]',"This works")

block = %Q[
- tag(:div, 'tag-content') do
  = tag(:label, 'Comments:', :for => :comments)
  = tag(:textarea,'This works', :id => :comments)
]
            haml_app block
            body.should_not have_tag('div', /tag-content/)
            body.should have_tag('label[@for=comments]', 'Comments:')
            body.should have_tag('textarea[@id=comments]',"This works")
          end

        end #/ with Blocks

        describe "as XHTML" do

          before(:each) do
            MyTestApp.tags_output_format_is_xhtml = true
          end
          %w( area base br col frame hr img input link meta param ).each do |t|

            it "should self-close <#{t} />" do
              erb_app "<%= tag(:#{t}) %>"
              body.should == "<#{t} />\n"

              haml_app "= tag(:#{t})"
              body.should == "<#{t} />\n"
            end

          end #/loop

        end #/ as XHTML

      end #/ #tag

    end #/ Helpers

  end #/ Tags

end #/ Sinatra


text:
namespace mscorlib
{
	namespace System
	{
		namespace Runtime
		{
			namespace InteropServices
			{

				//Public Methods
				//Get Set Properties Methods
				//	Get:WrappedObject
				mscorlib::System::Object  VariantWrapper::get_WrappedObject() const
				{
					MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Runtime.InteropServices", "VariantWrapper", 0, NULL, "get_WrappedObject", __native_object__, 0, NULL, NULL, NULL);
					return mscorlib::System::Object(__result__);
				}

			}
		}
	}
}


text:
FROM mcr.microsoft.com/vscode/devcontainers/miniconda:latest

COPY ci/*.txt /tmp/conda-tmp/
RUN sed -i -e "s/scipy==.*/scipy==1.5.3/" /tmp/conda-tmp/requirements.txt
RUN /opt/conda/bin/conda config --add channels conda-forge
RUN /opt/conda/bin/conda config --set channel_priority strict
RUN /opt/conda/bin/conda install --quiet --yes --file /tmp/conda-tmp/test_requirements.txt --file /tmp/conda-tmp/extra_requirements.txt --file /tmp/conda-tmp/requirements.txt --file /tmp/conda-tmp/linting_requirements.txt --file /tmp/conda-tmp/doc_requirements.txt


text:
package ru.org.linux.comment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import ru.org.linux.auth.CaptchaService;
import ru.org.linux.auth.FloodProtector;
import ru.org.linux.auth.IPBlockDao;
import ru.org.linux.auth.IPBlockInfo;
import ru.org.linux.edithistory.EditHistoryService;
import ru.org.linux.search.SearchQueueSender;
import ru.org.linux.spring.dao.MsgbaseDao;
import ru.org.linux.test.Users;
import ru.org.linux.topic.TopicDao;
import ru.org.linux.user.IgnoreListDao;
import ru.org.linux.user.User;
import ru.org.linux.user.UserDao;
import ru.org.linux.user.UserEventService;
import ru.org.linux.util.bbcode.LorCodeService;
import ru.org.linux.util.formatter.ToLorCodeFormatter;
import ru.org.linux.util.formatter.ToLorCodeTexFormatter;

import javax.servlet.http.HttpServletRequest;

import static org.mockito.Mockito.*;

/**
 * TODO: Тест отключен и не написан, потому что есть циклическая зависимость
 * LorCodeService -> TopicDao -> UserEventService -> LorCodeService
 * mock очень не любит такие зависимости. Тест должен быть дописан после упорядочивания зависимостей
 */

//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("unit-tests-context.xml")
public class CommentServiceTest {

  @Autowired
  CommentService commentService;

  @Autowired
  private CommentDao commentDao;

  @Autowired
  private TopicDao messageDao;

  @Autowired
  private UserDao userDao;

  @Autowired
  private ToLorCodeFormatter toLorCodeFormatter;

  @Autowired
  private ToLorCodeTexFormatter toLorCodeTexFormatter;

  @Autowired
  private CaptchaService captcha;

  @Autowired
  private CommentPrepareService commentPrepareService;

  @Autowired
  private FloodProtector floodProtector;

  @Autowired
  private IPBlockDao ipBlockDao;

  @Autowired
  private LorCodeService lorCodeService;

  @Autowired
  private UserEventService userEventService;

  @Autowired
  private MsgbaseDao msgbaseDao;

  @Autowired
  private SearchQueueSender searchQueueSender;

  @Autowired
  private IgnoreListDao ignoreListDao;

  @Autowired
  private EditHistoryService editHistoryService;

//  @Test
  public void checkPostData() throws Exception {
    CommentRequest commentRequest = new CommentRequest();
    User user = new User(Users.getUser1star());
    HttpServletRequest request = mock (HttpServletRequest.class);
    Errors errors = new BindException(commentRequest, "commentRequest");
    IPBlockInfo ipBlockInfo = new IPBlockInfo("127.0.0.1");

    commentService.checkPostData (commentRequest, user, ipBlockInfo, request, errors);
  }

}


text:
// Connection.cpp : Implementation of CConnection

/**************************
 **************************
 *****  Declarations  *****
 **************************
 **************************/

/********************
 *****  Global  *****
 ********************/

#include "VStdLib.h"
#include "VAccess.h"

/******************
 *****  Self  *****
 ******************/

#include "Connection.h"

/************************
 *****  Supporting  *****
 ************************/

#include "VExtractWS.h"
#include "VFormatSettings.h"
#include "VariantConverter.h"

/**********************
 *****  Standard  *****
 **********************/

DEFINE_V_WRAPPER_WITH_FACTORY(VConnection,CConnection,IConnection);

/*************************
 *************************
 *****  Definitions  *****
 *************************
 *************************/

/////////////////////////////////////////////////////////////////////////////
// CConnection

STDMETHODIMP CConnection::InterfaceSupportsErrorInfo(REFIID riid) {
    static const IID* arr[] = {
	&IID_IConnection
    };
    for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) {
	if (InlineIsEqualGUID(*arr[i],riid))
	    return S_OK;
    }
    return S_FALSE;
}

/////////////////////////////////////////////////////////////////////////////
// IConnection

STDMETHODIMP CConnection::get_IsConnected(BOOL *pVal) {
    *pVal = m_pImplementation->isConnected ();
    return S_OK;
}

STDMETHODIMP CConnection::get_FormatSettings(IFormatSettings **pVal) {
    *pVal= 0;
    return m_pImplementation->formatSettings()->QueryInterface (pVal);
}

STDMETHODIMP CConnection::Connect(BSTR hostname, long port) {
    VAccessString cHostname (hostname);

    if (m_pImplementation->connect (cHostname, (unsigned short)port))
	return S_OK;

    Error ("Connection::Connect: Failed", IID_IConnection);
    return E_FAIL;
}

STDMETHODIMP CConnection::Login(BSTR hostname, BSTR username, BSTR password, VARIANT command) {
    VAccessString cHostname (hostname);
    VAccessString cUsername (username);
    VAccessString cPassword (password);
    CVariantConverter cCommand (command);

    VAccessString sErrorMessage;
    VAccessString sCommand (cCommand.asStringElse ("/vision/bin/batchvision"));
    if (m_pImplementation->login (
	    sErrorMessage,
	    cHostname,
            cUsername,
            cPassword,
	    sCommand
	)
    ) return S_OK;

    // TODO: Check if the conversion to char* is necessary. Is there some reason for the 1280 below?
    char iErrorMessage[1280];
    sprintf (iErrorMessage, "Connection::Login: %s", sErrorMessage.content());
    Error (iErrorMessage, IID_IConnection);
    return E_FAIL;
}

STDMETHODIMP CConnection::Disconnect() {
    m_pImplementation->disconnect ();
    return S_OK;
}

STDMETHODIMP CConnection::Submit(
    BSTR	request,
    VARIANT	date,
    VARIANT	currency,
    VARIANT	replyBufferInitialSize,
    VARIANT	replyBufferSizeIncrement,
    BSTR*	reply
) {
//  Obtain optional argument values...
    CVariantConverter cDate		(date);
    CVariantConverter cCurrency		(currency);

    VAccessString cRequest (request);
    VAccessString iReplyBuffer;
    if (m_pImplementation->submit (
	    iReplyBuffer,
	    cRequest,
	    cDate		.asStringElse	(0),
	    cCurrency		.asStringElse	(0)
	)
    ) {
	*reply = iReplyBuffer.asBSTR ();
	return S_OK;
    }

    Error ("Connection::Submit: Failed", IID_IConnection);
    return E_FAIL;
}

STDMETHODIMP CConnection::Execute(BSTR request, VARIANT date, VARIANT currency) {
    VAccessString	      cRequest	(request);
    CVariantConverter cDate	(date);
    CVariantConverter cCurrency	(currency);

    if (m_pImplementation->execute (cRequest, cDate.asStringElse (0), cCurrency.asStringElse (0)))
	return S_OK;

    Error ("Connection::Execute: Failed", IID_IConnection);
    return E_FAIL;
}

STDMETHODIMP CConnection::Include(BSTR remoteFileName) {
    VAccessString cRemoteFileName (remoteFileName);
    if (m_pImplementation->include (cRemoteFileName))
	return S_OK;

    Error ("Connection::Include: Failed", IID_IConnection);
    return E_FAIL;
}

STDMETHODIMP CConnection::GetDouble(double *result, BSTR entityType, BSTR entity, BSTR item, VARIANT date, VARIANT currency, BOOL* pSuccessful) {
    VAccessString		cEntityType	(entityType);
    VAccessString		cEntity		(entity);
    VAccessString		cItem		(item);
    CVariantConverter	cDate		(date);
    CVariantConverter	cCurrency	(currency);

    double iResult;
    *pSuccessful = m_pImplementation->getValue (
	iResult, cEntityType, cEntity, cItem, cDate.asStringElse (0), cCurrency.asStringElse (0)
    );
    *result = *pSuccessful ? iResult : m_pImplementation->formatSettings()->doubleNaN();
    return S_OK;
}

STDMETHODIMP CConnection::GetLong(long *result, BSTR entityType, BSTR entity, BSTR item, VARIANT date, VARIANT currency, BOOL* pSuccessful) {
    VAccessString		cEntityType	(entityType);
    VAccessString		cEntity		(entity);
    VAccessString		cItem		(item);
    CVariantConverter	cDate		(date);
    CVariantConverter	cCurrency	(currency);

    int iResult;
    *pSuccessful = m_pImplementation->getValue (
	iResult, cEntityType, cEntity, cItem, cDate.asStringElse (0), cCurrency.asStringElse (0)
    );
    *result = *pSuccessful ? iResult : m_pImplementation->formatSettings ()->longNaN ();
    return S_OK;
}

STDMETHODIMP CConnection::GetString(BSTR *result, BSTR entityType, BSTR entity, BSTR item, VARIANT date, VARIANT currency, BOOL* pSuccessful) {
    VAccessString		cEntityType	(entityType);
    VAccessString		cEntity		(entity);
    VAccessString		cItem		(item);
    CVariantConverter	cDate		(date);
    CVariantConverter	cCurrency	(currency);

    VAccessString iResult;
    *pSuccessful = m_pImplementation->getValue (
	iResult, cEntityType, cEntity, cItem, cDate.asStringElse (0), cCurrency.asStringElse (0)
    );
    *result = *pSuccessful ? iResult.asBSTR (
	m_pImplementation->formatSettings()->returningUnicode ()
    ) : 0;
    return S_OK;
}

STDMETHODIMP CConnection::GetValue(VARIANT *result, BSTR entityType, BSTR entity, BSTR item, VARIANT date, VARIANT currency, BOOL* pSuccessful) {
    VAccessString		cEntityType	(entityType);
    VAccessString		cEntity		(entity);
    VAccessString		cItem		(item);
    CVariantConverter	cDate		(date);
    CVariantConverter	cCurrency	(currency);

    VDatum iResult;
    *pSuccessful = m_pImplementation->getValue (
	iResult, cEntityType, cEntity, cItem, cDate.asStringElse (0), cCurrency.asStringElse (0)
    );
    VariantInit (result);
    iResult.getValue (result, m_pImplementation->formatSettings()->returningUnicode ());
    return S_OK;
}

STDMETHODIMP CConnection::NewExtractWS(IExtractWS **ppExtractWS) {
    VReference<VExtractWS> pExtractWS (new VExtractWS (m_pImplementation));
    *ppExtractWS = 0;
    return pExtractWS ? pExtractWS->QueryInterface (
//	__uuidof (IExtractWS), reinterpret_cast<void**>(ppExtractWS)
	ppExtractWS
    ) : E_OUTOFMEMORY;
}

STDMETHODIMP CConnection::Rexec(BSTR hostname, BSTR username, BSTR password, VARIANT command) {
    return Login (hostname, username, password, command);
}

STDMETHODIMP CConnection::get_SessionNames(BSTR* sessionNames) {
    VAccessString cSessionNames;
    if (!m_pImplementation->getSessionNames(cSessionNames)) return E_FAIL;
    *sessionNames = cSessionNames.asBSTR();
    return S_OK;
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>[title] // [subtitle]</title>
  <meta name="description" content="[description]" />
  <meta name="keywords" content="[keywords]" />
  <meta name="robots" content="index, follow" />

  <meta property="og:title" content="[title] // [subtitle]"/>
  <meta property="og:url" content="http://ahsx.github.com/[repository]"/>
  <meta property="og:site_name" content="[title] // [subtitle]"/>
  <meta property="og:type" content="article"/>
  <meta property="og:image" content="[image]"/>

  <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="/statics/styles/vendors.css"/>
  <link rel="stylesheet" href="/statics/styles/app.css"/>

  <description
    title="[title]"
    subtitle="[subtitle]"
    github="http://github.com/ahsx/"
    demo="http://ahsx.github.com/[repository]/"
  >
  </description>

  <sprite></sprite>

                <icon label="icon-facebook"></icon>

                <icon label="icon-twitter"></icon>

                <icon label="icon-paperplane" ng-click="trackSocial('mailto', 'send')"></icon>

                <icon label="icon-link"></icon>

{{title}}

{{subtitle}}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
          quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
          consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
          cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
          proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        <form class="content">

            Global

            <dropdown
              title="Composite"
              model="options.composite"
            >
              <option value="normal">normal</option>
              <option value="multiply">multiply</option>
              <option value="screen">screen</option>
              <option value="overlay">overlay</option>
              <option value="darken">darken</option>
              <option value="lighten">lighten</option>
              <option value="color-dodge">color-dodge</option>
              <option value="color-burn">color-burn</option>
              <option value="hard-light">hard-light</option>
              <option value="soft-light">soft-light</option>
              <option value="difference">difference</option>
              <option value="exclusion">exclusion</option>
              <option value="hue">hue</option>
              <option value="saturation">saturation</option>
              <option value="color">color</option>
              <option value="luminosity">luminosity</option>
            </dropdown>

            <range
              min="1"
              max="30"
              value="15"
              title="Number of layers"
              model="options.nLayers">
            </range>

            <range
              min="2"
              max="30"
              value="8"
              title="Number of points"
              model="options.nPoints">
            </range>

            Stage

            <range
              min="10"
              max="100"
              value="100"
              title="Width (%)"
              model="options.stageWidth"
            ></range>

            <range
              id="stageHeight"
              min="10"
              max="100"
              value="100"
              title="Height (%)"
              model="options.stageHeight"
            ></range>

            Controls

            <fieldset>

              <button class="reset field" type="button">reset</button>
              <button
                href="{{saveURL}}"
                class="button save field"
                type="button"
                download="file.png"
                ng-click="saveCanvas()"
                >save</button>

            </fieldset>

        </form>

      <toolbar>
        <toolbaritem href="#options" title="Options" icon="icon-font-cog">
          <icon label="icon-cog"></icon>
        </toolbaritem>

        <toolbaritem href="#about" title="About" icon="icon-font-eye">
          <icon label="icon-eye"></icon>
        </toolbaritem>

      </toolbar>

{{title}} ///{{subtitle}}

            <canvas id="display"></canvas>


text:
#ifndef _SPHERE_3D_H_
#define _SPHERE_3D_H_

#include <Globals.h>

#include <glm/glm.hpp>

namespace core
{

//! Sphere
class ENGINE_PUBLIC_EXPORT sphere3d
{
public:

	// Constructors

	sphere3d();
	sphere3d(const glm::vec3& center, const float radius);
	sphere3d(const sphere3d& other);

	// operators

	sphere3d& operator=(const sphere3d& other);

	bool operator==(const sphere3d& other) const;
	bool operator!=(const sphere3d& other) const;

	// functions

	inline void set(const glm::vec3 center, const float radius);
	inline void set(const sphere3d& s);

	glm::vec3 Center;
	float Radius;
};

} // end namespace core

#endif


text:
class BuildEnvironment
  extend T::Sig

  sig { params(settings: Symbol).void }
  def initialize(*settings)
    @settings = Set.new(settings)
  end

  sig { params(args: T::Enumerable[Symbol]).returns(T.self_type) }
  def merge(*args)
    @settings.merge(*args)
    self
  end

  sig { params(o: Symbol).returns(T.self_type) }
  def <<(o)
    @settings << o
    self
  end

  sig { returns(T::Boolean) }
  def std?
    @settings.include? :std
  end

  # DSL for specifying build environment settings.
  module DSL
    extend T::Sig

    sig { params(settings: Symbol).returns(BuildEnvironment) }
    def env(*settings)
      @env ||= BuildEnvironment.new
      @env.merge(settings)
    end
  end

  KEYS = %w[
    CC CXX LD OBJC OBJCXX
    HOMEBREW_CC HOMEBREW_CXX
    CFLAGS CXXFLAGS CPPFLAGS LDFLAGS SDKROOT MAKEFLAGS
    CMAKE_PREFIX_PATH CMAKE_INCLUDE_PATH CMAKE_LIBRARY_PATH CMAKE_FRAMEWORK_PATH
    MACOSX_DEPLOYMENT_TARGET PKG_CONFIG_PATH PKG_CONFIG_LIBDIR
    HOMEBREW_DEBUG HOMEBREW_MAKE_JOBS HOMEBREW_VERBOSE
    HOMEBREW_SVN HOMEBREW_GIT
    HOMEBREW_SDKROOT
    MAKE GIT CPP
    ACLOCAL_PATH PATH CPATH
    LD_LIBRARY_PATH LD_RUN_PATH LD_PRELOAD LIBRARY_PATH
  ].freeze
  private_constant :KEYS

  sig { params(env: T.untyped).returns(T::Array[String]) }
  def self.keys(env)
    KEYS & env.keys
  end

  sig { params(env: T.untyped, f: IO).void }
  def self.dump(env, f = $stdout)
    keys = self.keys(env)
    keys -= %w[CC CXX OBJC OBJCXX] if env["CC"] == env["HOMEBREW_CC"]

    keys.each do |key|
      value = env.fetch(key)
      s = +"#{key}: #{value}"
      case key
      when "CC", "CXX", "LD"
        s << " => #{Pathname.new(value).realpath}" if File.symlink?(value)
      end
      s.freeze
      f.puts s
    end
  end
end


text:
"use strict";

exports.__esModule = true;
exports.default = void 0;

var _applyNativeMethods = _interopRequireDefault(require("../../modules/applyNativeMethods"));

var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));

var _View = _interopRequireDefault(require("../View"));

var _react = _interopRequireDefault(require("react"));

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

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

var createSvgCircle = function createSvgCircle(style) {
  return _react.default.createElement("circle", {
    cx: "16",
    cy: "16",
    fill: "none",
    r: "14",
    strokeWidth: "4",
    style: style
  });
};

var ActivityIndicator =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(ActivityIndicator, _React$Component);

  function ActivityIndicator() {
    return _React$Component.apply(this, arguments) || this;
  }

  var _proto = ActivityIndicator.prototype;

  _proto.render = function render() {
    var _this$props = this.props,
        _this$props$animating = _this$props.animating,
        animating = _this$props$animating === void 0 ? true : _this$props$animating,
        _this$props$color = _this$props.color,
        color = _this$props$color === void 0 ? '#1976D2' : _this$props$color,
        _this$props$hidesWhen = _this$props.hidesWhenStopped,
        hidesWhenStopped = _this$props$hidesWhen === void 0 ? true : _this$props$hidesWhen,
        _this$props$size = _this$props.size,
        size = _this$props$size === void 0 ? 'small' : _this$props$size,
        style = _this$props.style,
        other = _objectWithoutPropertiesLoose(_this$props, ["animating", "color", "hidesWhenStopped", "size", "style"]);

    var svg = _react.default.createElement("svg", {
      height: "100%",
      viewBox: "0 0 32 32",
      width: "100%"
    }, createSvgCircle({
      stroke: color,
      opacity: 0.2
    }), createSvgCircle({
      stroke: color,
      strokeDasharray: 80,
      strokeDashoffset: 60
    }));

    return _react.default.createElement(_View.default, _extends({}, other, {
      accessibilityRole: "progressbar",
      "aria-valuemax": "1",
      "aria-valuemin": "0",
      style: [styles.container, style]
    }), _react.default.createElement(_View.default, {
      children: svg,
      style: [typeof size === 'number' ? {
        height: size,
        width: size
      } : indicatorSizes[size], styles.animation, !animating && styles.animationPause, !animating && hidesWhenStopped && styles.hidesWhenStopped]
    }));
  };

  return ActivityIndicator;
}(_react.default.Component);

ActivityIndicator.displayName = 'ActivityIndicator';

var styles = _StyleSheet.default.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  hidesWhenStopped: {
    visibility: 'hidden'
  },
  animation: {
    animationDuration: '0.75s',
    animationKeyframes: [{
      '0%': {
        transform: [{
          rotate: '0deg'
        }]
      },
      '100%': {
        transform: [{
          rotate: '360deg'
        }]
      }
    }],
    animationTimingFunction: 'linear',
    animationIterationCount: 'infinite'
  },
  animationPause: {
    animationPlayState: 'paused'
  }
});

var indicatorSizes = _StyleSheet.default.create({
  small: {
    width: 20,
    height: 20
  },
  large: {
    width: 36,
    height: 36
  }
});

var _default = (0, _applyNativeMethods.default)(ActivityIndicator);

exports.default = _default;
module.exports = exports.default;


text:
//IBM_PROLOG_BEGIN_TAG

//IBM_PROLOG_END_TAG

#include <ServerI2CInstruction.H>
#include <OutputLite.H>
#include <stdio.h>
#include <errno.h>
#include <adal_iic.h>
#include <ecmdStructs.H>

// commented out because of conflict with iic_dd.h
//#include <linux/i2c-dev.h>
//#include <linux/i2c.h>
// copied from i2c-dev.h
#define I2C_RETRIES     0x0701  /* number of time a device address should
                                   be polled when not acknowledging */
#define I2C_TIMEOUT     0x0702  /* set timeout in units of 10 ms */
#define I2C_SLAVE	0x0703	/* Use this slave address */
#define I2C_SLAVE_FORCE 0x0706  /* Use this slave address even if in use by a driver */
#define I2C_TENBIT	0x0704	/* 0 for 7 bit addrs, != 0 for 10 bit */
#define I2C_FUNCS	0x0705	/* Get the adapter functionality mask */
#define I2C_RDWR	0x0707	/* Combined R/W transfer (one STOP only) */
// copied from i2c.h
#define I2C_FUNC_I2C                    0x00000001
#define I2C_FUNC_10BIT_ADDR             0x00000002

#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>

#ifdef SERVER_PRINT_PERF
#include <sys/time.h>
#endif

extern bool global_server_debug;

/* For this code device string is used to build file paths of valid i2c devices */
/* this include fsi i2c and native i2c devices */
/* we'll determine a valid device by what we find in the filesystem */

struct system_iic
{
    int fd;
    uint32_t slave_address;
    uint32_t slave_address_mask;
    uint8_t offset_width;
    uint64_t offset;
    uint32_t funcs;
};

system_iic * system_iic_open(const char * device, int flags)
{
    int fd = 0;
    fd = open(device, flags);
    if (fd < 0)
    {
        return NULL;
    }

    system_iic * ret = new system_iic;
    ret->fd = fd;
    return ret;
}

void system_iic_close(system_iic * handle)
{
    if (handle != NULL)
    {
        close(handle->fd);
        delete handle;
    }
}

uint32_t system_iic_reset(Handle * i_handle, int i_type)
{
    int rc = 0;

    if( i_type == ADAL_RESET_LIGHT || i_type == ADAL_RESET_FULL )
    {
        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;
    }

    // always attempt full reset even for light mode
    if( i_type == ADAL_RESET_FULL || i_type == ADAL_RESET_LIGHT)
    {
        // set diag_mode on
        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_MODE, 0x00000004 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_MODE, 0x00000004 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        // toggle clock line
        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET_SCL, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET_SCL, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_SET_SCL, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_SET_SCL, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        // stop signal
        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET_SCL, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET_SCL, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET_SDA, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_RESET_SDA, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_SET_SCL, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_SET_SCL, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_SET_SDA, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_SET_SDA, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;

        // set diag mode off
        rc = adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_MODE, 0x0 );
        if ( global_server_debug )
            printf("adal_iic_set_register( (adal_t *) i_handle, ADAL_IIC_REG_MODE, 0x0 )  rc(%d) errno(%d)\n", rc, errno);
        if ( rc < 0 )
            return rc;
    }
    else
    {
        return -1;
    }
    return rc;
}

uint32_t ServerI2CInstruction::iic_open(Handle ** handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
    char device[50];
    char errstr[200];
    int fd = 0;

    if(*handle != NULL)
      return rc;

    /* Open the device */
    if ((flags & INSTRUCTION_FLAG_DEVSTR) == 0) {
        //ERROR
        *handle = NULL;
        snprintf(errstr, 200, "ServerI2CInstruction::iic_open INSTRUCTION_FLAG_DEVSTR must be set\n");
        o_status.errorMessage.append(errstr);
        return SERVER_I2C_OPEN_FAIL;
    }

    if (iv_devicePaths.size() > 0)
    {
        iv_devicePaths.clear();
    }

    uint32_t deviceId = strtoul( deviceString.c_str(), NULL, 10 );

    snprintf(device, 50, "/dev/i2c-%d", ((deviceId * 100) + port));
    iv_devicePaths.push_back(device);
    snprintf(device, 50, "/dev/i2cfsi%d.%02d", deviceId, port);
    iv_devicePaths.push_back(device);
    iv_adalFsiDevice = 1;

    for( iv_deviceIdx=0; iv_deviceIdx < iv_devicePaths.size(); iv_deviceIdx++ )
    {
        fd = open(iv_devicePaths[iv_deviceIdx].c_str(), O_RDONLY);
        if (fd != -1)
        {
            close(fd);
            break;
        }
        close(fd);
    }

    if ( iv_deviceIdx >= iv_devicePaths.size() )
    {
        *handle = NULL;
        for( iv_deviceIdx=0; iv_deviceIdx < iv_devicePaths.size(); iv_deviceIdx++ )
        {
            snprintf(errstr, 200, "ServerI2CInstruction::iic_open invalid device open attempt %s\n", iv_devicePaths[iv_deviceIdx].c_str());
            o_status.errorMessage.append(errstr);
        }
        return SERVER_I2C_OPEN_FAIL;
    }

    // iv_deviceIdx contains the index into iv_devicePaths that points to a file that exists and we can open
    errno = 0;

    if (flags & INSTRUCTION_FLAG_SERVER_DEBUG) {
        if ( iv_deviceIdx == iv_adalFsiDevice )
            snprintf(errstr, 200, "SERVER_DEBUG : adal_iic_open(%s, O_RDWR | O_SYNC)\n", iv_devicePaths[iv_deviceIdx].c_str());
        else
            snprintf(errstr, 200, "SERVER_DEBUG : system_iic_open(%s, O_RDWR | O_SYNC)\n", iv_devicePaths[iv_deviceIdx].c_str());
        o_status.errorMessage.append(errstr);
    }

#ifdef TESTING
    if ( iv_deviceIdx == iv_adalFsiDevice )
        TEST_PRINT("*handle = adal_iic_open(%s, O_RDWR | O_SYNC);\n", iv_devicePaths[iv_deviceIdx].c_str());
    else
        TEST_PRINT("*handle = system_iic_open(%s, O_RDWR | O_SYNC);\n", iv_devicePaths[iv_deviceIdx].c_str());
    *handle = (Handle *) 0x1;
#else
    if ( iv_deviceIdx == iv_adalFsiDevice )
        *handle = (Handle *) adal_iic_open(iv_devicePaths[iv_deviceIdx].c_str(), O_RDWR | O_SYNC);
    else
        *handle = (Handle *) system_iic_open(iv_devicePaths[iv_deviceIdx].c_str(), O_RDWR | O_SYNC);
#endif
    if (flags & INSTRUCTION_FLAG_SERVER_DEBUG) {
        if ( iv_deviceIdx == iv_adalFsiDevice )
            snprintf(errstr, 200, "SERVER_DEBUG : adal_iic_open() *handle = %p\n", *handle);
        else
            snprintf(errstr, 200, "SERVER_DEBUG : system_iic_open() *handle = %p\n", *handle);
        o_status.errorMessage.append(errstr);
    }

    if ( iv_deviceIdx != iv_adalFsiDevice )
    {
        // Test if I2C_FUNC_I2C is available
        uint32_t funcs = 0;
        system_iic * l_handle = (system_iic *) *handle;
        rc = ioctl(l_handle->fd, I2C_FUNCS, &funcs);
        l_handle->funcs = funcs;
        if ((l_handle->funcs & I2C_FUNC_I2C) == 0)
        {
            snprintf(errstr, 200, "ServerI2CInstruction::iic_open I2C_FUNC_I2C not supported, funcs = %08X\n", l_handle->funcs);
            o_status.errorMessage.append(errstr);
            system_iic_close(l_handle);
            *handle = NULL;
            return SERVER_I2C_OPEN_FAIL;
        }
        else
        {
            if (flags & INSTRUCTION_FLAG_SERVER_DEBUG) {
                snprintf(errstr, 200, "SERVER_DEBUG : I2C_FUNCS = %08X\n", l_handle->funcs);
                o_status.errorMessage.append(errstr);
            }
        }
    }

    if (*handle == NULL) {
        snprintf(errstr, 200, "I2CInstruction::execute Problem opening I2C device %s : errno %d\n", iv_devicePaths[iv_deviceIdx].c_str(), errno);
        o_status.errorMessage.append(errstr);
        rc = o_status.rc = SERVER_I2C_OPEN_FAIL;
        return rc;
    }

    return rc;
}

void ServerI2CInstruction::iic_ffdc(Handle ** handle, InstructionStatus & o_status)
{
    // adal_iic_ffdc_extract
    //  append to o_status.errorMessage
    // adal_iic_ffdc_unlock

    uint32_t rc = iic_close(*handle);
    *handle = NULL;
    if (rc) o_status.rc = SERVER_I2C_CLOSE_FAIL;
}

uint32_t ServerI2CInstruction::iic_close(Handle * handle)
{
    uint32_t rc = 0;
    // close iic device
#ifdef TESTING
    if ( iv_deviceIdx == iv_adalFsiDevice )
        TEST_PRINT("adal_iic_close()\n");
    else
        TEST_PRINT("system_iic_close()\n");
#else
    if ( iv_deviceIdx == iv_adalFsiDevice )
        rc = adal_iic_close((adal_t *) handle);
    else
        system_iic_close((system_iic *) handle);
#endif
    return rc;
}

uint32_t ServerI2CInstruction::iic_config_speed(Handle * i_handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
#if 0
    int cfg_val = 0;
    char errstr[200];

    switch (busSpeed)
    {
        case 100:
            cfg_val = ADAL_IIC_VAL_100KHZ;
            break;
        case 400:
            cfg_val = ADAL_IIC_VAL_400KHZ;
            break;
        default:
            snprintf(errstr, 200, "ServerI2CInstruction::iic_config_speed Bus speed %d is not known\n", busSpeed);
            o_status.errorMessage.append(errstr);
            rc = SERVER_IIC_SPEED_INVALID;
            break;
    }

    if (rc == 0)
    {
#ifdef TESTING
        TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_SPEED, %x, 0);\n", cfg_val);
#else
        rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_SPEED, &cfg_val, 0);
#endif
    }
#endif
    return rc;
}

uint32_t ServerI2CInstruction::iic_config_slave_address(Handle * i_handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
    if ( iv_deviceIdx == iv_adalFsiDevice )
#ifdef TESTING
        TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_DEV_ADDR, %x, 0);\n", slaveAddress);
#else
        rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_DEV_ADDR, &slaveAddress, 0);
#endif
    else
    {
#ifdef TESTING
        TESTPRINT("ioctl(handle->fd, I2C_TENBIT, 1) if tenbit supported\n");
        TESTPRINT("ioctl(handle->fd, I2C_SLAVE, handle->slave_address)\n");
#else
        errno = 0;
        system_iic * handle = (system_iic *) i_handle;
        if ( (handle->funcs & I2C_FUNC_10BIT_ADDR) == I2C_FUNC_10BIT_ADDR )
        {
            rc = ioctl(handle->fd, I2C_TENBIT, 1);
            if ( rc ) return rc;
            handle->slave_address = slaveAddress;
            handle->slave_address_mask = 0x3FF;
        }
        else
        {
            handle->slave_address = slaveAddress >> 1; // right shift to a 7-bit address
            handle->slave_address_mask = 0x7F;
        }
        if ( serverI2cFlags & ECMD_I2C_FLAGS_I2C_SLAVE_FORCE )
            rc = ioctl(handle->fd, I2C_SLAVE_FORCE, handle->slave_address & handle->slave_address_mask);
        else
            rc = ioctl(handle->fd, I2C_SLAVE, handle->slave_address & handle->slave_address_mask);
#endif
    }
    return rc;
}

uint32_t ServerI2CInstruction::iic_config_device_width(Handle * i_handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
    int cfg_val = 0;
    char errstr[200];

    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
        switch (offsetFieldSize)
        {
            case 0:
                cfg_val = ADAL_IIC_VAL_0BYTE;
                break;
            case 1:
                cfg_val = ADAL_IIC_VAL_1BYTE;
                break;
            case 2:
                cfg_val = ADAL_IIC_VAL_2BYTE;
                break;
            case 3:
                cfg_val = ADAL_IIC_VAL_3BYTE;
                break;
            case 4:
                cfg_val = ADAL_IIC_VAL_4BYTE;
                break;
            default:
                snprintf(errstr, 200, "ServerI2CInstruction::iic_config_device_width Invalid offsetFieldSize: %d is not supported\n", offsetFieldSize);
                o_status.errorMessage.append(errstr);
                rc = SERVER_IIC_INVALID_OFFSET_SIZE;
        }

        if (rc == 0)
        {
#ifdef TESTING
            TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_DEV_WIDTH, %x, 0);\n", cfg_val);
#else
            rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_DEV_WIDTH, &cfg_val, 0);
#endif
        }
    }
    else
    {
        system_iic * handle = (system_iic *) i_handle;
        handle->offset_width = offsetFieldSize;
        if (handle->offset_width > 8)
        {
            char errstr[200];
            snprintf(errstr, 200, "ServerI2CInstruction::iic_config_device_width Invalid offsetFieldSize: %d is not supported\n", handle->offset_width);
            o_status.errorMessage.append(errstr);
            rc = SERVER_IIC_INVALID_OFFSET_SIZE;
        }
    }

    return rc;
}

uint32_t ServerI2CInstruction::iic_config_device_offset(Handle * i_handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
#ifdef TESTING
        TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_OFFSET, %x, 0);\n", offset);
#else
        rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_OFFSET, &offset, 0);
#endif
    }
    else
    {
        system_iic * handle = (system_iic *) i_handle;
        if (offsetFieldSize > 4)
        {
            handle->offset = address;
        }
        else
        {
            handle->offset = offset;
        }
    }
    return rc;
}

uint32_t ServerI2CInstruction::iic_config_device_timeout(Handle * i_handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
#ifdef TESTING
        TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_TIMEOUT, %x, 0);\n", msDelay);
#else
        rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_TIMEOUT, &msDelay, 0);
#endif
    }
    else
    {
#ifdef TESTING
        TESTPRINT("ioctl(handle->fd, I2C_TIMEOUT, %d)\n", msDelay/10);
#else
        errno = 0;
        system_iic * handle = (system_iic *) i_handle;
        // value to I2C_TIMEOUT is in 10ms units
        rc = ioctl( handle->fd, I2C_TIMEOUT, msDelay/10 );
#endif
    }
    return rc;
}

uint32_t ServerI2CInstruction::iic_config_device_retries(Handle * i_handle, InstructionStatus & o_status)
{
    uint32_t rc = 0;
    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
#ifdef TESTING
        TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_REDO_POL, %x, 0);\n", numRedos);
#else
        rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_REDO_POL, &numRedos, 0);
#endif
    }
    else
    {
#ifdef TESTING
        TESTPRINT("ioctl(handle->fd, I2C_RETRIES, %d)\n", numRedos);
#else
        errno = 0;
        system_iic * handle = (system_iic *) i_handle;
        rc = ioctl( handle->fd, I2C_RETRIES, numRedos );
#endif
    }
    return rc;
}

ssize_t ServerI2CInstruction::iic_read(Handle * i_handle, ecmdDataBufferBase & o_data, InstructionStatus & o_status)
{
    char errstr[200];
#ifdef SERVER_PRINT_PERF
    struct timeval start_time;
    struct timeval end_time;
#endif

    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
        ssize_t len = length % 8 ? (length / 8) + 1 : length / 8;

        uint8_t * buffer = new uint8_t[len + 4];

#ifdef SERVER_PRINT_PERF
        printf("bytes: %d, msDelay: %d, numRedos: %d\n", len, msDelay, numRedos);
#endif

#ifdef SERVER_PRINT_PERF
        gettimeofday(&start_time, NULL);
#endif
#ifdef TESTING
        TESTPRINT("len = adal_iic_read((adal_t *) i_handle, buffer, len);\n");
#else
        len = adal_iic_read((adal_t *) i_handle, buffer, len);
#endif
#ifdef SERVER_PRINT_PERF
        gettimeofday(&end_time, NULL);
        int perf_run_time = (end_time.tv_sec - start_time.tv_sec) * 1000 + ((end_time.tv_usec - start_time.tv_usec) / 1000);
        printf("time: %d, rc %d\n", perf_run_time, len);
#endif

#if 0
        for (int i = 0; i < (len + 4); i++)
        {
            printf("%02X ", (uint32_t) buffer[i]);
        }
        printf ("\n");
#endif

        uint32_t rc_ecmd = o_data.insert(buffer, 0, length);
        if (rc_ecmd)
        {
            printf("insert error %d\n", rc_ecmd);
        }
        delete [] buffer;

        return len;
    }
    else
    {
        system_iic * handle = (system_iic *) i_handle;
        uint32_t bytes = length % 8 ? (length / 8) + 1 : length / 8;

        uint32_t messages = 0;
        // check if we need to write address to the bus before the write
        if (handle->offset_width > 0)
        {
            messages = 1;
        }

        const uint32_t msgMax = (i2cFlags & INSTRUCTION_I2C_FLAG_MSG_SIZE_MASK) == 0 ? 8192 : ((i2cFlags & INSTRUCTION_I2C_FLAG_MSG_SIZE_MASK) >> INSTRUCITON_I2C_FLAG_MSG_SIZE_SHIFT);
        messages += (bytes / (msgMax)) + ((bytes % msgMax) > 0 ? 1 : 0);

        i2c_rdwr_ioctl_data * rdwr_data = new i2c_rdwr_ioctl_data;
        rdwr_data->msgs = new i2c_msg[messages];
        rdwr_data->nmsgs = messages;

        uint32_t msg_offset = 0;

        if (messages > 1)
        {
            // set up write message
            rdwr_data->msgs[msg_offset].addr = handle->slave_address;
            rdwr_data->msgs[msg_offset].flags = 0;
            rdwr_data->msgs[msg_offset].len = handle->offset_width;
            rdwr_data->msgs[msg_offset].buf = new uint8_t[rdwr_data->msgs[msg_offset].len];
            // copy in offset data in bytes
            for (uint8_t buf_offset = 0; buf_offset < handle->offset_width; buf_offset++)
            {
                rdwr_data->msgs[msg_offset].buf[buf_offset] =
                    (handle->offset >> ((handle->offset_width - buf_offset - 1) * 8)) & 0xFF;
            }

            msg_offset++;
        }

        // set up read message
        for( uint32_t idx=0; (msgMax*idx) < bytes && msg_offset < messages; idx++ )
        {
            // set up read message
            rdwr_data->msgs[msg_offset].addr = handle->slave_address;
            rdwr_data->msgs[msg_offset].flags = I2C_M_RD;
            uint32_t tmpbytes = ((msgMax*(idx+1)) > bytes) ? bytes - (msgMax*idx) : msgMax;
            rdwr_data->msgs[msg_offset].len = tmpbytes;
            rdwr_data->msgs[msg_offset].buf = new uint8_t[tmpbytes];

            msg_offset++;
        }

        if (flags & INSTRUCTION_FLAG_SERVER_DEBUG)
        {
            snprintf(errstr, 200, "SERVER_DEBUG : rc = ioctl( handle->fd, I2C_RDWR, rdwr_data)\n");
            o_status.errorMessage.append(errstr);
            for( uint32_t msgidx=0; msgidx < messages; msgidx++)
            {
                snprintf(errstr, 200, "SERVER_DEBUG : rdwr_data[%d] - addr(0x%X) flag(%X) bytes(%d) buf...\n", msgidx, rdwr_data->msgs[msgidx].addr, rdwr_data->msgs[msgidx].flags, rdwr_data->msgs[msgidx].len);
                o_status.errorMessage.append(errstr);
            }
        }
        int32_t rc = 0;
#ifdef TESTING
        TESTPRINT("rc = ioctl(handle->fd, I2C_RDWR, rdwr_data);\n");
#else
        rc = ioctl(handle->fd, I2C_RDWR, rdwr_data);
#endif

        if (flags & INSTRUCTION_FLAG_SERVER_DEBUG)
        {
            snprintf(errstr, 200, "SERVER_DEBUG : rc = %d, errno = %d\n", rc, errno);
            o_status.errorMessage.append(errstr);
        }

        if (rc >= 0)
        {
            rc = 0;
            uint32_t byteidx = 0;
            for ( msg_offset = 0; msg_offset < messages; msg_offset++ )
            {
                if ( rdwr_data->msgs[msg_offset].flags != 0 )
                {
                    // copy out data
                    uint32_t tmplength = ((msgMax*(byteidx+1)) < bytes) ? msgMax*8 : length - (msgMax*byteidx*8);
                    o_data.insert(rdwr_data->msgs[msg_offset].buf, (byteidx*msgMax*8), tmplength);

                    rc += tmplength % 8 ? (tmplength / 8) + 1 : tmplength / 8;
                    byteidx++;
                }
            }
            rc = bytes;
        }
        else
        {
            //perror("i2c read");
        }

        for (msg_offset = 0; msg_offset < messages; msg_offset++)
        {
            delete [] rdwr_data->msgs[msg_offset].buf;
        }
        delete [] rdwr_data->msgs;
        delete rdwr_data;

        return rc;
    }
}

ssize_t ServerI2CInstruction::iic_write(Handle * i_handle, InstructionStatus & o_status)
{
    char errstr[200];
#ifdef SERVER_PRINT_PERF
    struct timeval start_time;
    struct timeval end_time;
#endif

    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
        ssize_t len = length % 8 ? (length / 8) + 1 : length / 8;

        uint8_t * buffer = new uint8_t[len + 4];
        memset(buffer, 0x00, len + 4);
        data.extract(buffer, 0, length);

#ifdef SERVER_PRINT_PERF
        gettimeofday(&start_time, NULL);
#endif
#ifdef TESTING
        TESTPRINT("len = adal_iic_write((adal_t *) i_handle, buffer), len);\n");
#else
        len = adal_iic_write((adal_t *) i_handle, buffer, len);
#endif
#ifdef SERVER_PRINT_PERF
        gettimeofday(&end_time, NULL);
        int perf_run_time = (end_time.tv_sec - start_time.tv_sec) * 1000 + ((end_time.tv_usec - start_time.tv_usec) / 1000);
        printf("time: %d, rc %d\n", perf_run_time, len);
#endif
        delete [] buffer;

        return len;
    }
    else
    {
        system_iic * handle = (system_iic *) i_handle;
        uint32_t bytes = length % 8 ? (length / 8) + 1 : length / 8;

        uint32_t messages = 1;

        i2c_rdwr_ioctl_data * rdwr_data = new i2c_rdwr_ioctl_data;
        rdwr_data->msgs = new i2c_msg[messages];
        rdwr_data->nmsgs = messages;

        uint32_t msg_offset = 0;

        // set up write message
        rdwr_data->msgs[msg_offset].addr = handle->slave_address;
        rdwr_data->msgs[msg_offset].flags = 0;
        rdwr_data->msgs[msg_offset].len = handle->offset_width + bytes;
        rdwr_data->msgs[msg_offset].buf = new uint8_t[rdwr_data->msgs[msg_offset].len];
        // copy in offset data in bytes
        for (uint8_t buf_offset = 0; buf_offset < handle->offset_width; buf_offset++)
        {
            rdwr_data->msgs[msg_offset].buf[buf_offset] =
                (handle->offset >> ((handle->offset_width - buf_offset - 1) * 8)) & 0xFF;
        }
        // copy in message data
        data.extract(rdwr_data->msgs[msg_offset].buf + handle->offset_width, 0, length);

        if (flags & INSTRUCTION_FLAG_SERVER_DEBUG)
        {
            snprintf(errstr, 200, "SERVER_DEBUG : rc = ioctl( handle->fd, I2C_RDWR, rdwr_data)\n");
            o_status.errorMessage.append(errstr);
            for( uint32_t idx=0; idx < messages; idx++)
            {
                snprintf(errstr, 200, "SERVER_DEBUG : rdwr_data[%d] - addr(0x%X) flag(%X) bytes(%d) buf...\n", idx, rdwr_data->msgs[idx].addr, rdwr_data->msgs[idx].flags, rdwr_data->msgs[idx].len);
                o_status.errorMessage.append(errstr);
            }
        }
        int32_t rc = 0;
#ifdef TESTING
        TESTPRINT("rc = ioctl(handle->fd, I2C_RDWR, rdwr_data);\n");
#else
        rc = ioctl(handle->fd, I2C_RDWR, rdwr_data);
#endif

        if (flags & INSTRUCTION_FLAG_SERVER_DEBUG)
        {
            snprintf(errstr, 200, "SERVER_DEBUG : rc = %d, errno = %d\n", rc, errno);
            o_status.errorMessage.append(errstr);
        }

        if (rc >= 0)
        {
           rc = bytes;
        }

        for (msg_offset = 0; msg_offset < messages; msg_offset++)
        {
            delete [] rdwr_data->msgs[msg_offset].buf;
        }
        delete [] rdwr_data->msgs;
        delete rdwr_data;

        return rc;
    }
}

uint32_t ServerI2CInstruction::iic_reset(Handle * i_handle, ResetType i_type)
{
#ifdef SERVER_PRINT_PERF
    struct timeval start_time;
    struct timeval end_time;
#endif

    uint32_t rc = 0;
    int l_type = 0;
    if (i_type == IIC_RESET_LIGHT)
    {
        l_type = ADAL_RESET_LIGHT;
    }
    else if (i_type == IIC_RESET_FULL)
    {
        l_type = ADAL_RESET_FULL;
    }

    if ( iv_deviceIdx == iv_adalFsiDevice )
    {
        int timeout = 60 * 1000;
#ifdef TESTING
        TESTPRINT("rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_TIMEOUT, %x, 0);\n", timeout);
#else
        ssize_t rc = adal_iic_config((adal_t *) i_handle, ADAL_CONFIG_WRITE, ADAL_IIC_CFG_TIMEOUT, &timeout, 0);
        if (rc)
        {
            return rc;
        }
#endif

#ifdef SERVER_PRINT_PERF
        gettimeofday(&start_time, NULL);
#endif
#ifdef TESTING
        TESTPRINT("len = adal_iic_reset((adal_t *) i_handle, l_type));\n");
#else
        rc = adal_iic_reset((adal_t *) i_handle, l_type);
#endif
#ifdef SERVER_PRINT_PERF
        gettimeofday(&end_time, NULL);
        int perf_run_time = (end_time.tv_sec - start_time.tv_sec) * 1000 + ((end_time.tv_usec - start_time.tv_usec) / 1000);
        printf("time: %d, rc %d\n", perf_run_time, len);
#endif
        return rc;
    }
    else
    {

#ifdef TESTING
        TESTPRINT("rc = system_iic_reset((adal_t *) handle, l_type);\n");
#else
        // disabling calling system_iic_reset
        //rc = system_iic_reset( i_handle, l_type );
#endif

        if (rc < 0 && l_type == ADAL_RESET_FULL)
        {
            rc = SERVER_I2C_RESET_FULL_FAIL;
        }
        else if (rc < 0 && l_type == ADAL_RESET_LIGHT)
        {
            rc = SERVER_I2C_RESET_LIGHT_FAIL;
        }

        return rc;
    }
}