text:
package org.unitils.inject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import org.unitils.UnitilsJUnit4;
import org.unitils.core.ConfigurationLoader;
import org.unitils.core.UnitilsException;
import org.unitils.inject.annotation.InjectIntoStaticByType;
import org.unitils.inject.util.PropertyAccess;

import java.util.Properties;

/**
 * @author Filip Neven
 * @author Tim Ducheyne
 */
public class InjectModuleInjectIntoStaticByTypeExceptionsTest extends UnitilsJUnit4 {

    private static final Log logger = LogFactory.getLog(InjectModuleInjectIntoStaticByTypeExceptionsTest.class);

    private TestInjectIntoStaticByType_NoPropertyOfType testInjectIntoStaticByType_noPropertyOfType = new TestInjectIntoStaticByType_NoPropertyOfType();
    private TestInjectIntoStaticByType_MoreThanOneFieldOfType testInjectIntoStaticByType_moreThanOneFieldOfType = new TestInjectIntoStaticByType_MoreThanOneFieldOfType();
    private TestInjectIntoStaticByType_MoreThanOneSetterOfType testInjectIntoStaticByType_moreThanOneSetterOfType = new TestInjectIntoStaticByType_MoreThanOneSetterOfType();
    private TestInjectIntoStaticByType_MoreThanOneFieldOfSuperType testInjectIntoStaticByType_moreThanOneFieldOfSuperType = new TestInjectIntoStaticByType_MoreThanOneFieldOfSuperType();
    private TestInjectIntoStaticByType_MoreThanOneSetterOfSuperType testInjectIntoStaticByType_moreThanOneSetterOfSuperType = new TestInjectIntoStaticByType_MoreThanOneSetterOfSuperType();

    private InjectModule injectModule = new InjectModule();

    @Before
    public void setUp() throws Exception {
        Properties configuration = new ConfigurationLoader().loadConfiguration();
        injectModule.init(configuration);
    }

    @Test
    public void testInjectIntoStaticByType_noPropertyOfType() {
        try {
            injectModule.injectObjects(testInjectIntoStaticByType_noPropertyOfType);
            fail("UnitilsException should have been thrown");
        } catch (UnitilsException e) {
            // Expected flow
            logger.debug(this, e);
        }
    }

    @Test
    public void testInjectIntoStaticByType_moreThanOneFieldOfType() {
        try {
            injectModule.injectObjects(testInjectIntoStaticByType_moreThanOneFieldOfType);
            fail("UnitilsException should have been thrown");
        } catch (UnitilsException e) {
            // Expected flow
            logger.debug(this, e);
        }
    }

    @Test
    public void testInjectIntoStaticByType_moreThanOneSetterOfType() {
        try {
            injectModule.injectObjects(testInjectIntoStaticByType_moreThanOneSetterOfType);
            fail("UnitilsException should have been thrown");
        } catch (UnitilsException e) {
            // Expected flow
            logger.debug(this, e);
        }
    }

    @Test
    public void testInjectIntoStaticByType_moreThanOneFieldOfSuperType() {
        try {
            injectModule.injectObjects(testInjectIntoStaticByType_moreThanOneFieldOfSuperType);
            fail("UnitilsException should have been thrown");
        } catch (UnitilsException e) {
            // Expected flow
            logger.debug(this, e);
        }
    }

    @Test
    public void testInjectIntoStaticByType_moreThanOneSetterOfSuperType() {
        try {
            injectModule.injectObjects(testInjectIntoStaticByType_moreThanOneSetterOfSuperType);
            fail("UnitilsException should have been thrown");
        } catch (UnitilsException e) {
            // Expected flow
            logger.debug(this, e);
        }
    }

    @SuppressWarnings("unused")
    public class TestInjectIntoStaticByType_NoPropertyOfType {

        @InjectIntoStaticByType(target = InjectOn_NoPropertyOfType.class)
        private ToInject toInject;
    }

    @SuppressWarnings("unused")
    public class TestInjectIntoStaticByType_MoreThanOneFieldOfType {

        @InjectIntoStaticByType(target = InjectOn_MoreThanOneFieldOfType.class)
        private ToInject toInject;
    }

    @SuppressWarnings("unused")
    public class TestInjectIntoStaticByType_MoreThanOneSetterOfType {

        @InjectIntoStaticByType(target = InjectOn_MoreThanOneSetterOfType.class, propertyAccess = PropertyAccess.SETTER)
        private ToInject toInject;
    }

    @SuppressWarnings("unused")
    public class TestInjectIntoStaticByType_MoreThanOneFieldOfSuperType {

        @InjectIntoStaticByType(target = InjectOn_MoreThanOneFieldOfSuperType.class)
        private ToInject toInject;
    }

    @SuppressWarnings("unused")
    public class TestInjectIntoStaticByType_MoreThanOneSetterOfSuperType {

        @InjectIntoStaticByType(target = InjectOn_MoreThanOneSetterOfSuperType.class, propertyAccess = PropertyAccess.SETTER)
        private ToInject toInject;
    }

    public class ToInjectSuper {
    }

    /**
     * Object to inject
     */
    public class ToInject extends ToInjectSuper {
    }

    /**
     * Object to inject into
     */
    public class InjectOn {
    }

    public static class InjectOn_NoPropertyOfType {
    }

    @SuppressWarnings("unused")
    public static class InjectOn_MoreThanOneFieldOfType {

        private static ToInject toInject1;

        private static ToInject toInject2;

    }

    public static class InjectOn_MoreThanOneSetterOfType {

        public static void setToInject1(ToInject toInject1) {
        }

        public static void setToInject2(ToInject toInject2) {
        }

    }

    @SuppressWarnings("unused")
    public static class InjectOn_MoreThanOneFieldOfSuperType {

        private static ToInjectSuper toInject1;

        private static ToInjectSuper toInject2;

    }

    public static class InjectOn_MoreThanOneSetterOfSuperType {

        public static void setToInject1(ToInjectSuper toInject1) {
        }

        public static void setToInject2(ToInjectSuper toInject2) {
        }

    }
}


text:
{-# LANGUAGE CPP #-}

#define INSTANCES_USUAL Eq, Ord, Enum, Show

module Data.VCD.Types where

import Prelude

import Data.ByteString.Char8 (ByteString)
import Data.Word

-- * Declaration

data VarType
    = Event | Integer | Parameter | Real | Reg
    | Supply0 | Supply1 | Time
    | Tri | TriAnd | TriOr | TriReg | Tri0 | Tri1
    | WAnd | Wire | WOr
    deriving (INSTANCES_USUAL)

type IdCode = ByteString
type Identifier = ByteString
type Reference = (Identifier, Maybe (Either (Int, Int) Int))

data ScopeType = Begin | Fork | Function | Module | Task
    deriving (INSTANCES_USUAL)

data TextType = Comment | Date | Version
    deriving (INSTANCES_USUAL)

data TimeUnit = S | MS | US | NS | PS | FS
    deriving (INSTANCES_USUAL)

data Declaration
    = DVar VarType Int IdCode Reference
    | DScope ScopeType Identifier
    | DUpScope
    | DText TextType ByteString
    | DTimeScale Int TimeUnit
    deriving (Show)

-- * Simulation

data Four = O | I | Z | X
    deriving (INSTANCES_USUAL) -- TODO: Unbox?

data Value
    = VScalar Four
    -- TODO: use Vector?
    | VVector [Four] -- ^ LSB-first
    | VReal Double
    deriving (Show)

data Change = Change IdCode Value
    deriving (Show)

type Time = Word64
type Duration = Word64

data DumpType = All | Off | On | Vars
    deriving (INSTANCES_USUAL)

data Simulation
    = SChange Change
    | STime Time
    | SDump DumpType [Change]
    | SComment ByteString
    deriving (Show)

redpajama_set_name: RedPajamaGithub


text:
One of the hardest parts about converting from Troopmaster to
Scoutbook for a Scout Troop is the transfering of data.  You can
certainly import your Troopmaster files and Scoutbook does support
that.  It seems that you have far greater control over your data (and
I think it's also faster) if you import the data in the csv format
expected by Scoutbook.

Scoutbook provides a primer for doing this import, including sample
files here:
https://www.scoutbook.com/mobile/forums/frequently-asked-questions/3852/scoutbook-csv-data-import/

The scripts in this repository represent many hours of trial and error
on getting data out of Troopmaster and massaging it into the right
format for Scoutbook.  Due to the way that Troopmaster can be
"customized" some of the choices made by the scripts may not work
properly for your unit.  You should treat this as a starting point and
adjust as necessary.  I wish I could provide a turnkey solution but
there are just too many different combinations to make that feesible.

# Exporting of Data From Troopmaster

Here are the steps necessary to export your data from Troopmaster:

File -> Export -> ASCII Delimited...

Scout.txt file:
    Check Include field names as first line of export
    Format: Comma delimited
    Select area: Scout Data
    Date Format: MM/DD/YYYY
    Members: All Scouts
    Click "Add All>>"

    Export

Adult.txt file:
    Check Include field names as first line of export
    Format: Comma delimited
    Select area: Adult Data
    Date Format: MM/DD/YYYY
    Members: All Adults
    Click "Add All>>"

    Export

Reports:
    Reports -> Activities -> Individual Activities...

    Display Level: All Levels
    Display Types: All Activity Types

    Select All Activities

    Check: Include scout attendance
    Un-Check: Include adult attendance

    Select

    Save as Text report

# Data Not Exported

You should utilize ScoutNET for all completed advancement and training
records.  If you aren't using Internet Advancement, now is an
excellent time to start.

# Scripts

scout.py
    Parse the exported scout data file into something appropriate for Scoutbook.

adult.py
    Parse the exported adult data file into something appropriate for Scoutbook.

parse_activity_report.py
    Parse the activity report into something appropriate for Scoutbook.


text:
require 'spec_helper'

describe Rubocop::Options, :isolated_environment do
  include FileHelper

  subject(:options) { described_class.new }

  before(:each) do
    $stdout = StringIO.new
    $stderr = StringIO.new
  end

  after(:each) do
    $stdout = STDOUT
    $stderr = STDERR
  end

  def abs(path)
    File.expand_path(path)
  end

  describe 'option' do
    describe '-h/--help' do
      it 'exits cleanly' do
        expect { options.parse ['-h'] }.to exit_with_code(0)
        expect { options.parse ['--help'] }.to exit_with_code(0)
      end

      it 'shows help text' do
        begin
          options.parse(['--help'])
        rescue SystemExit # rubocop:disable HandleExceptions
        end

        expected_help = <<-END
Usage: rubocop [options] [file1, file2, ...]
        --only COP                   Run just one cop.
    -c, --config FILE                Specify configuration file.
        --auto-gen-config            Generate a configuration file acting as a
                                     TODO list.
    -f, --format FORMATTER           Choose an output formatter. This option
                                     can be specified multiple times to enable
                                     multiple formatters at the same time.
                                       [p]rogress (default)
                                       [s]imple
                                       [c]lang
                                       [e]macs
                                       [j]son
                                       [f]iles
                                       [o]ffences
                                       custom formatter class name
    -o, --out FILE                   Write output to a file instead of STDOUT.
                                     This option applies to the previously
                                     specified --format, or the default format
                                     if no format is specified.
    -r, --require FILE               Require Ruby file.
        --show-cops [cop1,cop2,...]  Shows the given cops, or all cops by
                                     default, and their configurations for the
                                     current directory.
    -d, --debug                      Display debug info.
    -D, --display-cop-names          Display cop names in offence messages.
    -R, --rails                      Run extra Rails cops.
    -l, --lint                       Run only lint cops.
    -a, --auto-correct               Auto-correct offences.
    -n, --no-color                   Disable color output.
    -v, --version                    Display version.
    -V, --verbose-version            Display verbose version.
      END

        expect($stdout.string).to eq(expected_help)
      end

      it 'lists all builtin formatters' do
        begin
          options.parse(['--help'])
        rescue SystemExit # rubocop:disable HandleExceptions
        end

        option_sections = $stdout.string.lines.slice_before(/^\s*-/)

        format_section = option_sections.find do |lines|
          lines.first =~ /^\s*-f/
        end

        formatter_keys = format_section.reduce([]) do |keys, line|
          match = line.match(/^[ ]{39}(\[[a-z\]]+)/)
          next keys unless match
          keys << match.captures.first.gsub(/\[|\]/, '')
        end.sort

        expected_formatter_keys =
          Rubocop::Formatter::FormatterSet::BUILTIN_FORMATTERS_FOR_KEYS
          .keys.sort

        expect(formatter_keys).to eq(expected_formatter_keys)
      end
    end

    describe '--only' do
      it 'exits with error if an incorrect cop name is passed' do
        expect { options.parse(%w(--only 123)) }
          .to raise_error(ArgumentError, /Unrecognized cop name: 123./)
      end
    end

    describe '--require' do
      let(:required_file_path) { './path/to/required_file.rb' }

      before do
        create_file('example.rb', '# encoding: utf-8')

        create_file(required_file_path, [
                                         '# encoding: utf-8',
                                         "puts 'Hello from required file!'"
                                        ])
      end

      it 'requires the passed path' do
        options.parse(['--require', required_file_path, 'example.rb'])
        expect($stdout.string).to start_with('Hello from required file!')
      end
    end
  end

  unless Rubocop::Version::STRING.start_with?('0')
    describe '-e/--emacs option' do
      it 'is dropped in RuboCop 1.0.0' do
        # This spec can be removed once the option is dropped.
        expect { options.parse(['--emacs']) }
          .to raise_error(OptionParser::InvalidOption)
      end
    end

    describe '-s/--silent option' do
      it 'raises error in RuboCop 1.0.0' do
        # This spec can be removed
        # once Options#ignore_dropped_options is removed.
        expect { options.parse(['--silent']) }
          .to raise_error(OptionParser::InvalidOption)
      end
    end
  end
end


text:
These developer notes show how to install, configure, build, run, and test Argumenta from source.

## Install

### 1. Get the Source

To get started with Argumenta development, clone the git repo:

```shell
$ git clone https://github.com/argumenta/argumenta.git
```

Even better, fork our repo on GitHub and clone that. This way you can push your changes, and send us a pull request!

### 2. Install Dependencies

Change into the source directory, and install Argumenta's dependencies with npm:

```shell
$ cd argumenta
$ npm install
```
### 4. Database Setup

Setup databases in the same way you would for a normal install, but using `./bin/setup-postgres.sh`.
See the [Install instructions][Install].

[Install]: ./README.Install.markdown

### 3. Configure

Run the command `./bin/setup-config.sh` to generate local config files:

```bash
$ argumenta-setup-config
Initializing config/deploy
Creating './config/deploy/development.json'
Creating './config/deploy/testing.json'
Creating './config/deploy/staging.json'
Creating './config/deploy/production.json'
Done!
```

This copies defaults for each mode, and generates a random app secret. It won't overwrite existing config files.

You should now edit these files. In particular, edit the `postgresUrl` setting and change its `PASSWORD` placeholder to match the database password for each mode. See `config/modes` for a full list of settings, and the default for each mode.

### 4. Run

Run the `build` make target to compile the client and server:

```shell
$ make build
```

Run the test suite to make sure everything is ok:

```shell
$ make test
```

Argumenta should now be ready to run!

```shell
$ node app
Argumenta 0.0.1 (development mode) | http://localhost:3000
```

## Building

Make all (build + docs)

```shell
$ make all
```

Make build (server + client)

```shell
$ make build
```

Make coffee

```shell
$ make coffee
```

Make coffee automatically

```shell
$ make coffee_forever
```

## Testing

Run tests once

```shell
$ make test
```

Run tests automatically

```shell
$ make test_forever
```

Run tests matching `pattern` in a given `file`

```shell
$ NODE_ENV='testing' mocha -g '<pattern>' test/<file>.js
```

## Test Options

### NODE_ENV

The node env determines the application mode.
Current modes include 'production', 'staging', 'development', and 'testing'.
Settings for each mode reside in `config/deploy/<mode>.json`.
These extend the mode defaults in `config/modes/<mode>.json`.

### LOG_LEVEL

The default log level for tests hides errors to reduce output noise.
Change the log level from 'testing' to 'debug' to see more error output.

```shell
$ LOG_LEVEL='debug' make test
```

### REPORTER

The default reporter shows the name of each test as it is run.
Change the reporter from 'spec' to 'dot' for quieter automatic testing.

```shell
$ REPORTER='dot' make test_forever
```

### BCRYPT_COST

The bcrypt cost determines how many times passwords will be hashed.
The default cost of '10' increases the cost of reversing password hashes, but slows down account creation and login.
When testing, the value is lowered to '1' for faster tests.
Raise the bcrypt cost above '10' to experiment with higher values.

```shell
$ BCRYPT_COST='12' make test
```


text:
package io.github.opencubicchunks.cubicchunks.api.world;

import io.github.opencubicchunks.cubicchunks.api.util.CubePos;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.world.chunk.Chunk;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public interface ICubeProviderServer extends ICubeProvider {

    /**
     * Retrieve a column. The work done to retrieve the column is specified by the {@link Requirement} {@code req}
     *
     * @param columnX Column x position
     * @param columnZ Column z position
     * @param req Work done to retrieve the column
     *
     * @return the column, or {@code null} if no column could be created with the specified requirement level
     */
    @Nullable
    Chunk getColumn(int columnX, int columnZ, Requirement req);

    /**
     * Retrieve a cube. The work done to retrieve the cube is specified by {@link Requirement} {@code req}
     *
     * @param cubeX the cube's x coordinate
     * @param cubeY the cube's y coordinate
     * @param cubeZ the cube's z coordinate
     * @param req what the requirments are before you get the Cube
     *
     * @return the Cube or null if no Cube could be found or created
     */
    @Nullable
    ICube getCube(int cubeX, int cubeY, int cubeZ, Requirement req);

    @Nullable ICube getCubeNow(int cubeX, int cubeY, int cubeZ, ICubeProviderServer.Requirement req);

    /**
     * Returns true if the specified cube has been already generated (either loaded or saved
     * on disk).
     *
     * @param cubeX x coordinate of the cube
     * @param cubeY y coordinate of the cube
     * @param cubeZ z coordinate of the cube
     * @return true iff, for this position, {@link #getCube(int, int, int, Requirement)} with {@link Requirement#LOAD}
     * would return a non-null value. The result is guaranteed to be true only if the world save is not corrupted
     * and can otherwise be correctly read.
     */
    boolean isCubeGenerated(int cubeX, int cubeY, int cubeZ);

    /**
     * The effort made to retrieve a cube or column. Any further work should not be done, and returning
     * {@code null} is acceptable in those cases
     */
    enum Requirement {
        // Warning, don't modify order of these constants - ordinals are used in comparisons
        // TODO write a custom compare method
        /**
         * Only retrieve the cube/column if it is already cached
         */
        GET_CACHED,
        /**
         * Load the cube/column from disk, if necessary
         */
        LOAD,
        /**
         * Generate the cube/column, if necessary
         */
        GENERATE,
        /**
         * Populate the cube/column, if necessary
         */
        POPULATE,
        /**
         * Generate lighting information for the cube, if necessary
         */
        LIGHT
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: Namespace Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>

OR-Tools
    9.4

Here is a list of all namespace members with links to the namespace documentation for each member:

- f -

FailedLiteralProbingRound() : operations_research::sat

FailedPreconditionErrorBuilder() : util

fast_ilogb() : operations_research

fast_scalbn() : operations_research

fast_scalbn_inplace() : operations_research

FastTypeId() : gtl

fatal_message : google

fatal_msg_data_exclusive : google

fatal_msg_data_shared : google

fatal_msg_exclusive : google

fatal_msg_lock : google

fatal_time : google

FeasibilityStatus : operations_research::math_opt

FEASIBLE : operations_research

FeasibleTermination() : operations_research::math_opt

FillDomainInProto() : operations_research::sat

FillPathEvaluation() : operations_research

FillSparseBasisStatusVector() : operations_research::math_opt

FillSparseDoubleVector() : operations_research::math_opt

FillTravelBoundsOfVehicle() : operations_research

FillValues() : operations_research

FilterBoxesAndRandomize() : operations_research::sat

FilterBoxesThatAreTooLarge() : operations_research::sat

FindBestScalingAndComputeErrors() : operations_research::sat

FindCliques() : operations_research

FindCopy() : gtl

FindCpModelSymmetries() : operations_research::sat

FindCycleInDenseIntGraph() : util

FindDuplicateConstraints() : operations_research::sat

FindErrorInMPModelDeltaProto() : operations_research

FindErrorInMPModelForScip() : operations_research

FindErrorInMPModelProto() : operations_research

FindErrorInRoutingSearchParameters() : operations_research

FindErrorsInRoutingSearchParameters() : operations_research

FindFeasibilityErrorInSolutionHint() : operations_research

FindLinearBooleanProblemSymmetries() : operations_research::sat

FindOrDie() : gtl

FindOrDieNoPrint() : gtl

FindOrNull() : gtl

FindProportionalColumns() : operations_research::glop

FindProportionalColumnsUsingSimpleAlgorithm() : operations_research::glop

FindPtrOrNull() : gtl

FindRationalFactor() : operations_research::sat

FindScalingFactor() : operations_research::pdlp

FindWithDefault() : gtl

FirstLinearConstraintId() : operations_research::math_opt

FirstUnassignedVarAtItsMinHeuristic() : operations_research::sat

FirstVariableId() : operations_research::math_opt

FixAndParseParameters() : operations_research::fz

FixConstraintWithFixedStatuses() : operations_research::glop

FixedDivisionConstraint() : operations_research::sat

FixedModuloConstraint() : operations_research::sat

FixedWeightedSum() : operations_research::sat

FixedWeightedSumReif() : operations_research::sat

FlattenAnnotations() : operations_research::fz

FloatArrayEq() : operations_research::pdlp

FloatArrayNear() : operations_research::pdlp

FloorRatio() : operations_research, operations_research::sat

FloorSquareRoot() : operations_research::sat

FlowQuantity : operations_research

FlushLogFiles() : google

FlushLogFilesUnsafe() : google

FollowHint() : operations_research::sat

ForwardStarGraph : operations_research

ForwardStarStaticGraph : operations_research

Fraction : operations_research

Fractional : operations_research::glop

Fractionality() : operations_research::glop

FromGlopBasisStatus() : operations_research::math_opt

FullMerge() : operations_research::sat

FullProtocolMessageAsString() : operations_research

FullyCompressTuples() : operations_research::sat

FullyEncodeVariable() : operations_research::sat

Generated by

     1.9.4


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('recipes', '0012_comment_date'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='recipe',
            name='likes',
        ),
    ]


text:
using System;
using Xunit;

namespace SharpEssentials.Tests.Unit.SharpEssentials
{
	public class DisposableBaseTests
	{
		[Fact]
		public void Test_Dispose()
		{
			// Arrange.
			var test = new TestDisposable();

			// Act.
			test.Dispose();

			// Assert.
			Assert.True(test.IsDisposed);
			Assert.True(test.OnDisposingCalled);
			Assert.True(test.OnDisposeCalled);
		}

		[Fact]
		public void Test_ThrowIfDisposed()
		{
			// Arrange.
			var test = new TestDisposable();
			test.Dispose();

			// Act/Assert.
			Assert.Throws<ObjectDisposedException>(() => test.Do());
		}

		private class TestDisposable : DisposableBase
		{
			public void Do()
			{
				ThrowIfDisposed();
			}

			public bool OnDisposingCalled { get; private set; }
			public bool OnDisposeCalled { get; private set; }

			#region Overrides of DisposableBase

			protected override void OnDisposing()
			{
				OnDisposingCalled = true;
			}

			protected override void OnDispose()
			{
				OnDisposeCalled = true;
			}

			#endregion
		}
	}
}


text:
package vsphere

import (
	"reflect"
	"testing"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes/fake"
)

func TestSecretCredentialManager_GetCredential(t *testing.T) {
	var (
		userKey             = "username"
		passwordKey         = "password"
		testUser            = "user"
		testPassword        = "password"
		testServer          = "0.0.0.0"
		testServer2         = "0.0.1.1"
		testUserServer2     = "user1"
		testPasswordServer2 = "password1"
		testIncorrectServer = "1.1.1.1"
	)
	var (
		secretName      = "vsconf"
		secretNamespace = "kube-system"
	)
	var (
		addSecretOp      = "ADD_SECRET_OP"
		getCredentialsOp = "GET_CREDENTIAL_OP"
		deleteSecretOp   = "DELETE_SECRET_OP"
	)
	type GetCredentialsTest struct {
		server   string
		username string
		password string
		err      error
	}
	type OpSecretTest struct {
		secret *corev1.Secret
	}
	type testEnv struct {
		testName       string
		ops            []string
		expectedValues []interface{}
	}

	client := &fake.Clientset{}
	metaObj := metav1.ObjectMeta{
		Name:      secretName,
		Namespace: secretNamespace,
	}

	defaultSecret := &corev1.Secret{
		ObjectMeta: metaObj,
		Data: map[string][]byte{
			testServer + "." + userKey:     []byte(testUser),
			testServer + "." + passwordKey: []byte(testPassword),
		},
	}

	multiVCSecret := &corev1.Secret{
		ObjectMeta: metaObj,
		Data: map[string][]byte{
			testServer + "." + userKey:      []byte(testUser),
			testServer + "." + passwordKey:  []byte(testPassword),
			testServer2 + "." + userKey:     []byte(testUserServer2),
			testServer2 + "." + passwordKey: []byte(testPasswordServer2),
		},
	}

	emptySecret := &corev1.Secret{
		ObjectMeta: metaObj,
		Data:       map[string][]byte{},
	}

	tests := []testEnv{
		{
			testName: "Deleting secret should give the credentials from cache",
			ops:      []string{addSecretOp, getCredentialsOp, deleteSecretOp, getCredentialsOp},
			expectedValues: []interface{}{
				OpSecretTest{
					secret: defaultSecret,
				},
				GetCredentialsTest{
					username: testUser,
					password: testPassword,
					server:   testServer,
				},
				OpSecretTest{
					secret: defaultSecret,
				},
				GetCredentialsTest{
					username: testUser,
					password: testPassword,
					server:   testServer,
				},
			},
		},
		{
			testName: "Add secret and get credentials",
			ops:      []string{addSecretOp, getCredentialsOp},
			expectedValues: []interface{}{
				OpSecretTest{
					secret: defaultSecret,
				},
				GetCredentialsTest{
					username: testUser,
					password: testPassword,
					server:   testServer,
				},
			},
		},
		{
			testName: "Getcredentials should fail by not adding at secret at first time",
			ops:      []string{getCredentialsOp},
			expectedValues: []interface{}{
				GetCredentialsTest{
					username: testUser,
					password: testPassword,
					server:   testServer,
					err:      ErrCredentialsNotFound,
				},
			},
		},
		{
			testName: "GetCredential should fail to get credentials from empty secrets",
			ops:      []string{addSecretOp, getCredentialsOp},
			expectedValues: []interface{}{
				OpSecretTest{
					secret: emptySecret,
				},
				GetCredentialsTest{
					server: testServer,
					err:    ErrCredentialMissing,
				},
			},
		},
		{
			testName: "GetCredential should fail to get credentials for invalid server",
			ops:      []string{addSecretOp, getCredentialsOp},
			expectedValues: []interface{}{
				OpSecretTest{
					secret: defaultSecret,
				},
				GetCredentialsTest{
					server: testIncorrectServer,
					err:    ErrCredentialsNotFound,
				},
			},
		},
		{
			testName: "GetCredential for multi-vc",
			ops:      []string{addSecretOp, getCredentialsOp},
			expectedValues: []interface{}{
				OpSecretTest{
					secret: multiVCSecret,
				},
				GetCredentialsTest{
					server:   testServer2,
					username: testUserServer2,
					password: testPasswordServer2,
				},
			},
		},
	}

	// TODO: replace 0 with NoResyncPeriodFunc() once it moved out pkg/controller/controller_utils.go in k/k.
	informerFactory := informers.NewSharedInformerFactory(client, 0)
	secretInformer := informerFactory.Core().V1().Secrets()
	secretCredentialManager := &SecretCredentialManager{
		SecretName:      secretName,
		SecretNamespace: secretNamespace,
		SecretLister:    secretInformer.Lister(),
		Cache: &SecretCache{
			VirtualCenter: make(map[string]*Credential),
		},
	}
	cleanupSecretCredentialManager := func() {
		secretCredentialManager.Cache.Secret = nil
		for key := range secretCredentialManager.Cache.VirtualCenter {
			delete(secretCredentialManager.Cache.VirtualCenter, key)
		}
		secrets, err := secretCredentialManager.SecretLister.List(labels.Everything())
		if err != nil {
			t.Fatal("Failed to get all secrets from sharedInformer. error: ", err)
		}
		for _, secret := range secrets {
			err := secretInformer.Informer().GetIndexer().Delete(secret)
			if err != nil {
				t.Fatalf("Failed to delete secret from informer: %v", err)
			}
		}
	}

	for _, test := range tests {
		t.Logf("Executing Testcase: %s", test.testName)
		for ntest, op := range test.ops {
			switch op {
			case addSecretOp:
				expected := test.expectedValues[ntest].(OpSecretTest)
				t.Logf("Adding secret: %s", expected.secret)
				err := secretInformer.Informer().GetIndexer().Add(expected.secret)
				if err != nil {
					t.Fatalf("Failed to add secret to internal cache: %v", err)
				}
			case getCredentialsOp:
				expected := test.expectedValues[ntest].(GetCredentialsTest)
				credential, err := secretCredentialManager.GetCredential(expected.server)
				t.Logf("Retrieving credentials for server %s", expected.server)
				if err != expected.err {
					t.Fatalf("Fail to get credentials with error: %v", err)
				}
				if expected.err == nil {
					if expected.username != credential.User ||
						expected.password != credential.Password {
						t.Fatalf("Received credentials %v "+
							"are different than actual credential user:%s password:%s", credential, expected.username,
							expected.password)
					}
				}
			case deleteSecretOp:
				expected := test.expectedValues[ntest].(OpSecretTest)
				t.Logf("Deleting secret: %s", expected.secret)
				err := secretInformer.Informer().GetIndexer().Delete(expected.secret)
				if err != nil {
					t.Fatalf("Failed to delete secret to internal cache: %v", err)
				}
			}
		}
		cleanupSecretCredentialManager()
	}
}

func TestParseSecretConfig(t *testing.T) {
	var (
		testUsername = "Admin"
		testPassword = "Password"
		testIP       = "10.20.30.40"
	)
	var testcases = []struct {
		testName      string
		data          map[string][]byte
		config        map[string]*Credential
		expectedError error
	}{
		{
			testName: "Valid username and password",
			data: map[string][]byte{
				"10.20.30.40.username": []byte(testUsername),
				"10.20.30.40.password": []byte(testPassword),
			},
			config: map[string]*Credential{
				testIP: {
					User:     testUsername,
					Password: testPassword,
				},
			},
			expectedError: nil,
		},
		{
			testName: "Invalid username key with valid password key",
			data: map[string][]byte{
				"10.20.30.40.usernam":  []byte(testUsername),
				"10.20.30.40.password": []byte(testPassword),
			},
			config:        nil,
			expectedError: ErrUnknownSecretKey,
		},
		{
			testName: "Missing username",
			data: map[string][]byte{
				"10.20.30.40.password": []byte(testPassword),
			},
			config: map[string]*Credential{
				testIP: {
					Password: testPassword,
				},
			},
			expectedError: ErrCredentialMissing,
		},
		{
			testName: "Missing password",
			data: map[string][]byte{
				"10.20.30.40.username": []byte(testUsername),
			},
			config: map[string]*Credential{
				testIP: {
					User: testUsername,
				},
			},
			expectedError: ErrCredentialMissing,
		},
		{
			testName: "IP with unknown key",
			data: map[string][]byte{
				"10.20.30.40": []byte(testUsername),
			},
			config:        nil,
			expectedError: ErrUnknownSecretKey,
		},
	}

	resultConfig := make(map[string]*Credential)
	cleanupResultConfig := func(config map[string]*Credential) {
		for k := range config {
			delete(config, k)
		}
	}

	for _, testcase := range testcases {
		err := parseConfig(testcase.data, resultConfig)
		t.Logf("Executing Testcase: %s", testcase.testName)
		if err != testcase.expectedError {
			t.Fatalf("Parsing Secret failed for data %+v: %s", testcase.data, err)
		}
		if testcase.config != nil && !reflect.DeepEqual(testcase.config, resultConfig) {
			t.Fatalf("Parsing Secret failed for data %+v expected config %+v and actual config %+v",
				testcase.data, resultConfig, testcase.config)
		}
		cleanupResultConfig(resultConfig)
	}
}


text:
import json
import subprocess
import time
import os
import apt_pkg as apt
from charmhelpers.core.host import (
    mkdir,
    service_restart,
)
from charmhelpers.core.hookenv import (
    log,
    ERROR,
)
from charmhelpers.contrib.storage.linux.utils import (
    zap_disk,
    is_block_device,
)
from utils import (
    get_unit_hostname,
)

LEADER = 'leader'
PEON = 'peon'
QUORUM = [LEADER, PEON]

PACKAGES = ['ceph', 'gdisk', 'ntp', 'btrfs-tools', 'python-ceph', 'xfsprogs']

def is_quorum():
    asok = "/var/run/ceph/ceph-mon.{}.asok".format(get_unit_hostname())
    cmd = [
        "ceph",
        "--admin-daemon",
        asok,
        "mon_status"
    ]
    if os.path.exists(asok):
        try:
            result = json.loads(subprocess.check_output(cmd))
        except subprocess.CalledProcessError:
            return False
        except ValueError:
            # Non JSON response from mon_status
            return False
        if result['state'] in QUORUM:
            return True
        else:
            return False
    else:
        return False

def is_leader():
    asok = "/var/run/ceph/ceph-mon.{}.asok".format(get_unit_hostname())
    cmd = [
        "ceph",
        "--admin-daemon",
        asok,
        "mon_status"
    ]
    if os.path.exists(asok):
        try:
            result = json.loads(subprocess.check_output(cmd))
        except subprocess.CalledProcessError:
            return False
        except ValueError:
            # Non JSON response from mon_status
            return False
        if result['state'] == LEADER:
            return True
        else:
            return False
    else:
        return False

def wait_for_quorum():
    while not is_quorum():
        time.sleep(3)

def add_bootstrap_hint(peer):
    asok = "/var/run/ceph/ceph-mon.{}.asok".format(get_unit_hostname())
    cmd = [
        "ceph",
        "--admin-daemon",
        asok,
        "add_bootstrap_peer_hint",
        peer
    ]
    if os.path.exists(asok):
        # Ignore any errors for this call
        subprocess.call(cmd)

DISK_FORMATS = [
    'xfs',
    'ext4',
    'btrfs'
]

def is_osd_disk(dev):
    try:
        info = subprocess.check_output(['sgdisk', '-i', '1', dev])
        info = info.split("\n")  # IGNORE:E1103
        for line in info:
            if line.startswith(
                'Partition GUID code: 4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D'
            ):
                return True
    except subprocess.CalledProcessError:
        pass
    return False

def start_osds(devices):
    # Scan for ceph block devices
    rescan_osd_devices()
    if get_ceph_version() >= "0.56.6":
        # Use ceph-disk-activate for directory based OSD's
        for dev_or_path in devices:
            if os.path.exists(dev_or_path) and os.path.isdir(dev_or_path):
                subprocess.check_call(['ceph-disk-activate', dev_or_path])

def rescan_osd_devices():
    cmd = [
        'udevadm', 'trigger',
        '--subsystem-match=block', '--action=add'
    ]

    subprocess.call(cmd)

_bootstrap_keyring = "/var/lib/ceph/bootstrap-osd/ceph.keyring"

def is_bootstrapped():
    return os.path.exists(_bootstrap_keyring)

def wait_for_bootstrap():
    while (not is_bootstrapped()):
        time.sleep(3)

def import_osd_bootstrap_key(key):
    if not os.path.exists(_bootstrap_keyring):
        cmd = [
            'ceph-authtool',
            _bootstrap_keyring,
            '--create-keyring',
            '--name=client.bootstrap-osd',
            '--add-key={}'.format(key)
        ]
        subprocess.check_call(cmd)

# OSD caps taken from ceph-create-keys
_osd_bootstrap_caps = {
    'mon': [
        'allow command osd create ...',
        'allow command osd crush set ...',
        r'allow command auth add * osd allow\ * mon allow\ rwx',
        'allow command mon getmap'
    ]
}

_osd_bootstrap_caps_profile = {
    'mon': [
        'allow profile bootstrap-osd'
    ]
}

def parse_key(raw_key):
    # get-or-create appears to have different output depending
    # on whether its 'get' or 'create'
    # 'create' just returns the key, 'get' is more verbose and
    # needs parsing
    key = None
    if len(raw_key.splitlines()) == 1:
        key = raw_key
    else:
        for element in raw_key.splitlines():
            if 'key' in element:
                key = element.split(' = ')[1].strip()  # IGNORE:E1103
    return key

def get_osd_bootstrap_key():
    try:
        # Attempt to get/create a key using the OSD bootstrap profile first
        key = get_named_key('bootstrap-osd',
                            _osd_bootstrap_caps_profile)
    except:
        # If that fails try with the older style permissions
        key = get_named_key('bootstrap-osd',
                            _osd_bootstrap_caps)
    return key

_radosgw_keyring = "/etc/ceph/keyring.rados.gateway"

def import_radosgw_key(key):
    if not os.path.exists(_radosgw_keyring):
        cmd = [
            'ceph-authtool',
            _radosgw_keyring,
            '--create-keyring',
            '--name=client.radosgw.gateway',
            '--add-key={}'.format(key)
        ]
        subprocess.check_call(cmd)

# OSD caps taken from ceph-create-keys
_radosgw_caps = {
    'mon': ['allow rw'],
    'osd': ['allow rwx']
}

def get_radosgw_key():
    return get_named_key('radosgw.gateway', _radosgw_caps)

_default_caps = {
    'mon': ['allow rw'],
    'osd': ['allow rwx']
}

def get_named_key(name, caps=None):
    caps = caps or _default_caps
    cmd = [
        'ceph',
        '--name', 'mon.',
        '--keyring',
        '/var/lib/ceph/mon/ceph-{}/keyring'.format(
            get_unit_hostname()
        ),
        'auth', 'get-or-create', 'client.{}'.format(name),
    ]
    # Add capabilities
    for subsystem, subcaps in caps.iteritems():
        cmd.extend([
            subsystem,
            '; '.join(subcaps),
        ])
    return parse_key(subprocess.check_output(cmd).strip())  # IGNORE:E1103

def upgrade_key_caps(key, caps):
    ''' Upgrade key to have capabilities caps '''
    if not is_leader():
        # Not the MON leader OR not clustered
        return
    cmd = [
        'ceph', 'auth', 'caps', key
    ]
    for subsystem, subcaps in caps.iteritems():
        cmd.extend([subsystem, '; '.join(subcaps)])
    subprocess.check_call(cmd)

def bootstrap_monitor_cluster(secret):
    hostname = get_unit_hostname()
    path = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
    done = '{}/done'.format(path)
    upstart = '{}/upstart'.format(path)
    keyring = '/var/lib/ceph/tmp/{}.mon.keyring'.format(hostname)

    if os.path.exists(done):
        log('bootstrap_monitor_cluster: mon already initialized.')
    else:
        # Ceph >= 0.61.3 needs this for ceph-mon fs creation
        mkdir('/var/run/ceph', perms=0755)
        mkdir(path)
        # end changes for Ceph >= 0.61.3
        try:
            subprocess.check_call(['ceph-authtool', keyring,
                                   '--create-keyring', '--name=mon.',
                                   '--add-key={}'.format(secret),
                                   '--cap', 'mon', 'allow *'])

            subprocess.check_call(['ceph-mon', '--mkfs',
                                   '-i', hostname,
                                   '--keyring', keyring])

            with open(done, 'w'):
                pass
            with open(upstart, 'w'):
                pass

            service_restart('ceph-mon-all')
        except:
            raise
        finally:
            os.unlink(keyring)

def get_ceph_version():
    apt.init()
    cache = apt.Cache()
    pkg = cache['ceph']
    if pkg.current_ver:
        return apt.upstream_version(pkg.current_ver.ver_str)
    else:
        return None

def version_compare(a, b):
    return apt.version_compare(a, b)

def update_monfs():
    hostname = get_unit_hostname()
    monfs = '/var/lib/ceph/mon/ceph-{}'.format(hostname)
    upstart = '{}/upstart'.format(monfs)
    if os.path.exists(monfs) and not os.path.exists(upstart):
        # Mark mon as managed by upstart so that
        # it gets start correctly on reboots
        with open(upstart, 'w'):
            pass

def osdize(dev, osd_format, osd_journal, reformat_osd=False):
    if dev.startswith('/dev'):
        osdize_dev(dev, osd_format, osd_journal, reformat_osd)
    else:
        osdize_dir(dev)

def osdize_dev(dev, osd_format, osd_journal, reformat_osd=False):
    if not os.path.exists(dev):
        log('Path {} does not exist - bailing'.format(dev))
        return

    if not is_block_device(dev):
        log('Path {} is not a block device - bailing'.format(dev))
        return

    if (is_osd_disk(dev) and not reformat_osd):
        log('Looks like {} is already an OSD, skipping.'.format(dev))
        return

    if device_mounted(dev):
        log('Looks like {} is in use, skipping.'.format(dev))
        return

    cmd = ['ceph-disk-prepare']
    # Later versions of ceph support more options
    if get_ceph_version() >= "0.48.3":
        if osd_format:
            cmd.append('--fs-type')
            cmd.append(osd_format)
        cmd.append(dev)
        if osd_journal and os.path.exists(osd_journal):
            cmd.append(osd_journal)
    else:
        # Just provide the device - no other options
        # for older versions of ceph
        cmd.append(dev)

    if reformat_osd:
        zap_disk(dev)

    subprocess.check_call(cmd)

def osdize_dir(path):
    if os.path.exists(os.path.join(path, 'upstart')):
        log('Path {} is already configured as an OSD - bailing'.format(path))
        return

    if get_ceph_version() < "0.56.6":
        log('Unable to use directories for OSDs with ceph < 0.56.6',
            level=ERROR)
        raise

    mkdir(path)
    cmd = [
        'ceph-disk-prepare',
        '--data-dir',
        path
    ]
    subprocess.check_call(cmd)

def device_mounted(dev):
    return subprocess.call(['grep', '-wqs', dev + '1', '/proc/mounts']) == 0

def filesystem_mounted(fs):
    return subprocess.call(['grep', '-wqs', fs, '/proc/mounts']) == 0


text:
package org.jabref.logic.formatter.bibtexfields;

import java.util.stream.Stream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class HtmlToUnicodeFormatterTest {

    private HtmlToUnicodeFormatter formatter;

    private static Stream<Arguments> data() {
        return Stream.of(
                         Arguments.of("abc", "abc"),
                         Arguments.of("åäö", "åäö"),
                         Arguments.of("í", "í"),
                         Arguments.of("Ε", "Ε"),
                         Arguments.of("ä", "ä"),
                         Arguments.of("ä", "ä"),
                         Arguments.of("ä", "ä"),
                         Arguments.of("ñ", "ñ"),
                         Arguments.of("aaa", "
aaa
"),
                         Arguments.of("bread & butter", "bread & butter"));
    }

    @BeforeEach
    public void setUp() {
        formatter = new HtmlToUnicodeFormatter();
    }

    @ParameterizedTest
    @MethodSource("data")
    void testFormatterWorksCorrectly(String expected, String input) {
        assertEquals(expected, formatter.format(input));
    }
}


text:
package org.apache.hadoop.hdfs.client;

import org.apache.hadoop.HadoopIllegalArgumentException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.fs.BlockStoragePolicySpi;
import org.apache.hadoop.fs.CacheFlag;
import org.apache.hadoop.fs.FileEncryptionInfo;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSInotifyEventInputStream;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.AddErasureCodingPolicyResponse;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
import org.apache.hadoop.hdfs.protocol.CachePoolInfo;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicyInfo;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.ReencryptAction;
import org.apache.hadoop.hdfs.protocol.OpenFileEntry;
import org.apache.hadoop.hdfs.protocol.OpenFilesIterator.OpenFilesType;
import org.apache.hadoop.hdfs.protocol.ZoneReencryptionStatus;
import org.apache.hadoop.security.AccessControlException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.EnumSet;

/**
 * The public API for performing administrative functions on HDFS. Those writing
 * applications against HDFS should prefer this interface to directly accessing
 * functionality in DistributedFileSystem or DFSClient.
 *
 * Note that this is distinct from the similarly-named DFSAdmin, which
 * is a class that provides the functionality for the CLI `hdfs dfsadmin ...'
 * commands.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class HdfsAdmin {

  private DistributedFileSystem dfs;
  private static final FsPermission TRASH_PERMISSION = new FsPermission(
      FsAction.ALL, FsAction.ALL, FsAction.ALL, true);

  /**
   * Create a new HdfsAdmin client.
   *
   * @param uri the unique URI of the HDFS file system to administer
   * @param conf configuration
   * @throws IOException in the event the file system could not be created
   */
  public HdfsAdmin(URI uri, Configuration conf) throws IOException {
    FileSystem fs = FileSystem.get(uri, conf);
    if (!(fs instanceof DistributedFileSystem)) {
      throw new IllegalArgumentException("'" + uri + "' is not an HDFS URI.");
    } else {
      dfs = (DistributedFileSystem)fs;
    }
  }

  /**
   * Set the namespace quota (count of files, directories, and sym links) for a
   * directory.
   *
   * @param src the path to set the quota for
   * @param quota the value to set for the quota
   * @throws IOException in the event of error
   */
  public void setQuota(Path src, long quota) throws IOException {
    dfs.setQuota(src, quota, HdfsConstants.QUOTA_DONT_SET);
  }

  /**
   * Clear the namespace quota (count of files, directories and sym links) for a
   * directory.
   *
   * @param src the path to clear the quota of
   * @throws IOException in the event of error
   */
  public void clearQuota(Path src) throws IOException {
    dfs.setQuota(src, HdfsConstants.QUOTA_RESET, HdfsConstants.QUOTA_DONT_SET);
  }

  /**
   * Set the storage space quota (size of files) for a directory. Note that
   * directories and sym links do not occupy storage space.
   *
   * @param src the path to set the space quota of
   * @param spaceQuota the value to set for the space quota
   * @throws IOException in the event of error
   */
  public void setSpaceQuota(Path src, long spaceQuota) throws IOException {
    dfs.setQuota(src, HdfsConstants.QUOTA_DONT_SET, spaceQuota);
  }

  /**
   * Clear the storage space quota (size of files) for a directory. Note that
   * directories and sym links do not occupy storage space.
   *
   * @param src the path to clear the space quota of
   * @throws IOException in the event of error
   */
  public void clearSpaceQuota(Path src) throws IOException {
    dfs.setQuota(src, HdfsConstants.QUOTA_DONT_SET, HdfsConstants.QUOTA_RESET);
  }

  /**
   * Set the quota by storage type for a directory. Note that
   * directories and sym links do not occupy storage type quota.
   *
   * @param src the target directory to set the quota by storage type
   * @param type the storage type to set for quota by storage type
   * @param quota the value to set for quota by storage type
   * @throws IOException in the event of error
   */
  public void setQuotaByStorageType(Path src, StorageType type, long quota)
      throws IOException {
    dfs.setQuotaByStorageType(src, type, quota);
  }

  /**
   * Clear the space quota by storage type for a directory. Note that
   * directories and sym links do not occupy storage type quota.
   *
   * @param src the target directory to clear the quota by storage type
   * @param type the storage type to clear for quota by storage type
   * @throws IOException in the event of error
   */
  public void clearQuotaByStorageType(Path src, StorageType type) throws IOException {
    dfs.setQuotaByStorageType(src, type, HdfsConstants.QUOTA_RESET);
  }

  /**
   * Allow snapshot on a directory.
   * @param path The path of the directory where snapshots will be taken.
   */
  public void allowSnapshot(Path path) throws IOException {
    dfs.allowSnapshot(path);
  }

  /**
   * Disallow snapshot on a directory.
   * @param path The path of the snapshottable directory.
   */
  public void disallowSnapshot(Path path) throws IOException {
    dfs.disallowSnapshot(path);
  }

  /**
   * Add a new CacheDirectiveInfo.
   *
   * @param info Information about a directive to add.
   * @param flags {@link CacheFlag}s to use for this operation.
   * @return the ID of the directive that was created.
   * @throws IOException if the directive could not be added
   */
  public long addCacheDirective(CacheDirectiveInfo info,
      EnumSet<CacheFlag> flags) throws IOException {
  return dfs.addCacheDirective(info, flags);
  }

  /**
   * Modify a CacheDirective.
   *
   * @param info Information about the directive to modify. You must set the ID
   *          to indicate which CacheDirective you want to modify.
   * @param flags {@link CacheFlag}s to use for this operation.
   * @throws IOException if the directive could not be modified
   */
  public void modifyCacheDirective(CacheDirectiveInfo info,
      EnumSet<CacheFlag> flags) throws IOException {
    dfs.modifyCacheDirective(info, flags);
  }

  /**
   * Remove a CacheDirective.
   *
   * @param id identifier of the CacheDirectiveInfo to remove
   * @throws IOException if the directive could not be removed
   */
  public void removeCacheDirective(long id)
      throws IOException {
    dfs.removeCacheDirective(id);
  }

  /**
   * List cache directives. Incrementally fetches results from the server.
   *
   * @param filter Filter parameters to use when listing the directives, null to
   *               list all directives visible to us.
   * @return A RemoteIterator which returns CacheDirectiveInfo objects.
   */
  public RemoteIterator<CacheDirectiveEntry> listCacheDirectives(
      CacheDirectiveInfo filter) throws IOException {
    return dfs.listCacheDirectives(filter);
  }

  /**
   * Add a cache pool.
   *
   * @param info
   *          The request to add a cache pool.
   * @throws IOException
   *          If the request could not be completed.
   */
  public void addCachePool(CachePoolInfo info) throws IOException {
    dfs.addCachePool(info);
  }

  /**
   * Modify an existing cache pool.
   *
   * @param info
   *          The request to modify a cache pool.
   * @throws IOException
   *          If the request could not be completed.
   */
  public void modifyCachePool(CachePoolInfo info) throws IOException {
    dfs.modifyCachePool(info);
  }

  /**
   * Remove a cache pool.
   *
   * @param poolName
   *          Name of the cache pool to remove.
   * @throws IOException
   *          if the cache pool did not exist, or could not be removed.
   */
  public void removeCachePool(String poolName) throws IOException {
    dfs.removeCachePool(poolName);
  }

  /**
   * List all cache pools.
   *
   * @return A remote iterator from which you can get CachePoolEntry objects.
   *          Requests will be made as needed.
   * @throws IOException
   *          If there was an error listing cache pools.
   */
  public RemoteIterator<CachePoolEntry> listCachePools() throws IOException {
    return dfs.listCachePools();
  }

  /**
   * Get KeyProvider if present.
   *
   * @return the key provider if encryption is enabled on HDFS.
   *         Otherwise, it returns null.
   * @throws IOException on RPC exception to the NN.
   */
  public KeyProvider getKeyProvider() throws IOException {
    return dfs.getClient().getKeyProvider();
  }

  /**
   * Create an encryption zone rooted at an empty existing directory, using the
   * specified encryption key. An encryption zone has an associated encryption
   * key used when reading and writing files within the zone.
   *
   * @param path    The path of the root of the encryption zone. Must refer to
   *                an empty, existing directory.
   * @param keyName Name of key available at the KeyProvider.
   * @throws IOException            if there was a general IO exception
   * @throws AccessControlException if the caller does not have access to path
   * @throws FileNotFoundException  if the path does not exist
   */
  @Deprecated
  public void createEncryptionZone(Path path, String keyName)
      throws IOException, AccessControlException, FileNotFoundException {
    dfs.createEncryptionZone(path, keyName);
  }

  /**
   * Create an encryption zone rooted at an empty existing directory, using the
   * specified encryption key. An encryption zone has an associated encryption
   * key used when reading and writing files within the zone.
   *
   * Additional options, such as provisioning the trash directory, can be
   * specified using {@link CreateEncryptionZoneFlag} flags.
   *
   * @param path    The path of the root of the encryption zone. Must refer to
   *                an empty, existing directory.
   * @param keyName Name of key available at the KeyProvider.
   * @param flags   flags for this operation.
   * @throws IOException            if there was a general IO exception
   * @throws AccessControlException if the caller does not have access to path
   * @throws FileNotFoundException  if the path does not exist
   * @throws HadoopIllegalArgumentException if the flags are invalid
   */
  public void createEncryptionZone(Path path, String keyName,
      EnumSet<CreateEncryptionZoneFlag> flags)
      throws IOException, AccessControlException, FileNotFoundException,
      HadoopIllegalArgumentException{
    dfs.createEncryptionZone(path, keyName);
    if (flags.contains(CreateEncryptionZoneFlag.PROVISION_TRASH)) {
      if (flags.contains(CreateEncryptionZoneFlag.NO_TRASH)) {
        throw new HadoopIllegalArgumentException(
            "can not have both PROVISION_TRASH and NO_TRASH flags");
      }
      dfs.provisionEZTrash(path, TRASH_PERMISSION);
    }
  }

  /**
   * Provision a trash directory for a given encryption zone.

   * @param path the root of the encryption zone
   * @throws IOException if the trash directory can not be created.
   */
  public void provisionEncryptionZoneTrash(Path path) throws IOException {
    dfs.provisionEZTrash(path, TRASH_PERMISSION);
  }

  /**
   * Get the path of the encryption zone for a given file or directory.
   *
   * @param path The path to get the ez for.
   * @return An EncryptionZone, or null if path does not exist or is not in an
   * ez.
   * @throws IOException            if there was a general IO exception
   * @throws AccessControlException if the caller does not have access to path
   */
  public EncryptionZone getEncryptionZoneForPath(Path path)
      throws IOException, AccessControlException {
    return dfs.getEZForPath(path);
  }

  /**
   * Returns a RemoteIterator which can be used to list the encryption zones
   * in HDFS. For large numbers of encryption zones, the iterator will fetch
   * the list of zones in a number of small batches.
   *

   * Since the list is fetched in batches, it does not represent a
   * consistent snapshot of the entire list of encryption zones.
   *

   * This method can only be called by HDFS superusers.
   */
  public RemoteIterator<EncryptionZone> listEncryptionZones()
      throws IOException {
    return dfs.listEncryptionZones();
  }

  /**
   * Performs re-encryption action for a given encryption zone.
   *
   * @param zone the root of the encryption zone
   * @param action the re-encrypt action
   * @throws IOException If any error occurs when handling re-encrypt action.
   */
  public void reencryptEncryptionZone(final Path zone,
      final ReencryptAction action) throws IOException {
    dfs.reencryptEncryptionZone(zone, action);
  }

  /**
   * Returns a RemoteIterator which can be used to list all re-encryption
   * information. For large numbers of re-encryptions, the iterator will fetch
   * the list in a number of small batches.
   *

   * Since the list is fetched in batches, it does not represent a
   * consistent snapshot of the entire list of encryption zones.
   *

   * This method can only be called by HDFS superusers.
   */
  public RemoteIterator<ZoneReencryptionStatus> listReencryptionStatus()
      throws IOException {
    return dfs.listReencryptionStatus();
  }

  /**
   * Returns the FileEncryptionInfo on the HdfsFileStatus for the given path.
   * The return value can be null if the path points to a directory, or a file
   * that is not in an encryption zone.
   *
   * @throws FileNotFoundException if the path does not exist.
   * @throws AccessControlException if no execute permission on parent path.
   */
  public FileEncryptionInfo getFileEncryptionInfo(final Path path)
      throws IOException {
    return dfs.getFileEncryptionInfo(path);
  }

  /**
   * Exposes a stream of namesystem events. Only events occurring after the
   * stream is created are available.
   * See {@link org.apache.hadoop.hdfs.DFSInotifyEventInputStream}
   * for information on stream usage.
   * See {@link org.apache.hadoop.hdfs.inotify.Event}
   * for information on the available events.
   *

   * Inotify users may want to tune the following HDFS parameters to
   * ensure that enough extra HDFS edits are saved to support inotify clients
   * that fall behind the current state of the namespace while reading events.
   * The default parameter values should generally be reasonable. If edits are
   * deleted before their corresponding events can be read, clients will see a
   * {@link org.apache.hadoop.hdfs.inotify.MissingEventsException} on
   * {@link org.apache.hadoop.hdfs.DFSInotifyEventInputStream} method calls.
   *
   * It should generally be sufficient to tune these parameters:
   * dfs.namenode.num.extra.edits.retained
   * dfs.namenode.max.extra.edits.segments.retained
   *
   * Parameters that affect the number of created segments and the number of
   * edits that are considered necessary, i.e. do not count towards the
   * dfs.namenode.num.extra.edits.retained quota):
   * dfs.namenode.checkpoint.period
   * dfs.namenode.checkpoint.txns
   * dfs.namenode.num.checkpoints.retained
   * dfs.ha.log-roll.period
   *

   * It is recommended that local journaling be configured
   * (dfs.namenode.edits.dir) for inotify (in addition to a shared journal)
   * so that edit transfers from the shared journal can be avoided.
   *
   * @throws IOException If there was an error obtaining the stream.
   */
  public DFSInotifyEventInputStream getInotifyEventStream() throws IOException {
    return dfs.getInotifyEventStream();
  }

  /**
   * A version of {@link HdfsAdmin#getInotifyEventStream()} meant for advanced
   * users who are aware of HDFS edits up to lastReadTxid (e.g. because they
   * have access to an FSImage inclusive of lastReadTxid) and only want to read
   * events after this point.
   */
  public DFSInotifyEventInputStream getInotifyEventStream(long lastReadTxid)
      throws IOException {
    return dfs.getInotifyEventStream(lastReadTxid);
  }

  /**
   * Set the source path to the specified storage policy.
   *
   * @param src The source path referring to either a directory or a file.
   * @param policyName The name of the storage policy.
   */
  public void setStoragePolicy(final Path src, final String policyName)
      throws IOException {
    dfs.setStoragePolicy(src, policyName);
  }

  /**
   * Unset the storage policy set for a given file or directory.
   *
   * @param src file or directory path.
   * @throws IOException
   */
  public void unsetStoragePolicy(final Path src) throws IOException {
    dfs.unsetStoragePolicy(src);
  }

  /**
   * Query the effective storage policy ID for the given file or directory.
   *
   * @param src file or directory path.
   * @return storage policy for the given file or directory.
   * @throws IOException
   */
  public BlockStoragePolicySpi getStoragePolicy(final Path src)
      throws IOException {
    return dfs.getStoragePolicy(src);
  }

  /**
   * Retrieve all the storage policies supported by HDFS file system.
   *
   * @return all storage policies supported by HDFS file system.
   * @throws IOException
   */
  public Collection<? extends BlockStoragePolicySpi> getAllStoragePolicies()
      throws IOException {
    return dfs.getAllStoragePolicies();
  }

  /**
   * Set the source path to the specified erasure coding policy.
   *
   * @param path The source path referring to a directory.
   * @param ecPolicyName The erasure coding policy name for the directory.
   *
   * @throws IOException
   * @throws HadoopIllegalArgumentException if the specified EC policy is not
   * enabled on the cluster
   */
  public void setErasureCodingPolicy(final Path path,
      final String ecPolicyName) throws IOException {
    dfs.setErasureCodingPolicy(path, ecPolicyName);
  }

  /**
   * Get the erasure coding policy information for the specified path
   *
   * @param path
   * @return Returns the policy information if file or directory on the path is
   *          erasure coded. Null otherwise.
   * @throws IOException
   */
  public ErasureCodingPolicy getErasureCodingPolicy(final Path path)
      throws IOException {
    return dfs.getErasureCodingPolicy(path);
  }

  /**
   * Set the source path to the specified storage policy.
   *
   * @param path The source path referring to either a directory or a file.
   * @throws IOException
   */
  public void satisfyStoragePolicy(final Path path) throws IOException {
    dfs.satisfyStoragePolicy(path);
  }

  /**
   * Get the Erasure coding policies supported.
   *
   * @throws IOException
   */
  public ErasureCodingPolicyInfo[] getErasureCodingPolicies()
      throws IOException {
    return dfs.getClient().getErasureCodingPolicies();
  }

  /**
   * Unset erasure coding policy from the directory.
   *
   * @param path The source path referring to a directory.
   * @throws IOException
   */
  public void unsetErasureCodingPolicy(final Path path) throws IOException {
    dfs.unsetErasureCodingPolicy(path);
  }

  /**
   * Add Erasure coding policies to HDFS. For each policy input, schema and
   * cellSize are musts, name and id are ignored. They will be automatically
   * created and assigned by Namenode once the policy is successfully added,
   * and will be returned in the response; policy states will be set to
   * DISABLED automatically.
   *
   * @param policies The user defined ec policy list to add.
   * @return Return the response list of adding operations.
   * @throws IOException
   */
  public AddErasureCodingPolicyResponse[] addErasureCodingPolicies(
      ErasureCodingPolicy[] policies)  throws IOException {
    return dfs.addErasureCodingPolicies(policies);
  }

  /**
   * Remove erasure coding policy.
   *
   * @param ecPolicyName The name of the policy to be removed.
   * @throws IOException
   */
  public void removeErasureCodingPolicy(String ecPolicyName)
      throws IOException {
    dfs.removeErasureCodingPolicy(ecPolicyName);
  }

  /**
   * Enable erasure coding policy.
   *
   * @param ecPolicyName The name of the policy to be enabled.
   * @throws IOException
   */
  public void enableErasureCodingPolicy(String ecPolicyName)
      throws IOException {
    dfs.enableErasureCodingPolicy(ecPolicyName);
  }

  /**
   * Disable erasure coding policy.
   *
   * @param ecPolicyName The name of the policy to be disabled.
   * @throws IOException
   */
  public void disableErasureCodingPolicy(String ecPolicyName)
      throws IOException {
    dfs.disableErasureCodingPolicy(ecPolicyName);
  }

  /**
   * Returns a RemoteIterator which can be used to list all open files
   * currently managed by the NameNode. For large numbers of open files,
   * iterator will fetch the list in batches of configured size.
   *

   * Since the list is fetched in batches, it does not represent a
   * consistent snapshot of the all open files.
   *

   * This method can only be called by HDFS superusers.
   */
  @Deprecated
  public RemoteIterator<OpenFileEntry> listOpenFiles() throws IOException {
    return dfs.listOpenFiles();
  }

  public RemoteIterator<OpenFileEntry> listOpenFiles(
      EnumSet<OpenFilesType> openFilesTypes, String path) throws IOException {
    return dfs.listOpenFiles(openFilesTypes, path);
  }

}


text:
import 'rxjs/add/operator/finally';

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { environment } from '../../environments/environment';
import { Logger } from '../core/logger.service';
import { I18nService } from '../core/i18n.service';
import { AuthenticationService } from '../core/authentication/authentication.service';

const log = new Logger('Login');

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  version: string = environment.version;
  error: string = null;
  loginForm: FormGroup;
  isLoading = false;

  constructor(private router: Router,
              private formBuilder: FormBuilder,
              private i18nService: I18nService,
              private authenticationService: AuthenticationService) {
    this.createForm();
  }

  ngOnInit() { }

  login() {
    this.isLoading = true;
    this.authenticationService.login(this.loginForm.value)
      .finally(() => {
        this.loginForm.markAsPristine();
        this.isLoading = false;
      })
      .subscribe(credentials => {
        log.debug(`${credentials.username} successfully logged in`);
        this.router.navigate(['/'], { replaceUrl: true });
      }, error => {
        log.debug(`Login error: ${error}`);
        this.error = error;
      });
  }

  setLanguage(language: string) {
    this.i18nService.language = language;
  }

  get currentLanguage(): string {
    return this.i18nService.language;
  }

  get languages(): string[] {
    return this.i18nService.supportedLanguages;
  }

  private createForm() {
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      remember: true
    });
  }

}


text:
<?php
namespace Asar\Utility\Cli;
/**
 */
class Command {

  private
    $caller,
    $namespace,
    $command,
    $flags = array(),
    $arguments = array();

  function __construct(array $options = array()) {
    foreach (
      array('caller', 'command', 'namespace', 'flags', 'arguments') as $type
    ) {
      $this->setOption($type, $options);
    }
  }

  function setOption($type, $options) {
    if (isset($options[$type])) {
      $this->$type = $options[$type];
    }
  }

  function getCaller() {
    return $this->caller;
  }

  function getNamespace() {
    return $this->namespace;
  }

  function getCommand() {
    return $this->command;
  }

  function getFlags() {
    return $this->flags;
  }

  function getArguments() {
    return $this->arguments;
  }

}


text:
/**
 * @file
 * @brief Embox Framebuffer plugin
 *
 * @date 15.06.2019
 * @author Alexander Kalmuk
 */

#include "qgenericunixfontdatabase.h"
#include <QtGui/private/qpixmap_raster_p.h>
#include <qimage.h>
#include "emboxfbintegration.h"

#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include <linux/fb.h>

#define DPRINTF(fmt, ...) \
    do { \
        fprintf(stderr, "> QEmboxFB: " fmt, ## __VA_ARGS__); \
    } while (0)

void QEmboxFbIntegration::printFbInfo(void)
{
	DPRINTF("Framebuffer info:\n");
	DPRINTF("  Framebuffer start = 0x%x\n", (unsigned int) fbData);
	DPRINTF("  Width = %d, Height = %d\n", fbWidth, fbHeight);
	DPRINTF("  BytesPerLine = %d\n", fbBytesPerLine);
	DPRINTF("  Format = %d\n", fbFormat);
	DPRINTF("\n");
}

QEmboxFbIntegration::QEmboxFbIntegration()
	: fontDb(new QGenericUnixFontDatabase())
{
	struct fb_var_screeninfo vinfo;
	struct fb_fix_screeninfo finfo;
	const char *fbPath = "/dev/fb0";

	fbFd = open(fbPath, O_RDWR);
	if (fbFd < 0) {
		qFatal("QEmboxFbIntegration: Error open framebuffer %s", fbPath);
	}
	if (ioctl(fbFd, FBIOGET_FSCREENINFO, &finfo) == -1) {
		qFatal("QEmboxFbIntegration: Error ioctl framebuffer %s", fbPath);
	}
	if (ioctl(fbFd, FBIOGET_VSCREENINFO, &vinfo) == -1) {
		qFatal("QEmboxFbIntegration: Error ioctl framebuffer %s", fbPath);
	}
	fbWidth        = vinfo.xres;
	fbHeight       = vinfo.yres;
	fbBytesPerLine = finfo.line_length;
	fbSize         = fbBytesPerLine * fbHeight;
	fbFormat       = vinfo.fmt;
	fbData = (uint8_t *)mmap(0, fbSize, PROT_READ | PROT_WRITE,
				             MAP_SHARED, fbFd, 0);
	if (fbData == MAP_FAILED) {
		qFatal("QEmboxFbIntegration: Error mmap framebuffer %s", fbPath);
	}
	if (!fbData || !fbSize) {
		qFatal("QEmboxFbIntegration: Wrong framebuffer: base = %p,"
			   "size=%d", fbData, fbSize);
	}

	mPrimaryScreen = new QEmboxFbScreen(fbData, fbWidth,
							            fbHeight, fbBytesPerLine,
							            emboxFbFormatToQImageFormat(fbFormat));

	mPrimaryScreen->setPhysicalSize(QSize(fbWidth, fbHeight));
	mScreens.append(mPrimaryScreen);

	this->printFbInfo();
}

QEmboxFbIntegration::~QEmboxFbIntegration()
{
	delete mPrimaryScreen;
}

FbFormat QEmboxFbIntegration::emboxFbFormatToQImageFormat(
	int emboxFbFormat)
{
	FbFormat format;

	format.format = QImage::Format_Invalid;
	format.swapRgb = 0;

	switch (emboxFbFormat) {
	case EMBOX_BGR888:
		format.swapRgb = 1;
	case EMBOX_RGB888:
		format.format =  QImage::Format_RGB888;
		break;
	case EMBOX_BGRA8888:
		format.swapRgb = 1;
	case EMBOX_RGBA8888:
		format.format = QImage::Format_ARGB32;
		break;
	case EMBOX_BGR565:
		format.swapRgb = 1;
	case EMBOX_RGB565:
		format.format = QImage::Format_RGB16;
		break;
	default:
		qFatal("QEmboxFbIntegration: Unknown framebuffer format %d",
			emboxFbFormat);
		break;
	}
	return format;
}

bool QEmboxFbIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
	switch (cap) {
	case ThreadedPixmaps:
		return true;
	default:
		return QPlatformIntegration::hasCapability(cap);
	}
}

QPixmapData *QEmboxFbIntegration::createPixmapData(QPixmapData::PixelType type) const
{
	return new QRasterPixmapData(type);
}

QPlatformWindow *QEmboxFbIntegration::createPlatformWindow(QWidget *widget, WId winId) const
{
	Q_UNUSED(winId);
	QFbWindow *w = new QFbWindow(widget);
	mPrimaryScreen->addWindow(w);
	return w;
}

QWindowSurface *QEmboxFbIntegration::createWindowSurface(QWidget *widget, WId winId) const
{
	Q_UNUSED(winId);
	return new QFbWindowSurface(mPrimaryScreen, widget);
}

QPlatformFontDatabase *QEmboxFbIntegration::fontDatabase() const
{
	return fontDb;
}

QEmboxFbScreen::QEmboxFbScreen(uint8_t *data, int width,
	int height, int bytesPerLine,
	FbFormat format) : compositePainter(0)
{
	mData         = data;
	mGeometry     = QRect(0, 0, width, height);
	mBytesPerLine = bytesPerLine;
	mFormat       = format.format;
	mSwapRgb      = format.swapRgb;
	mDepth        = 16;

	mScreenImage = new QImage(mGeometry.width(), mGeometry.height(), mFormat);
	mFbScreenImage = new QImage(mData, mGeometry.width(), mGeometry.height(),
						        mBytesPerLine, mFormat);
#ifndef QT_NO_CURSOR
    cursor = new QPlatformSoftwareCursor(this);
#endif
}

void QEmboxFbScreen::setGeometry(QRect rect)
{
	mGeometry = rect;

	delete mFbScreenImage;
	mFbScreenImage = new QImage(mData, mGeometry.width(), mGeometry.height(),
						        mBytesPerLine, mFormat);
	delete compositePainter;
	compositePainter = 0;
	delete mScreenImage;
	mScreenImage = new QImage(mGeometry.width(), mGeometry.height(),
					          mFormat);
}

void QEmboxFbScreen::setFormat(QImage::Format format)
{
	mFormat = format;

	delete mFbScreenImage;
	mFbScreenImage = new QImage(mData, mGeometry.width(), mGeometry.height(),
						        mBytesPerLine, mFormat);
	delete compositePainter;
	compositePainter = 0;
	delete mScreenImage;
	mScreenImage = new QImage(mGeometry.width(), mGeometry.height(),
						      mFormat);
}

QRegion QEmboxFbScreen::doRedraw()
{
	QVector<QRect> rects;
	QRegion touched = QFbScreen::doRedraw();

	if (!compositePainter) {
		compositePainter = new QPainter(mFbScreenImage);
	}

	rects = touched.rects();
	if (mSwapRgb) {
		for (int i = 0; i < rects.size(); i++) {
			compositePainter->drawImage(rects[i], mScreenImage->rgbSwapped(), rects[i]);
			}
	} else {
		for (int i = 0; i < rects.size(); i++) {
			compositePainter->drawImage(rects[i], *mScreenImage, rects[i]);
		}
	}
	return touched;
}


text:
using Heroes.Icons;
using HeroesMatchTracker.Data.Models.Replays;
using HeroesMatchTracker.Data.Queries.Replays;

namespace HeroesMatchTracker.Core.ViewModels.RawData
{
    public class RawMatchPlayerTalentViewModel : RawDataViewModelBase<ReplayMatchPlayerTalent>
    {
        public RawMatchPlayerTalentViewModel(IRawDataQueries<ReplayMatchPlayerTalent> iRawDataQueries, IHeroesIcons heroesIcons)
            : base(iRawDataQueries, heroesIcons)
        { }
    }
}


text:
#include "simpletest.hpp"
#include "fudge-cpp/exception.hpp"
#include "fudge-cpp/codec.hpp"
#include "fudge/codec.h"
#include "fudge/message.h"
#include <stdio.h>

// Example user types
namespace
{
    static const fudge_type_id FUDGE_TYPE_EXAMPLEIP4  = 100,
                               FUDGE_TYPE_EXAMPLETICK = 101;

    class ExampleIp4
    {
        public:
            ExampleIp4 ( uint8_t first, uint8_t second, uint8_t third, uint8_t fourth )
            {
                quads [ 0 ] = first;
                quads [ 1 ] = second;
                quads [ 2 ] = third;
                quads [ 3 ] = fourth;
            }

            uint8_t quads [ 4 ];

            static void addField ( fudge::message & message,
                                   const fudge::string & name,
                                   const ExampleIp4 & ip )
            {
                fudge::exception::throwOnError ( FudgeMsg_addFieldOpaque (
                            message.raw ( ),
                            FUDGE_TYPE_EXAMPLEIP4,
                            name.raw ( ),
                            0,
                            reinterpret_cast<const fudge_byte *> ( &ip ),
                            sizeof ( ExampleIp4 ) ) );
            }

            static FudgeStatus coerceField ( const FudgeField * source,
                                             const fudge_type_id type,
                                             FudgeFieldData * target,
                                             fudge_i32 * numbytes )
            {
                if ( ! ( source && target && numbytes ) )
                    return FUDGE_NULL_POINTER;
                if ( source->type == type )
                    return FUDGE_COERCION_NOT_REQUIRED;

                // For test purposes, only a string conversion is supported
                if ( type == FUDGE_TYPE_STRING )
                {
                    const ExampleIp4 * ip4 = reinterpret_cast<const ExampleIp4 *> ( source->data.bytes );

                    char buffer [ 16 ];
                    sprintf ( buffer, "%03d.%03d.%03d.%03d", ip4->quads [ 0 ], ip4->quads [ 1 ], ip4->quads [ 2 ], ip4->quads [ 3 ] );

                    FudgeStatus status = FudgeString_createFromASCIIZ ( &( target->string ), buffer );
                    if ( status != FUDGE_OK )
                        return status;

                    *numbytes = FudgeString_getSize ( target->string );
                    return FUDGE_OK;
                }
                return FUDGE_INVALID_TYPE_COERCION;
            }
    };

    class ExampleTick
    {
        public:
            ExampleTick ( const std::string & ric_, fudge_f32 bid_, fudge_f32 ask_, fudge_i32 time_ )
            {
                memcpy ( ric, ric_.c_str ( ), ric_.size ( ) < 15 ? ric_.size ( ) + 1 : 16 );
                bid = bid_;
                ask = ask_;
                time = time_;
            }

            char ric [ 16 ];
            fudge_f32 bid, ask;
            fudge_i32 time;

            fudge::string getRic ( ) const
            {
                return fudge::string ( ric );
            }

            static void addField ( fudge::message & message,
                                   const fudge::string & name,
                                   const ExampleTick & tick )
            {
                fudge::exception::throwOnError ( FudgeMsg_addFieldOpaque
                        ( message.raw ( ),
                          FUDGE_TYPE_EXAMPLETICK,
                          name.raw ( ),
                          0,
                          reinterpret_cast<const fudge_byte *> ( &tick ),
                          sizeof ( ExampleTick ) ) );
            }

            static FudgeStatus coerceField ( const FudgeField * source,
                                             const fudge_type_id type,
                                             FudgeFieldData * target,
                                             fudge_i32 * numbytes )
            {
                if ( ! ( source && target && numbytes ) )
                    return FUDGE_NULL_POINTER;
                if ( source->type == type )
                    return FUDGE_COERCION_NOT_REQUIRED;

                // For test purposes, only a string conversion is supported
                if ( type == FUDGE_TYPE_STRING )
                {
                    const ExampleTick * tick = reinterpret_cast<const ExampleTick *> ( source->data.bytes );

                    char buffer [ 52 ];
                    sprintf ( buffer, "%16s %8f %8f %16d", tick->ric, tick->bid, tick->ask, tick->time );

                    FudgeStatus status = FudgeString_createFromASCIIZ ( &( target->string ), buffer );
                    if ( status != FUDGE_OK )
                        return status;

                    *numbytes = FudgeString_getSize ( target->string );
                    return FUDGE_OK;
                }
                return FUDGE_INVALID_TYPE_COERCION;
            }

            static FudgeStatus encodeField ( const FudgeField * field, fudge_byte * * data )
            {
                const ExampleTick * tick = reinterpret_cast<const ExampleTick *> ( field->data.bytes );

                FudgeCodec_encodeFieldLength ( field->numbytes, data );

                // Write the RIC - as the string is of fixed length, a fixed
                // width field can be used
                FudgeCodec_encodeByteArray ( reinterpret_cast<const fudge_byte *> ( tick->ric ), 16, FUDGE_TRUE, data );

                // Write the float and integer values - this will perform the
                // necessary endian conversions
                FudgeCodec_encodeF32 ( tick->bid, data );
                FudgeCodec_encodeF32 ( tick->ask, data );
                FudgeCodec_encodeI32 ( tick->time, data );
                return FUDGE_OK;
            }

            static FudgeStatus decodeField ( const fudge_byte * bytes, const fudge_i32 width, FudgeFieldData * data )
            {
                // Make sure that the width in the header matches that of
                // the target structure
                if ( width != sizeof ( ExampleTick ) )
                    return FUDGE_OUT_OF_BYTES;

                // Allocate the target structure and point the data
                // structure's bytes pointer at it: use malloc rather than
                // new as the reference counter will destroy it with free
                ExampleTick * tick = reinterpret_cast<ExampleTick *> ( malloc ( width ) );
                if ( ! tick )
                    return FUDGE_OUT_OF_MEMORY;
                data->bytes = reinterpret_cast<const fudge_byte *> ( tick );

                // Copy in the string component and advance the source pointer
                memcpy ( tick->ric, bytes, 16 );
                bytes += 16;

                // Copy in the float/integer values: advancing the source
                // pointer after each one
                tick->bid = FudgeCodec_decodeF32 ( bytes );     bytes += sizeof ( fudge_f32 );
                tick->ask = FudgeCodec_decodeF32 ( bytes );     bytes += sizeof ( fudge_f32 );
                tick->time = FudgeCodec_decodeI32 ( bytes );    bytes += sizeof ( fudge_i32 );
                return FUDGE_OK;
            }
    };
}

DEFINE_TEST( UserTypeHandling )
    using fudge::codec;
    using fudge::envelope;
    using fudge::field;
    using fudge::message;
    using fudge::string;

    // Populate test objects and arrays
    fudge_byte bytes [ 16 ];
    for ( size_t index ( 0 ); index < sizeof ( bytes ); ++index )
        bytes [ index ] = index;

    ExampleIp4 localhost ( 127, 0, 0, 1 );
    ExampleIp4 opendns ( 208, 67, 222, 222 );
    ExampleTick tick ( "GBP=", 1.605, 1.607, 1263138018u );

    // Fail to register user types
    TEST_EQUALS_INT( FudgeRegistry_registerType ( FUDGE_TYPE_EXAMPLEIP4,
                                                  FUDGE_TYPE_PAYLOAD_LOCAL, // User types must have a bytes payload!
                                                  FudgeCodec_decodeFieldByteArray,
                                                  FudgeCodec_encodeFieldByteArray,
                                                  ExampleIp4::coerceField ), FUDGE_INVALID_USER_TYPE );

    TEST_EQUALS_INT( FudgeRegistry_registerType ( FUDGE_TYPE_EXAMPLEIP4,
                                                  FUDGE_TYPE_PAYLOAD_BYTES,
                                                  FudgeCodec_decodeFieldByteArray,
                                                  0,    // Cannot have a null pointer as an encoder function!
                                                  ExampleIp4::coerceField ), FUDGE_NULL_POINTER );

    // Register user types
    TEST_EQUALS_INT( FudgeRegistry_registerType ( FUDGE_TYPE_EXAMPLEIP4,
                                                  FUDGE_TYPE_PAYLOAD_BYTES,
                                                  FudgeCodec_decodeFieldByteArray,
                                                  FudgeCodec_encodeFieldByteArray,
                                                  ExampleIp4::coerceField ), FUDGE_OK );

    TEST_EQUALS_INT( FudgeRegistry_registerType ( FUDGE_TYPE_EXAMPLETICK,
                                                  FUDGE_TYPE_PAYLOAD_BYTES,
                                                  ExampleTick::decodeField,
                                                  ExampleTick::encodeField,
                                                  ExampleTick::coerceField ), FUDGE_OK );

    // Construct a test message with user and built-in types
    message message1;
    message1.addField ( static_cast<fudge_i64> ( 2147483648ll ), string ( "bigint" ) );
    ExampleIp4::addField ( message1, string ( "localhost" ), localhost );
    ExampleIp4::addField ( message1, string ( "opendns" ), opendns );
    ExampleTick::addField ( message1, string ( "tick" ), tick );
    message1.addField16ByteArray ( bytes, string ( "byte[16]" ) );

    TEST_EQUALS_INT( message1.size ( ), 5 );

    // Encode the test message and clear the message container
    envelope envelope1 ( 0, 0, 0, message1 );
    fudge_byte * encoded;
    fudge_i32 encodedsize;
    codec codec1;
    TEST_THROWS_NOTHING( codec1.encode ( envelope1, encoded, encodedsize ) );
    message1 = message ( );
    envelope1 = envelope ( );

    // Decode the test message and clear the encoded form
    envelope1 = codec1.decode ( encoded, encodedsize );
    message1 = envelope1.payload ( );
    free ( encoded );

    TEST_EQUALS_INT( message1.size ( ), 5 );

    // Retrieve and check the decoded fields
    field field1 = message1.getField ( string ( "bigint" ) );
    TEST_EQUALS_INT( field1.type ( ), FUDGE_TYPE_LONG );
    TEST_EQUALS_INT( field1.getInt64 ( ), 2147483648ll );

    field1 = message1.getField ( string ( "byte[16]" ) );
    TEST_EQUALS_INT( field1.type ( ), FUDGE_TYPE_BYTE_ARRAY_16 );
    TEST_EQUALS_MEMORY( field1.bytes ( ), field1.numbytes ( ), bytes, sizeof ( bytes ) );

    field1 = message1.getField ( string ( "localhost" ) );
    TEST_EQUALS_INT( field1.type ( ), FUDGE_TYPE_EXAMPLEIP4 );
    TEST_EQUALS_MEMORY( field1.bytes ( ), field1.numbytes ( ), reinterpret_cast<const fudge_byte *> ( &localhost ), sizeof ( ExampleIp4 ) );

    FudgeFieldData fielddata;
    FudgeTypePayload payload;
    fudge_i32 numbytes;
    TEST_EQUALS_INT( FudgeMsg_getFieldAs ( &( field1.raw ( ) ), FUDGE_TYPE_EXAMPLEIP4, &fielddata, &payload, &numbytes ), FUDGE_COERCION_NOT_REQUIRED );
    TEST_EQUALS_INT( FudgeMsg_getFieldAs ( &( field1.raw ( ) ), FUDGE_TYPE_FUDGE_MSG,  &fielddata, &payload, &numbytes ), FUDGE_INVALID_TYPE_COERCION );
    TEST_THROWS_EXCEPTION( field1.getAsInt16 ( ), std::runtime_error );

    string string1 = field1.getAsString ( );
    TEST_EQUALS_TRUE( string1 == string ( "127.000.000.001" ) );

    field1 = message1.getField ( string ( "opendns" ) );
    TEST_EQUALS_INT( field1.type ( ), FUDGE_TYPE_EXAMPLEIP4 );
    TEST_EQUALS_MEMORY( field1.bytes ( ), field1.numbytes ( ), reinterpret_cast<const fudge_byte *> ( &opendns ), sizeof ( ExampleIp4 ) );

    string1 = field1.getAsString ( );
    TEST_EQUALS_TRUE( string1 == string ( "208.067.222.222" ) );

    field1 = message1.getField ( string ( "tick" ) );
    TEST_EQUALS_INT( field1.type ( ), FUDGE_TYPE_EXAMPLETICK );
    TEST_EQUALS_INT( field1.numbytes ( ), sizeof ( ExampleTick ) );
    const ExampleTick * fieldtick = reinterpret_cast<const ExampleTick *> ( field1.bytes ( ) );
    TEST_EQUALS_TRUE( fieldtick->getRic ( ) == tick.getRic ( ) );
    TEST_EQUALS_FLOAT( fieldtick->bid, tick.bid, 0.0001 );
    TEST_EQUALS_FLOAT( fieldtick->ask, tick.ask, 0.0001 );
    TEST_EQUALS_INT( fieldtick->time, tick.time );

    string1 = field1.getAsString ( );
    TEST_EQUALS_TRUE( string1 == string ( "            GBP= 1.605000 1.607000       1263138018" ) );
END_TEST

DEFINE_TEST_SUITE( UserTypes )
    REGISTER_TEST( UserTypeHandling )
END_TEST_SUITE