text:
/* eslint camelcase: 0 */
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  ensureIsArray,
  t,
  styled,
  getChartControlPanelRegistry,
  QueryFormData,
  DatasourceType,
  css,
} from '@superset-ui/core';
import {
  ControlPanelSectionConfig,
  ControlState,
  CustomControlItem,
  DatasourceMeta,
  ExpandedControlItem,
  InfoTooltipWithTrigger,
  sections,
} from '@superset-ui/chart-controls';

import Collapse from 'src/components/Collapse';
import Tabs from 'src/components/Tabs';
import { PluginContext } from 'src/components/DynamicPlugins';
import Loading from 'src/components/Loading';

import { getSectionsToRender } from 'src/explore/controlUtils';
import {
  ExploreActions,
  exploreActions,
} from 'src/explore/actions/exploreActions';
import { ExplorePageState } from 'src/explore/reducers/getInitialState';
import { ChartState } from 'src/explore/types';

import ControlRow from './ControlRow';
import Control from './Control';

export type ControlPanelsContainerProps = {
  actions: ExploreActions;
  datasource_type: DatasourceType;
  exploreState: ExplorePageState['explore'];
  chart: ChartState;
  controls: Record<string, ControlState>;
  form_data: QueryFormData;
  isDatasourceMetaLoading: boolean;
};

export type ExpandedControlPanelSectionConfig = Omit<
  ControlPanelSectionConfig,
  'controlSetRows'
> & {
  controlSetRows: ExpandedControlItem[][];
};

const Styles = styled.div`
  height: 100%;
  width: 100%;
  overflow: auto;
  overflow-x: visible;
  overflow-y: auto;
  #controlSections {
    min-height: 100%;
    overflow: visible;
  }
  .nav-tabs {
    flex: 0 0 1;
  }
  .tab-content {
    overflow: auto;
    flex: 1 1 100%;
  }
  .Select__menu {
    max-width: 100%;
  }
  .type-label {
    margin-right: ${({ theme }) => theme.gridUnit * 3}px;
    width: ${({ theme }) => theme.gridUnit * 7}px;
    display: inline-block;
    text-align: center;
    font-weight: ${({ theme }) => theme.typography.weights.bold};
  }
`;

const ControlPanelsTabs = styled(Tabs)`
  .ant-tabs-nav-list {
    width: ${({ fullWidth }) => (fullWidth ? '100%' : '50%')};
  }
  .ant-tabs-content-holder {
    overflow: visible;
  }
  .ant-tabs-tabpane {
    height: 100%;
  }
`;

type ControlPanelsContainerState = {
  expandedQuerySections: string[];
  expandedCustomizeSections: string[];
  querySections: ControlPanelSectionConfig[];
  customizeSections: ControlPanelSectionConfig[];
  loading: boolean;
};

const isTimeSection = (section: ControlPanelSectionConfig): boolean =>
  !!section.label &&
  (sections.legacyRegularTime.label === section.label ||
    sections.legacyTimeseriesTime.label === section.label);

const hasTimeColumn = (datasource: DatasourceMeta): boolean =>
  datasource?.columns?.some(c => c.is_dttm) ||
  datasource.type === DatasourceType.Druid;

const sectionsToExpand = (
  sections: ControlPanelSectionConfig[],
  datasource: DatasourceMeta,
): string[] =>
  // avoid expanding time section if datasource doesn't include time column
  sections.reduce(
    (acc, section) =>
      section.expanded && (!isTimeSection(section) || hasTimeColumn(datasource))
        ? [...acc, String(section.label)]
        : acc,
    [] as string[],
  );

function getState(
  props: ControlPanelsContainerProps,
): ControlPanelsContainerState {
  const {
    exploreState: { datasource },
  } = props;

  const querySections: ControlPanelSectionConfig[] = [];
  const customizeSections: ControlPanelSectionConfig[] = [];

  getSectionsToRender(props.form_data.viz_type, props.datasource_type).forEach(
    section => {
      // if at least one control in the section is not `renderTrigger`
      // or asks to be displayed at the Data tab
      if (
        section.tabOverride === 'data' ||
        section.controlSetRows.some(rows =>
          rows.some(
            control =>
              control &&
              typeof control === 'object' &&
              'config' in control &&
              control.config &&
              (!control.config.renderTrigger ||
                control.config.tabOverride === 'data'),
          ),
        )
      ) {
        querySections.push(section);
      } else {
        customizeSections.push(section);
      }
    },
  );
  const expandedQuerySections: string[] = sectionsToExpand(
    querySections,
    datasource,
  );
  const expandedCustomizeSections: string[] = sectionsToExpand(
    customizeSections,
    datasource,
  );
  return {
    expandedQuerySections,
    expandedCustomizeSections,
    querySections,
    customizeSections,
    loading: false,
  };
}

export class ControlPanelsContainer extends React.Component<
  ControlPanelsContainerProps,
  ControlPanelsContainerState
> {
  // trigger updates to the component when async plugins load
  static contextType = PluginContext;

  constructor(props: ControlPanelsContainerProps) {
    super(props);
    this.state = {
      expandedQuerySections: [],
      expandedCustomizeSections: [],
      querySections: [],
      customizeSections: [],
      loading: false,
    };
    this.renderControl = this.renderControl.bind(this);
    this.renderControlPanelSection = this.renderControlPanelSection.bind(this);
  }

  componentDidUpdate(prevProps: ControlPanelsContainerProps) {
    if (
      this.props.form_data.datasource !== prevProps.form_data.datasource ||
      this.props.form_data.viz_type !== prevProps.form_data.viz_type
    ) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState(getState(this.props));
    }
  }

  // required for an Antd bug that would otherwise malfunction re-rendering
  // a collapsed panel after changing the datasource or viz type
  UNSAFE_componentWillReceiveProps(nextProps: ControlPanelsContainerProps) {
    if (
      this.props.form_data.datasource !== nextProps.form_data.datasource ||
      this.props.form_data.viz_type !== nextProps.form_data.viz_type
    ) {
      this.setState({ loading: true });
    }
  }

  componentDidMount() {
    this.setState(getState(this.props));
  }

  renderControl({ name, config }: CustomControlItem) {
    const { actions, controls, chart, exploreState } = this.props;
    const { visibility } = config;

    // If the control item is not an object, we have to look up the control data from
    // the centralized controls file.
    // When it is an object we read control data straight from `config` instead
    const controlData = {
      ...config,
      ...controls[name],
      // if `mapStateToProps` accept three arguments, it means it needs chart
      // state, too. Since it's may be expensive to run mapStateToProps for every
      // re-render, we only run this when the chart plugin explicitly ask for this.
      ...(config.mapStateToProps?.length === 3
        ? // @ts-ignore /* The typing accuses of having an extra parameter. I didn't remove it because I believe it could be an error in the types and not in the code */
          config.mapStateToProps(exploreState, controls[name], chart)
        : // for other controls, `mapStateToProps` is already run in
          // controlUtils/getControlState.ts
          undefined),
      name,
    };
    const { validationErrors, ...restProps } = controlData as ControlState & {
      validationErrors?: any[];
    };

    // if visibility check says the config is not visible, don't render it
    if (visibility && !visibility.call(config, this.props, controlData)) {
      return null;
    }
    return (
      <Control
        key={`control-${name}`}
        name={name}
        validationErrors={validationErrors}
        actions={actions}
        {...restProps}
      />
    );
  }

  renderControlPanelSection(section: ExpandedControlPanelSectionConfig) {
    const { controls } = this.props;
    const { label, description } = section;

    // Section label can be a ReactNode but in some places we want to
    // have a string ID. Using forced type conversion for now,
    // should probably add a `id` field to sections in the future.
    const sectionId = String(label);

    const hasErrors = section.controlSetRows.some(rows =>
      rows.some(item => {
        const controlName =
          typeof item === 'string'
            ? item
            : item && 'name' in item
            ? item.name
            : null;
        return (
          controlName &&
          controlName in controls &&
          controls[controlName].validationErrors &&
          controls[controlName].validationErrors.length > 0
        );
      }),
    );
    const PanelHeader = () => (

        {label}{' '}
        {description && (
          // label is only used in tooltip id (should probably call this prop `id`)
          <InfoTooltipWithTrigger label={sectionId} tooltip={description} />
        )}
        {hasErrors && (
          <InfoTooltipWithTrigger
            label="validation-errors"
            bsStyle="danger"
            tooltip="This section contains validation errors"
          />
        )}

    );

    return (
      <Collapse.Panel
        data-test="collapsible-control-panel"
        css={theme => css`
          margin-bottom: 0;
          box-shadow: none;

          &:last-child {
            padding-bottom: ${theme.gridUnit * 10}px;
          }

          .panel-body {
            margin-left: ${theme.gridUnit * 4}px;
            padding-bottom: 0px;
          }

          span.label {
            display: inline-block;
          }
        `}
        header={PanelHeader()}
        key={sectionId}
      >
        {section.controlSetRows.map((controlSets, i) => {
          const renderedControls = controlSets
            .map(controlItem => {
              if (!controlItem) {
                // When the item is invalid
                return null;
              }
              if (React.isValidElement(controlItem)) {
                // When the item is a React element
                return controlItem;
              }
              if (
                controlItem.name &&
                controlItem.config &&
                controlItem.name !== 'datasource'
              ) {
                return this.renderControl(controlItem);
              }
              return null;
            })
            .filter(x => x !== null);
          // don't show the row if it is empty
          if (renderedControls.length === 0) {
            return null;
          }
          return (
            <ControlRow
              key={`controlsetrow-${i}`}
              controls={renderedControls}
            />
          );
        })}
      </Collapse.Panel>
    );
  }

  render() {
    const controlPanelRegistry = getChartControlPanelRegistry();
    if (
      (!controlPanelRegistry.has(this.props.form_data.viz_type) &&
        this.context.loading) ||
      this.state.loading
    ) {
      return <Loading />;
    }

    const showCustomizeTab = this.state.customizeSections.length > 0;
    return (

    );
  }
}

export default connect(
  function mapStateToProps(state: ExplorePageState) {
    const { explore, charts } = state;
    const chartKey = Object.keys(charts)[0];
    const chart = charts[chartKey];
    return {
      chart,
      isDatasourceMetaLoading: explore.isDatasourceMetaLoading,
      controls: explore.controls,
      exploreState: explore,
    };
  },
  function mapDispatchToProps(dispatch) {
    return {
      actions: bindActionCreators(exploreActions, dispatch),
    };
  },
)(ControlPanelsContainer);


text:
module Puppet.Language.NativeTypes.File (nativeFile) where

import qualified Data.Attoparsec.Text                as AT
import qualified Data.Char                           as Char
import qualified Data.Map.Strict                     as Map
import qualified Data.Set                            as Set
import qualified Data.Text                           as Text

import           Puppet.Language.NativeTypes.Helpers

nativeFile :: (NativeTypeName, NativeTypeMethods)
nativeFile = ("file", nativetypemethods parameterfunctions (validateSourceOrContent >=> validateMode))

-- Autorequires: If Puppet is managing the user or group that owns a file, the file resource will autorequire them. If Puppet is managing any parent directories of a file, the file resource will autorequire them.

parameterfunctions :: [(Text, [Text -> NativeTypeValidate])]
parameterfunctions =
    [("backup"               , [string])
    ,("checksum"             , [values ["md5", "md5lite", "mtime", "ctime", "none"]])
    ,("content"              , [string])
    --,("ensure"               , [defaultvalue "present", string, values ["directory","file","present","absent","link"]])
    ,("ensure"               , [defaultvalue "present", string])
    ,("force"                , [string, values ["true","false"]])
    ,("group"                , [defaultvalue "root", string])
    ,("ignore"               , [strings])
    ,("links"                , [string])
    ,("mode"                 , [defaultvalue "0644", string])
    ,("owner"                , [string])
    ,("path"                 , [nameval, fullyQualified, noTrailingSlash'])
    ,("provider"             , [values ["posix","windows"]])
    ,("purge"                , [string, values ["true","false"]])
    ,("recurse"              , [string, values ["inf","true","false","remote"]])
    ,("recurselimit"         , [integer])
    ,("replace"              , [string, values ["true","false","yes","no"]])
    ,("show_diff"            , [string, values ["true","false"]])
    ,("sourceselect"         , [values ["first","all"]])
    ,("seltype"              , [string])
    ,("selrange"             , [string])
    ,("selinux_ignore_defaults", [string, values ["true","false"]])
    ,("selrole"              , [string])
    ,("target"               , [string])
    ,("source"               , [rarray, strings, flip runarray checkSource])
    ,("seluser"              , [string])
    ,("validate_cmd"         , [string])
    ,("validate_replacement" , [string])
    ]

noTrailingSlash' :: Text -> NativeTypeValidate
noTrailingSlash' param res
  | res ^? rattributes . ix "ensure" == Just "directory" = Right res
  | otherwise = noTrailingSlash param res

validateMode :: NativeTypeValidate
validateMode res = do
    modestr <- case res ^. rattributes . at "mode" of
                  Just (PString s) -> return s
                  Just x -> throwError $ PrettyError ("Invalide mode type, should be a string " <+> pretty x)
                  Nothing -> throwError "Could not find mode!"
    (numeric modestr <|> except (ugo modestr)) & runExcept & _Right %~ ($ res)

numeric :: Text -> Except PrettyError (Resource -> Resource)
numeric modestr = do
    when ((Text.length modestr /= 3) && (Text.length modestr /= 4)) (throwError "Invalid mode size")
    unless (Text.all Char.isDigit modestr) (throwError "The mode should only be made of digits")
    return $ if Text.length modestr == 3
                 then rattributes . at "mode" ?~ PString (Text.cons '0' modestr)
                 else identity

checkSource :: Text -> PValue -> NativeTypeValidate
checkSource _ (PString x) res | any (`Text.isPrefixOf` x) ["puppet://", "file://", "/", "http://", "https://"] = Right res
                              | otherwise = throwError "A source should start with either puppet://, http://, https:// or file:// or an absolute path"
checkSource _ x _ = throwError $ PrettyError ("Expected a string, not" <+> pretty x)

data PermParts = Special | User | Group | Other
               deriving (Eq, Ord)

data PermSet = R | W | X
             deriving (Ord, Eq)

ugo :: Text -> Either PrettyError (Resource -> Resource)
ugo t = AT.parseOnly (modestring <* AT.endOfInput) t
        & _Left %~ (\rr -> PrettyError $ "Could not parse the mode string: " <> ppstring rr)
        & _Right %~ (\s -> rattributes . at "mode" ?~ PString (mkmode Special s <> mkmode User s <> mkmode Group s <> mkmode Other s))

mkmode :: PermParts -> Map PermParts (Set PermSet) -> Text
mkmode p m = let s = m ^. at p . non mempty
             in  Text.pack $ show $ fromEnum (Set.member R s) * 4
                               + fromEnum (Set.member W s) * 2
                               + fromEnum (Set.member X s)

modestring :: AT.Parser (Map PermParts (Set.Set PermSet))
modestring = Map.fromList . mconcat <$> (modepart `AT.sepBy` AT.char ',')

-- TODO suid, sticky and other funky things are not yet supported
modepart :: AT.Parser [(PermParts, Set PermSet)]
modepart = do
    let permpart =   (AT.char 'u' *> pure [User])
                 <|> (AT.char 'g' *> pure [Group])
                 <|> (AT.char 'o' *> pure [Other])
                 <|> (AT.char 'a' *> pure [User,Group,Other])
        permission =   (AT.char 'r' *> pure R)
                   <|> (AT.char 'w' *> pure W)
                   <|> (AT.char 'x' *> pure X)
    pp <- mconcat <$> some permpart
    void $ AT.char '='
    pr <- Set.fromList <$> some permission
    return (map (\p -> (p, pr)) pp)

redpajama_set_name: RedPajamaGithub


text:
require_relative './../../../spec_helper'

describe 'oneview_test_api300_synergy::sas_logical_interconnect_activate_firmware' do
  let(:resource_name) { 'sas_logical_interconnect' }
  let(:base_sdk) { OneviewSDK::API300::Synergy }
  let(:provider) { OneviewCookbook::API300::Synergy::SASLogicalInterconnectProvider }
  include_context 'chef context'
  include_context 'shared context'

  # Mocks the firmware_handler
  before(:each) do
    @firmware_driver = base_sdk::FirmwareDriver.new(client300, name: 'Unit SPP', uri: 'rest/firmware/fake')
    allow_any_instance_of(base_sdk::SASLogicalInterconnect).to receive(:retrieve!).and_return(true)
    allow_any_instance_of(base_sdk::SASLogicalInterconnect).to receive(:get_firmware).and_return({})
    allow_any_instance_of(provider).to receive(:load_resource).with(:FirmwareDriver, anything).and_return(@firmware_driver)
  end

  it 'activates the current firmware' do
    expect_any_instance_of(base_sdk::SASLogicalInterconnect).to receive(:firmware_update)
      .with('Activate', @firmware_driver, anything).and_return(true)
    expect(real_chef_run).to activate_oneview_sas_logical_interconnect_firmware('SASLogicalInterconnect-activate_firmware')
  end
end


text:
package com.smartbear.loadtest.utils;

import java.net.URL;

/**
 * @author Renato
 */
public interface ResourceLoader {

    public String read( URL url );

}


text:
from flask import Flask, redirect, render_template, url_for

# Import SQLAlchemy
from flask.ext.sqlalchemy import SQLAlchemy

# Define the WSGI application object
app = Flask(__name__)

# Configurations
app.config.from_object('config')

# Define the database object which is imported
# by modules and controllers
db = SQLAlchemy(app)

# Sample HTTP error handling
@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404

# Index redirect
@app.route('/')
def home():
    """
    Redirect to the slide viewer

    """
    return redirect(url_for('slides.slide_viewer'))

# Import modules for Blueprint
from app.slides.controllers import slides
from app.admin.controllers import admin

# Register blueprints
app.register_blueprint(slides)
app.register_blueprint(admin)

# Build the database:
# This will create the database file using SQLAlchemy
db.create_all()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>All Classes (star 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2017-04-21">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Auth0CallbackController

Auth0CConfig

ChapterModel

DatabaseBackupTask

DocsIndexController

HttpSessionConfig

IndexController

LoginController

LogoutController

StarApplication

StoryModel

TagModel

UserModel

UserProfileController

UserSettingsModel

V1Controller

V1Model

V1StatusController

V1StatusModel


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{{ page.title }} - Opera extensions documentation</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
		<link href="//netdna.bootstrapcdn.com/bootswatch/2.3.2/cosmo/bootstrap.min.css" rel="stylesheet">
		<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap-responsive.min.css" rel="stylesheet">
		<link href="css/custom.css" rel="stylesheet" media="screen">

						<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

						</button>
						Opera extensions documentation

Contact

↑ Dev.Opera

							<form class="navbar-search pull-right" action="search.html">
							  <input name="q" type="text" class="search-query span3" placeholder="Search extension docs">
							</form>


text:
package org.apache.sysds.test.functions.pipelines;

import org.junit.Test;
import org.apache.sysds.common.Types.ExecMode;
import org.apache.sysds.common.Types.ExecType;
import org.apache.sysds.runtime.matrix.data.MatrixValue;
import org.apache.sysds.test.AutomatedTestBase;
import org.apache.sysds.test.TestConfiguration;
import org.apache.sysds.test.TestUtils;

import java.util.HashMap;

public class BuiltinImageMirrorTest extends AutomatedTestBase
{
	private final static String TEST_NAME = "image_mirror";
	private final static String TEST_DIR = "functions/builtin/";
	private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinImageMirrorTest.class.getSimpleName() + "/";

	private final static double eps = 1e-10;
	private final static int rows = 256;
	private final static int cols = 256;
	private final static double spSparse = 0.1;
	private final static double spDense = 0.9;

	@Override
	public void setUp() {
		addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{"Bx", "By"}));
	}

	@Test
	public void testImageMirrorMatrixDenseCP() {runImageMirrorTest(false, ExecType.CP);
	}

	@Test
	public void testImageMirrorMatrixSparseCP() {runImageMirrorTest(true, ExecType.CP);
	}

	@Test
	public void testImageMirrorMatrixDenseSP() {runImageMirrorTest(false, ExecType.SPARK);
	}

	@Test
	public void testImageMirrorMatrixSparseSP() {runImageMirrorTest(false,ExecType.SPARK);
	}

	private void runImageMirrorTest(boolean sparse, ExecType instType)
	{
		ExecMode platformOld = setExecMode(instType);

		try
		{
			loadTestConfiguration(getTestConfiguration(TEST_NAME));
			double sparsity = sparse ? spSparse : spDense;

			String HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = HOME + TEST_NAME + ".dml";
			programArgs = new String[]{"-nvargs",
					"in_file=" + input("A"),
					"x_out_file=" + output("Bx"),
					"y_out_file=" + output("By"),
			};

			fullRScriptName = HOME + TEST_NAME + ".R";
			rCmd = "Rscript" + " " + fullRScriptName + " " + inputDir() + " " + expectedDir();

			//generate actual dataset
			double[][] A = getRandomMatrix(rows, cols, 0, 255, sparsity, 7);
			writeInputMatrixWithMTD("A", A, true);

			runTest(true, false, null, -1);
			runRScript(true);

			//compare matrices of the image mirrored on the x axis
			HashMap<MatrixValue.CellIndex, Double> dmlfile_x = readDMLMatrixFromOutputDir("Bx");
			HashMap<MatrixValue.CellIndex, Double> rfile_x  = readRMatrixFromExpectedDir("Bx");
			TestUtils.compareMatrices(dmlfile_x, rfile_x, eps, "Stat-DML", "Stat-R");

			//compare matrices of the image mirrored on the y axis
			HashMap<MatrixValue.CellIndex, Double> dmlfile_y = readDMLMatrixFromOutputDir("By");
			HashMap<MatrixValue.CellIndex, Double> rfile_y  = readRMatrixFromExpectedDir("By");
			TestUtils.compareMatrices(dmlfile_y, rfile_y, eps, "Stat-DML", "Stat-R");
		}
		finally {
			rtplatform = platformOld;
		}
	}
}


text:
import { now, random, find, findIndex } from 'lodash';

const LOCAL_KEY = 'cards';

// RFC 4122 version 4 uuid
export const uuid = function () {
  let d = now();
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = (d + random(16)) % 16 | 0;
      d = Math.floor(d / 16);
      return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
};

const persistedStore = function () {
  let d = localStorage.getItem(LOCAL_KEY);
  return d ? JSON.parse(d) : { users:[] };
};

export const createUser = function (username='sarahconnor', avatar=0) {
  return {
    id: uuid(),
    name: username,
    avatar: avatar
  };
};

export const setMe = function (userinfo){
  let persisted = persistedStore();
  persisted.me = userinfo;
  localStorage.setItem(LOCAL_KEY, JSON.stringify(persisted));
  return persisted.me;
};

export const findMe = function () {
  let persisted = persistedStore();
  return persisted.me;
};

export const findUser = function (username) {
  let persisted = persistedStore();
  let user = find(persisted.users, { name: username});
  console.log('findUser', persisted, user);
  //username ? find(persisted.users, { name: username}) : persisted.users[0];
  // if(!user){
  //   user = setUser({
  //     name: username || 'sarahconnor',
  //     id: uuid(),
  //     avatar: 5
  //   });
  // }
  return user;
};

export const setUser = function (userinfo) {
  let persisted = persistedStore();
  let index = findIndex(persisted.users, { id: userinfo.id});
  if(index == -1){
    persisted.users.push(userinfo);
  } else {
    persisted.users[index] = userinfo;
  }
  localStorage.setItem(LOCAL_KEY, JSON.stringify(persisted));
  return userinfo;
};

const guys = [0,2,4,6];
const girls = [1,3,5];
const guyNames = ['Plant', 'Mercury', 'Hendrix', 'Bono', 'Presley', 'Tyler', 'Jagger', 'Morrison'];
const girlNames = ['Kat', 'Hanna', 'Grace', 'Joni', 'Nicks', 'Joplin'];

export const createBot = function (ignore) {
  let bot = {id:uuid(), bot:true};
  if(random(0, 1) === 0){
    return {
      name: uniqueName(ignore, girlNames),
      avatar: girls[random(0, girls.length-1)],
      ...bot
    };
  }
  return {
    name: uniqueName(ignore, guyNames),
    avatar: guys[random(0, guys.length-1)],
    ...bot
  };
};

const uniqueName = function (ignore, list) {
  let name = list[random(0, list.length-1)];
  let safe = 10;
  while(findIndex(ignore, { name: name }) != -1){
    name = list[random(0, list.length-1)];
    if(safe-- <= 0){
      break;
    }
  }
  return name;
};


text:
<!DOCTYPE html>
<!--
Copyright (c) 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/tracing/base/statistics.html">
<link rel="import" href="/tracing/metrics/system_health/utils.html">
<link rel="import" href="/tracing/metrics/system_health/efficiency_metric.html">
<link rel="import" href="/tracing/metrics/system_health/responsiveness_metric.html">

<script>
'use strict';

tr.exportTo('tr.metrics.sh', function() {
  function SystemHealthMetric() {
  }

  SystemHealthMetric.forModel = function(model, opt_rangeOfInterest) {
    return tr.b.Statistics.weightedMean(
        tr.metrics.sh.filterExpectationsByRange(
            model.userModel.expectations, opt_rangeOfInterest),
        tr.metrics.sh.perceptualBlend,
        SystemHealthMetric.forExpectation);
  };

  SystemHealthMetric.forExpectation = function(ir) {
    function getValue(metric) {
      return metric.forExpectation(ir);
    }
    function getWeight(metric, index, score) {
      var weight = 1;

      // Without knowing which specific value of responsiveness or efficiency is
      // lower, responsiveness is theoretically twice as important as
      // efficiency.  If the entire web were to eventually achieve relatively
      // high responsiveness scores such that responsiveness was less of a
      // concern than efficiency, then this number could be lowered. If further
      // thought suggests that responsiveness is even more than twice as
      // important as efficiency, then this number could be raised.
      if (metric === tr.metrics.sh.ResponsivenessMetric)
        weight = 2;

      return weight * tr.metrics.sh.perceptualBlend(ir, index, score);
    }
    return tr.b.Statistics.weightedMean(
        [tr.metrics.sh.ResponsivenessMetric,
         tr.metrics.sh.EfficiencyMetric],
        getWeight,
        getValue);
  };

  return {
    SystemHealthMetric: SystemHealthMetric
  };
});
</script>


text:
-------------------------------------------------------------------------------
--  user role
-------------------------------------------------------------------------------
CREATE TABLE AUTH_USER_ROLE(
        USER_STATUS_ID BIGINT NOT NULL,
        ROLE_ID BIGINT NOT NULL,
        CONSTRAINT PK_AUTH_USER_ROLE PRIMARY KEY(USER_STATUS_ID,ROLE_ID),
        CONSTRAINT FK_AUTH_USER_ROLE_USER FOREIGN KEY(USER_STATUS_ID) REFERENCES AUTH_USER_STATUS(ID),
        CONSTRAINT FK_AUTH_USER_ROLE_ROLE FOREIGN KEY(ROLE_ID) REFERENCES AUTH_ROLE(ID)
) ENGINE=INNODB CHARSET=UTF8;


text:
Finally, configure the |kconnect| worker to allow overrides, because |crep| needs to override the default behavior of the |kconnect| worker's embedded producer.

.. sourcecode:: bash

   connector.client.config.override.policy=All


text:
/**
 * @file Header file for the PCAL9535A driver.
 */

#ifndef _GPIO_PCAL9535A_H_
#define _GPIO_PCAL9535A_H_

#include <kernel.h>

#include <gpio.h>
#include <i2c.h>

#ifdef __cplusplus
extern "C" {
#endif

/** Configuration data */
struct gpio_pcal9535a_config {
	/** The master I2C device's name */
	const char * const i2c_master_dev_name;

	/** The slave address of the chip */
	uint16_t i2c_slave_addr;

	uint8_t stride[2];
};

/** Store the port 0/1 data for each register pair. */
union gpio_pcal9535a_port_data {
	uint16_t all;
	uint8_t port[2];
	uint8_t byte[2];
};

/** Runtime driver data */
struct gpio_pcal9535a_drv_data {
	/** Master I2C device */
	struct device *i2c_master;

	/**
	 * Specify polarity inversion of pin. This is used for ouput as
	 * the polarity inversion registers on chip affects inputs only.
	 */
	uint32_t out_pol_inv;

	struct {
		union gpio_pcal9535a_port_data output;
		union gpio_pcal9535a_port_data pol_inv;
		union gpio_pcal9535a_port_data dir;
		union gpio_pcal9535a_port_data pud_en;
		union gpio_pcal9535a_port_data pud_sel;
	} reg_cache;

	uint8_t stride[2];
};

#ifdef __cplusplus
}
#endif

#endif /* _GPIO_PCAL9535A_H_ */


text:
#import <Foundation/Foundation.h>
#import "TWTRAuthSession.h"

NS_ASSUME_NONNULL_BEGIN

@interface TWTRTokenOnlyAuthSession : NSObject <TWTRAuthSession>

@property (nonatomic, copy, readonly) NSString *authToken;

@property (nonatomic, copy, readonly) NSString *authTokenSecret;

/**
 * This value is here to satisfy TWTRAuthSession protocol but
 * it defaults to an empty string and cannot be updated.
 */
@property (nonatomic, copy, readonly) NSString *userID;

- (instancetype)initWithToken:(NSString *)authToken secret:(NSString *)authTokenSecret;
+ (instancetype)authSessionWithToken:(NSString *)authToken secret:(NSString *)authTokenSecret;

@end

NS_ASSUME_NONNULL_END


text:
package org.jitsi.android.gui.account;

import android.content.*;
import android.os.Bundle;

import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;

import org.jitsi.*;
import org.jitsi.android.gui.*;
import org.jitsi.android.gui.menu.*;
import org.jitsi.android.gui.util.*;

import org.osgi.framework.*;

/**
 * The <tt>AccountLoginActivity</tt> is the activity responsible for creating
 * a new account.
 *
 * @author Yana Stamcheva
 * @author Pawel Domas
 */
public class AccountLoginActivity
    extends ExitMenuActivity
    implements AccountLoginFragment.AccountLoginListener
{
    /**
     * The username property name.
     */
    public static final String USERNAME = "Username";

    /**
     * The password property name.
     */
    public static final String PASSWORD = "Password";

    /**
     * Called when the activity is starting. Initializes the corresponding
     * call interface.
     *
     * @param savedInstanceState If the activity is being re-initialized after
     * previously being shut down then this Bundle contains the data it most
     * recently supplied in onSaveInstanceState(Bundle).
     * Note: Otherwise it is null.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // If we have instance state it means the fragment is already created
        if(savedInstanceState == null)
        {
            // Create AccountLoginFragment fragment
            String login = getIntent().getStringExtra(USERNAME);
            String password = getIntent().getStringExtra(PASSWORD);
            AccountLoginFragment accountLogin
                    = AccountLoginFragment.createInstance(login, password);

            getSupportFragmentManager()
                    .beginTransaction()
                    .add(android.R.id.content, accountLogin)
                    .commit();
        }
    }

    /**
     * Sign in the account with the given <tt>userName</tt>, <tt>password</tt>
     * and <tt>protocolName</tt>.
     *
     * @param userName the username of the account
     * @param password the password of the account
     * @param protocolName the name of the protocol
     * @return the <tt>ProtocolProviderService</tt> corresponding to the newly
     * signed in account
     */
    private ProtocolProviderService signIn( String userName,
                                            String password,
                                            String protocolName)
    {
        BundleContext bundleContext = getBundlecontext();

        Logger logger = Logger.getLogger(Jitsi.class);

        ServiceReference<?>[] accountWizardRefs = null;
        try
        {
            accountWizardRefs = bundleContext.getServiceReferences(
                    AccountRegistrationWizard.class.getName(),
                    null);
        }
        catch (InvalidSyntaxException ex)
        {
            // this shouldn't happen since we're providing no parameter string
            // but let's log just in case.
            logger.error(
                    "Error while retrieving service refs", ex);
        }

        // in case we found any, add them in this container.
        if (accountWizardRefs == null)
        {
            logger.error("No registered registration wizards found");
            return null;
        }

        if (logger.isDebugEnabled())
            logger.debug("Found " + accountWizardRefs.length
                                  + " already installed providers.");

        AccountRegistrationWizard selectedWizard = null;

        for (int i = 0; i < accountWizardRefs.length; i++)
        {
            AccountRegistrationWizard accReg
                    = (AccountRegistrationWizard) bundleContext
                    .getService(accountWizardRefs[i]);
            if (accReg.getProtocolName().equals(protocolName))
            {
                selectedWizard = accReg;
                break;
            }
        }
        if(selectedWizard == null)
        {
            logger.warn("No wizard found for protocol name: "+protocolName);
            return null;
        }
        try
        {
            selectedWizard.setModification(false);

            return selectedWizard.signin(userName, password);
        }
        catch (OperationFailedException e)
        {
            logger.error("Sign in operation failed.", e);

            if (e.getErrorCode() == OperationFailedException.ILLEGAL_ARGUMENT)
            {
                AndroidUtils.showAlertDialog(
                        this,
                        R.string.service_gui_LOGIN_FAILED,
                        R.string.service_gui_USERNAME_NULL);
            }
            else if (e.getErrorCode()
                            == OperationFailedException.IDENTIFICATION_CONFLICT)
            {
                AndroidUtils.showAlertDialog(
                        this,
                        R.string.service_gui_LOGIN_FAILED,
                        R.string.service_gui_USER_EXISTS_ERROR);
            }
            else if (e.getErrorCode()
                            == OperationFailedException.SERVER_NOT_SPECIFIED)
            {
                AndroidUtils.showAlertDialog(
                        this,
                        R.string.service_gui_LOGIN_FAILED,
                        R.string.service_gui_SPECIFY_SERVER);
            }
            else
            {
                AndroidUtils.showAlertDialog(
                        this,
                        R.string.service_gui_LOGIN_FAILED,
                        R.string.service_gui_ACCOUNT_CREATION_FAILED);
            }
        }
        catch (Exception e)
        {
            logger.error("Exception while adding account: "+e.getMessage(), e);
            AndroidUtils.showAlertDialog(
                    this,
                    R.string.service_gui_ERROR,
                    R.string.service_gui_ACCOUNT_CREATION_FAILED);
        }
        return null;
    }

    /**
     *
     */
    @Override
    public void onLoginPerformed(String login, String password, String network)
    {
        ProtocolProviderService protocolProvider
                = signIn( login, password, network );

        if (protocolProvider != null)
        {
            //addAndroidAccount(protocolProvider);

            Intent showContactsIntent = new Intent(Jitsi.ACTION_SHOW_CONTACTS);
            startActivity(showContactsIntent);
            finish();
        }

    }
}


text:
class Output < Struct.new(:content)
  def show
    $stdout.puts "=> #{content}"
  end
end


text:
etcd
====

.. versionadded:: 0.4

`etcd <https://github.com/coreos/etcd>`_ is used in the project by
:doc:`calico` to distribute information about workloads, endpoints, and policy
to each Docker host. It's run in a Docker container on each host and managed
by systemd.

Variables
---------

You can use these variables to customize your etcd installation. Beware,
you will need to update ``ETCD_AUTHORITY`` in the Calico role as well.

.. data:: etcd_client_port

   Port for etcd client communication

   Default: ``2379``

.. data:: etcd_peer_port

   Port for etcd server-to-server communication

   Default: ``2380``


text:
#ifndef _V_WINDOW_
#define _V_WINDOW_

extern const void *_vorbis_window(int type,int left);
extern void _vorbis_apply_window(ogg_int32_t *d,const void *window[2],
				 long *blocksizes,
				 int lW,int W,int nW);

#endif


text:
#ifndef dom_html_br_element_h_
#define dom_html_br_element_h_

#include <stdbool.h>
#include <dom/core/exceptions.h>
#include <dom/core/string.h>

typedef struct dom_html_br_element dom_html_br_element;

dom_exception dom_html_br_element_get_clear(
	dom_html_br_element *ele, dom_string **clear);

dom_exception dom_html_br_element_set_clear(
	dom_html_br_element *ele, dom_string *clear);

#endif


text:
package br.puc_rio.ele.lvc.interimage.data.imageioimpl.plugins.tiff;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.ComponentSampleModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import org.w3c.dom.Node;
import br.puc_rio.ele.lvc.interimage.data.imageio.plugins.tiff.BaselineTIFFTagSet;
import br.puc_rio.ele.lvc.interimage.data.imageio.plugins.tiff.TIFFColorConverter;
import br.puc_rio.ele.lvc.interimage.data.imageio.plugins.tiff.TIFFDecompressor;
import br.puc_rio.ele.lvc.interimage.data.imageio.plugins.tiff.TIFFField;
import br.puc_rio.ele.lvc.interimage.data.imageio.plugins.tiff.TIFFImageReadParam;
import br.puc_rio.ele.lvc.interimage.data.imageio.plugins.tiff.TIFFTag;
import br.puc_rio.ele.lvc.interimage.data.imageioimpl.common.ImageUtil;
import br.puc_rio.ele.lvc.interimage.data.imageioimpl.common.PackageUtil;

public class TIFFImageReader extends ImageReader {

    private static final boolean DEBUG = false; // XXX 'false' for release!!!

    // The current ImageInputStream source.
    ImageInputStream stream = null;

    // True if the file header has been read.
    boolean gotHeader = false;

    ImageReadParam imageReadParam = getDefaultReadParam();

    // Stream metadata, or null.
    TIFFStreamMetadata streamMetadata = null;

    // The current image index.
    int currIndex = -1;

    // Metadata for image at 'currIndex', or null.
    TIFFImageMetadata imageMetadata = null;

    // A List of Longs indicating the stream
    // positions of the start of the IFD for each image.  Entries
    // are added as needed.
    List imageStartPosition = new ArrayList();

    // The number of images in the stream, if known, otherwise -1.
    int numImages = -1;

    // The ImageTypeSpecifiers of the images in the stream.
    // Contains a map of Integers to Lists.
    HashMap imageTypeMap = new HashMap();

    BufferedImage theImage = null;

    int width = -1;
    int height = -1;
    int numBands = -1;
    int tileOrStripWidth = -1, tileOrStripHeight = -1;

    int planarConfiguration = BaselineTIFFTagSet.PLANAR_CONFIGURATION_CHUNKY;

    int rowsDone = 0;

    int compression;
    int photometricInterpretation;
    int samplesPerPixel;
    int[] sampleFormat;
    int[] bitsPerSample;
    int[] extraSamples;
    char[] colorMap;

    int sourceXOffset;
    int sourceYOffset;
    int srcXSubsampling;
    int srcYSubsampling;

    int dstWidth;
    int dstHeight;
    int dstMinX;
    int dstMinY;
    int dstXOffset;
    int dstYOffset;

    int tilesAcross;
    int tilesDown;

    int pixelsRead;
    int pixelsToRead;

    public TIFFImageReader(ImageReaderSpi originatingProvider) {
        super(originatingProvider);
    }

    public void setInput(Object input,
                         boolean seekForwardOnly,
                         boolean ignoreMetadata) {
        super.setInput(input, seekForwardOnly, ignoreMetadata);

        // Clear all local values based on the previous stream contents.
        resetLocal();

        if (input != null) {
            if (!(input instanceof ImageInputStream)) {
                throw new IllegalArgumentException
                    ("input not an ImageInputStream!");
            }
            this.stream = (ImageInputStream)input;
        } else {
            this.stream = null;
        }
    }

    // Do not seek to the beginning of the stream so as to allow users to
    // point us at an IFD within some other file format
    private void readHeader() throws IIOException {
        if (gotHeader) {
            return;
        }
        if (stream == null) {
            throw new IllegalStateException("Input not set!");
        }

        // Create an object to store the stream metadata
        this.streamMetadata = new TIFFStreamMetadata();

        try {
            int byteOrder = stream.readUnsignedShort();
            if (byteOrder == 0x4d4d) {
                streamMetadata.byteOrder = ByteOrder.BIG_ENDIAN;
                stream.setByteOrder(ByteOrder.BIG_ENDIAN);
            } else if (byteOrder == 0x4949) {
                streamMetadata.byteOrder = ByteOrder.LITTLE_ENDIAN;
                stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
            } else {
                processWarningOccurred(
                           "Bad byte order in header, assuming little-endian");
                streamMetadata.byteOrder = ByteOrder.LITTLE_ENDIAN;
                stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
            }

            int magic = stream.readUnsignedShort();
            if (magic != 42) {
                processWarningOccurred(
                                     "Bad magic number in header, continuing");
            }

            // Seek to start of first IFD
            long offset = stream.readUnsignedInt();
            imageStartPosition.add(new Long(offset));
            stream.seek(offset);
        } catch (IOException e) {
            throw new IIOException("I/O error reading header!", e);
        }

        gotHeader = true;
    }

    private int locateImage(int imageIndex) throws IIOException {
        readHeader();

        try {
            // Find closest known index
            int index = Math.min(imageIndex, imageStartPosition.size() - 1);

            // Seek to that position
            Long l = (Long)imageStartPosition.get(index);
            stream.seek(l.longValue());

            // Skip IFDs until at desired index or last image found
            while (index < imageIndex) {
                int count = stream.readUnsignedShort();
                stream.skipBytes(12*count);

                long offset = stream.readUnsignedInt();
                if (offset == 0) {
                    return index;
                }

                imageStartPosition.add(new Long(offset));
                stream.seek(offset);
                ++index;
            }
        } catch (IOException e) {
            throw new IIOException("Couldn't seek!", e);
        }

        if (currIndex != imageIndex) {
            imageMetadata = null;
        }
        currIndex = imageIndex;
        return imageIndex;
    }

    public int getNumImages(boolean allowSearch) throws IOException {
        if (stream == null) {
            throw new IllegalStateException("Input not set!");
        }
        if (seekForwardOnly && allowSearch) {
            throw new IllegalStateException
                ("seekForwardOnly and allowSearch can't both be true!");
        }

        if (numImages > 0) {
            return numImages;
        }
        if (allowSearch) {
            this.numImages = locateImage(Integer.MAX_VALUE) + 1;
        }
        return numImages;
    }

    public IIOMetadata getStreamMetadata() throws IIOException {
        readHeader();
        return streamMetadata;
    }

    // Throw an IndexOutOfBoundsException if index < minIndex,
    // and bump minIndex if required.
    private void checkIndex(int imageIndex) {
        if (imageIndex < minIndex) {
            throw new IndexOutOfBoundsException("imageIndex < minIndex!");
        }
        if (seekForwardOnly) {
            minIndex = imageIndex;
        }
    }

    // Verify that imageIndex is in bounds, find the image IFD, read the
    // image metadata, initialize instance variables from the metadata.
    private void seekToImage(int imageIndex) throws IIOException {
        checkIndex(imageIndex);

        int index = locateImage(imageIndex);
        if (index != imageIndex) {
            throw new IndexOutOfBoundsException("imageIndex out of bounds!");
        }

        readMetadata();

        initializeFromMetadata();
    }

    // Stream must be positioned at start of IFD for 'currIndex'
    private void readMetadata() throws IIOException {
        if (stream == null) {
            throw new IllegalStateException("Input not set!");
        }

        if (imageMetadata != null) {
            return;
        }
        try {
            // Create an object to store the image metadata
            List tagSets;
            if (imageReadParam instanceof TIFFImageReadParam) {
                tagSets =
                    ((TIFFImageReadParam)imageReadParam).getAllowedTagSets();
            } else {
                tagSets = new ArrayList(1);
                tagSets.add(BaselineTIFFTagSet.getInstance());
            }

            this.imageMetadata = new TIFFImageMetadata(tagSets);
            imageMetadata.initializeFromStream(stream, ignoreMetadata);
        } catch (IIOException iioe) {
            throw iioe;
        } catch (IOException ioe) {
            throw new IIOException("I/O error reading image metadata!", ioe);
        }
    }

    private int getWidth() {
        return this.width;
    }

    private int getHeight() {
        return this.height;
    }

    private int getNumBands() {
        return this.numBands;
    }

    // Returns tile width if image is tiled, else image width
    private int getTileOrStripWidth() {
        TIFFField f =
            imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_TILE_WIDTH);
        return (f == null) ? getWidth() : f.getAsInt(0);
    }

    // Returns tile height if image is tiled, else strip height
    private int getTileOrStripHeight() {
        TIFFField f =
            imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_TILE_LENGTH);
        if (f != null) {
            return f.getAsInt(0);
        }

        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_ROWS_PER_STRIP);
        // Default for ROWS_PER_STRIP is 2^32 - 1, i.e., infinity
        int h = (f == null) ? -1 : f.getAsInt(0);
        return (h == -1) ? getHeight() : h;
    }

    private int getPlanarConfiguration() {
        TIFFField f =
        imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_PLANAR_CONFIGURATION);
        if (f != null) {
            int planarConfigurationValue = f.getAsInt(0);
            if(planarConfigurationValue ==
               BaselineTIFFTagSet.PLANAR_CONFIGURATION_PLANAR) {
                // Some writers (e.g. Kofax standard Multi-Page TIFF
                // Storage Filter v2.01.000; cf. bug 4929147) do not
                // correctly set the value of this field. Attempt to
                // ascertain whether the value is correctly Planar.
                if(getCompression() ==
                   BaselineTIFFTagSet.COMPRESSION_OLD_JPEG &&
                   imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT) !=
                   null) {
                    // JPEG interchange format cannot have
                    // PlanarConfiguration value Chunky so reset.
                    processWarningOccurred("PlanarConfiguration \"Planar\" value inconsistent with JPEGInterchangeFormat; resetting to \"Chunky\".");
                    planarConfigurationValue =
                        BaselineTIFFTagSet.PLANAR_CONFIGURATION_CHUNKY;
                } else {
                    TIFFField offsetField =
                        imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_TILE_OFFSETS);
                    if (offsetField == null) {
                        // Tiles
                        offsetField =
                            imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_STRIP_OFFSETS);
                        int tw = getTileOrStripWidth();
                        int th = getTileOrStripHeight();
                        int tAcross = (getWidth() + tw - 1)/tw;
                        int tDown = (getHeight() + th - 1)/th;
                        int tilesPerImage = tAcross*tDown;
                        long[] offsetArray = offsetField.getAsLongs();
                        if(offsetArray != null &&
                           offsetArray.length == tilesPerImage) {
                            // Length of offsets array is
                            // TilesPerImage for Chunky and
                            // SamplesPerPixel*TilesPerImage for Planar.
                            processWarningOccurred("PlanarConfiguration \"Planar\" value inconsistent with TileOffsets field value count; resetting to \"Chunky\".");
                            planarConfigurationValue =
                                BaselineTIFFTagSet.PLANAR_CONFIGURATION_CHUNKY;
                        }
                    } else {
                        // Strips
                        int rowsPerStrip = getTileOrStripHeight();
                        int stripsPerImage =
                            (getHeight() + rowsPerStrip - 1)/rowsPerStrip;
                        long[] offsetArray = offsetField.getAsLongs();
                        if(offsetArray != null &&
                           offsetArray.length == stripsPerImage) {
                            // Length of offsets array is
                            // StripsPerImage for Chunky and
                            // SamplesPerPixel*StripsPerImage for Planar.
                            processWarningOccurred("PlanarConfiguration \"Planar\" value inconsistent with StripOffsets field value count; resetting to \"Chunky\".");
                            planarConfigurationValue =
                                BaselineTIFFTagSet.PLANAR_CONFIGURATION_CHUNKY;
                        }
                    }
                }
            }
            return planarConfigurationValue;
        }

        return BaselineTIFFTagSet.PLANAR_CONFIGURATION_CHUNKY;
    }

    private long getTileOrStripOffset(int tileIndex) throws IIOException {
        TIFFField f =
            imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_TILE_OFFSETS);
        if (f == null) {
            f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_STRIP_OFFSETS);
        }
        if (f == null) {
            f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT);
        }

        if(f == null) {
            throw new IIOException
                ("Missing required strip or tile offsets field.");
        }

        return f.getAsLong(tileIndex);
    }

    private long getTileOrStripByteCount(int tileIndex) throws IOException {
        TIFFField f =
           imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS);
        if (f == null) {
            f =
          imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_STRIP_BYTE_COUNTS);
        }
        if (f == null) {
            f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
        }

        long tileOrStripByteCount;
        if(f != null) {
            tileOrStripByteCount = f.getAsLong(tileIndex);
        } else {
            processWarningOccurred("TIFF directory contains neither StripByteCounts nor TileByteCounts field: attempting to calculate from strip or tile width and height.");

            // Initialize to number of bytes per strip or tile assuming
            // no compression.
            int bitsPerPixel = bitsPerSample[0];
            for(int i = 1; i < samplesPerPixel; i++) {
                bitsPerPixel += bitsPerSample[i];
            }
            int bytesPerRow = (getTileOrStripWidth()*bitsPerPixel + 7)/8;
            tileOrStripByteCount = bytesPerRow*getTileOrStripHeight();

            // Clamp to end of stream if possible.
            long streamLength = stream.length();
            if(streamLength != -1) {
                tileOrStripByteCount =
                    Math.min(tileOrStripByteCount,
                             streamLength - getTileOrStripOffset(tileIndex));
            } else {
                processWarningOccurred("Stream length is unknown: cannot clamp estimated strip or tile byte count to EOF.");
            }
        }

        return tileOrStripByteCount;
    }

    private int getCompression() {
        TIFFField f =
            imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION);
        if (f == null) {
	    return BaselineTIFFTagSet.COMPRESSION_NONE;
	} else {
            return f.getAsInt(0);
	}
    }

    public int getWidth(int imageIndex) throws IOException {
        seekToImage(imageIndex);
        return getWidth();
    }

    public int getHeight(int imageIndex) throws IOException {
        seekToImage(imageIndex);
        return getHeight();
    }

    /**
     * Initializes these instance variables from the image metadata:
     *

     * compression
     * width
     * height
     * samplesPerPixel
     * numBands
     * colorMap
     * photometricInterpretation
     * sampleFormat
     * bitsPerSample
     * extraSamples
     * tileOrStripWidth
     * tileOrStripHeight
     *

     */
    private void initializeFromMetadata() {
        TIFFField f;

        // Compression
        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION);
        if (f == null) {
            processWarningOccurred
                ("Compression field is missing; assuming no compression");
            compression = BaselineTIFFTagSet.COMPRESSION_NONE;
        } else {
            compression = f.getAsInt(0);
        }

        // Whether key dimensional information is absent.
        boolean isMissingDimension = false;

        // ImageWidth -> width
        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_WIDTH);
        if (f != null) {
            this.width = f.getAsInt(0);
        } else {
            processWarningOccurred("ImageWidth field is missing.");
            isMissingDimension = true;
        }

        // ImageLength -> height
        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_LENGTH);
        if (f != null) {
            this.height = f.getAsInt(0);
        } else {
            processWarningOccurred("ImageLength field is missing.");
            isMissingDimension = true;
        }

        // SamplesPerPixel
        f =
          imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL);
        if (f != null) {
            samplesPerPixel = f.getAsInt(0);
        } else {
            samplesPerPixel = 1;
            isMissingDimension = true;
        }

        // If any dimension is missing and there is a JPEG stream available
        // get the information from it.
        int defaultBitDepth = 1;
        if(isMissingDimension &&
           (f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT)) != null) {
            Iterator iter = ImageIO.getImageReadersByFormatName("JPEG");
            if(iter != null && iter.hasNext()) {
                ImageReader jreader = (ImageReader)iter.next();
                try {
                    stream.mark();
                    stream.seek(f.getAsLong(0));
                    jreader.setInput(stream);
                    if(imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_WIDTH) == null) {
                        this.width = jreader.getWidth(0);
                    }
                    if(imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_IMAGE_LENGTH) == null) {
                        this.height = jreader.getHeight(0);
                    }
                    ImageTypeSpecifier imageType = jreader.getRawImageType(0);
                    if(imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL) == null) {
                        this.samplesPerPixel =
                            imageType.getSampleModel().getNumBands();
                    }
                    stream.reset();
                    defaultBitDepth =
                        imageType.getColorModel().getComponentSize(0);
                } catch(IOException e) {
                    // Ignore it and proceed: an error will occur later.
                }
                jreader.dispose();
            }
        }

        if (samplesPerPixel < 1) {
            processWarningOccurred("Samples per pixel < 1!");
        }

        // SamplesPerPixel -> numBands
        numBands = samplesPerPixel;

        // ColorMap
        this.colorMap = null;
        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_COLOR_MAP);
        if (f != null) {
            // Grab color map
            colorMap = f.getAsChars();
        }

        // PhotometricInterpretation
        f =
        imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_PHOTOMETRIC_INTERPRETATION);
        if (f == null) {
            if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE ||
                compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_4 ||
                compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
                processWarningOccurred
                    ("PhotometricInterpretation field is missing; "+
                     "assuming WhiteIsZero");
                photometricInterpretation =
                   BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO;
            } else if(this.colorMap != null) {
                photometricInterpretation =
                    BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_PALETTE_COLOR;
            } else if(samplesPerPixel == 3 || samplesPerPixel == 4) {
                photometricInterpretation =
                    BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_RGB;
            } else {
                processWarningOccurred
                    ("PhotometricInterpretation field is missing; "+
                     "assuming BlackIsZero");
                photometricInterpretation =
                   BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO;
            }
        } else {
            photometricInterpretation = f.getAsInt(0);
        }

        // SampleFormat
        boolean replicateFirst = false;
        int first = -1;

        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_SAMPLE_FORMAT);
        sampleFormat = new int[samplesPerPixel];
        replicateFirst = false;
        if (f == null) {
            replicateFirst = true;
            first = BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED;
        } else if (f.getCount() != samplesPerPixel) {
            replicateFirst = true;
            first = f.getAsInt(0);
        }

        for (int i = 0; i < samplesPerPixel; i++) {
            sampleFormat[i] = replicateFirst ? first : f.getAsInt(i);
            if (sampleFormat[i] !=
                  BaselineTIFFTagSet.SAMPLE_FORMAT_UNSIGNED_INTEGER &&
                sampleFormat[i] !=
                  BaselineTIFFTagSet.SAMPLE_FORMAT_SIGNED_INTEGER &&
                sampleFormat[i] !=
                  BaselineTIFFTagSet.SAMPLE_FORMAT_FLOATING_POINT &&
                sampleFormat[i] !=
                  BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED) {
                processWarningOccurred(
          "Illegal value for SAMPLE_FORMAT, assuming SAMPLE_FORMAT_UNDEFINED");
                sampleFormat[i] = BaselineTIFFTagSet.SAMPLE_FORMAT_UNDEFINED;
            }
        }

        // BitsPerSample
        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);
        this.bitsPerSample = new int[samplesPerPixel];
        replicateFirst = false;
        if (f == null) {
            replicateFirst = true;
            first = defaultBitDepth;
        } else if (f.getCount() != samplesPerPixel) {
            replicateFirst = true;
            first = f.getAsInt(0);
        }

        for (int i = 0; i < samplesPerPixel; i++) {
            // Replicate initial value if not enough values provided
            bitsPerSample[i] = replicateFirst ? first : f.getAsInt(i);

            if (DEBUG) {
                System.out.println("bitsPerSample[" + i + "] = "
                                   + bitsPerSample[i]);
            }
        }

        // ExtraSamples
        this.extraSamples = null;
        f = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_EXTRA_SAMPLES);
        if (f != null) {
            extraSamples = f.getAsInts();
        }

//         System.out.println("colorMap = " + colorMap);
//         if (colorMap != null) {
//             for (int i = 0; i < colorMap.length; i++) {
//              System.out.println("colorMap[" + i + "] = " + (int)(colorMap[i]));
//             }
//         }

    }

    public Iterator getImageTypes(int imageIndex) throws IIOException {
        List l; // List of ImageTypeSpecifiers

        Integer imageIndexInteger = new Integer(imageIndex);
        if(imageTypeMap.containsKey(imageIndexInteger)) {
            // Return the cached ITS List.
            l = (List)imageTypeMap.get(imageIndexInteger);
        } else {
            // Create a new ITS List.
            l = new ArrayList(1);

            // Create the ITS and cache if for later use so that this method
            // always returns an Iterator containing the same ITS objects.
            seekToImage(imageIndex);
            ImageTypeSpecifier itsRaw =
                TIFFDecompressor.getRawImageTypeSpecifier
                    (photometricInterpretation,
                     compression,
                     samplesPerPixel,
                     bitsPerSample,
                     sampleFormat,
                     extraSamples,
                     colorMap);

            // Check for an ICCProfile field.
            TIFFField iccProfileField =
                imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_ICC_PROFILE);

            // If an ICCProfile field is present change the ImageTypeSpecifier
            // to use it if the data layout is component type.
            if(iccProfileField != null &&
               itsRaw.getColorModel() instanceof ComponentColorModel) {
                // Create a ColorSpace from the profile.
                byte[] iccProfileValue = iccProfileField.getAsBytes();
                ICC_Profile iccProfile =
                    ICC_Profile.getInstance(iccProfileValue);
                ICC_ColorSpace iccColorSpace =
                    new ICC_ColorSpace(iccProfile);

                // Get the raw sample and color information.
                ColorModel cmRaw = itsRaw.getColorModel();
                ColorSpace csRaw = cmRaw.getColorSpace();
                SampleModel smRaw = itsRaw.getSampleModel();

                // Get the number of samples per pixel and the number
                // of color components.
                int numBands = smRaw.getNumBands();
                int numComponents = iccColorSpace.getNumComponents();

                // Replace the ColorModel with the ICC ColorModel if the
                // numbers of samples and color components are amenable.
                if(numBands == numComponents ||
                   numBands == numComponents + 1) {
                    // Set alpha flags.
                    boolean hasAlpha = numComponents != numBands;
                    boolean isAlphaPre =
                        hasAlpha && cmRaw.isAlphaPremultiplied();

                    // Create a ColorModel of the same class and with
                    // the same transfer type.
                    ColorModel iccColorModel =
                        new ComponentColorModel(iccColorSpace,
                                                cmRaw.getComponentSize(),
                                                hasAlpha,
                                                isAlphaPre,
                                                cmRaw.getTransparency(),
                                                cmRaw.getTransferType());

                    // Prepend the ICC profile-based ITS to the List. The
                    // ColorModel and SampleModel are guaranteed to be
                    // compatible as the old and new ColorModels are both
                    // ComponentColorModels with the same transfer type
                    // and the same number of components.
                    l.add(new ImageTypeSpecifier(iccColorModel, smRaw));

                    // Append the raw ITS to the List if and only if its
                    // ColorSpace has the same type and number of components
                    // as the ICC ColorSpace.
                    if(csRaw.getType() == iccColorSpace.getType() &&
                       csRaw.getNumComponents() ==
                       iccColorSpace.getNumComponents()) {
                        l.add(itsRaw);
                    }
                } else { // ICCProfile not compatible with SampleModel.
                    // Append the raw ITS to the List.
                    l.add(itsRaw);
                }
            } else { // No ICCProfile field or raw ColorModel not component.
                // Append the raw ITS to the List.
                l.add(itsRaw);
            }

            // Cache the ITS List.
            imageTypeMap.put(imageIndexInteger, l);
        }

        return l.iterator();
    }

    public IIOMetadata getImageMetadata(int imageIndex) throws IIOException {
        seekToImage(imageIndex);
        TIFFImageMetadata im =
            new TIFFImageMetadata(imageMetadata.getRootIFD().getTagSetList());
        Node root =
            imageMetadata.getAsTree(TIFFImageMetadata.nativeMetadataFormatName);
        im.setFromTree(TIFFImageMetadata.nativeMetadataFormatName, root);
        return im;
    }

    public IIOMetadata getStreamMetadata(int imageIndex) throws IIOException {
        readHeader();
        TIFFStreamMetadata sm = new TIFFStreamMetadata();
        Node root = sm.getAsTree(TIFFStreamMetadata.nativeMetadataFormatName);
        sm.setFromTree(TIFFStreamMetadata.nativeMetadataFormatName, root);
        return sm;
    }

    public boolean isRandomAccessEasy(int imageIndex) throws IOException {
        if(currIndex != -1) {
            seekToImage(currIndex);
            return getCompression() == BaselineTIFFTagSet.COMPRESSION_NONE;
        } else {
            return false;
        }
    }

    // Thumbnails

    public boolean readSupportsThumbnails() {
        return false;
    }

    public boolean hasThumbnails(int imageIndex) {
        return false;
    }

    public int getNumThumbnails(int imageIndex) throws IOException {
        return 0;
    }

    public ImageReadParam getDefaultReadParam() {
        return new TIFFImageReadParam();
    }

    public boolean isImageTiled(int imageIndex) throws IOException {
        seekToImage(imageIndex);

        TIFFField f =
            imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_TILE_WIDTH);
        return f != null;
    }

    public int getTileWidth(int imageIndex) throws IOException {
        seekToImage(imageIndex);
        return getTileOrStripWidth();
    }

    public int getTileHeight(int imageIndex) throws IOException {
        seekToImage(imageIndex);
        return getTileOrStripHeight();
    }

    public BufferedImage readTile(int imageIndex, int tileX, int tileY)
        throws IOException {

        int w = getWidth(imageIndex);
        int h = getHeight(imageIndex);
        int tw = getTileWidth(imageIndex);
        int th = getTileHeight(imageIndex);

        int x = tw*tileX;
        int y = th*tileY;

        if(tileX < 0 || tileY < 0 || x >= w || y >= h) {
            throw new IllegalArgumentException
                ("Tile indices are out of bounds!");
        }

        if (x + tw > w) {
            tw = w - x;
        }

        if (y + th > h) {
            th = h - y;
        }

        ImageReadParam param = getDefaultReadParam();
        Rectangle tileRect = new Rectangle(x, y, tw, th);
        param.setSourceRegion(tileRect);

        return read(imageIndex, param);
    }

    public boolean canReadRaster() {
        // Enable this?
        return false;
    }

    public Raster readRaster(int imageIndex, ImageReadParam param)
        throws IOException {
        // Enable this?
        throw new UnsupportedOperationException();
    }

//     public BufferedImage readTileRaster(int imageIndex,
//                                         int tileX, int tileY)
//         throws IOException {
//     }

    private int[] sourceBands;
    private int[] destinationBands;

    private TIFFDecompressor decompressor;

    // floor(num/den)
    private static int ifloor(int num, int den) {
        if (num < 0) {
            num -= den - 1;
        }
        return num/den;
    }

    // ceil(num/den)
    private static int iceil(int num, int den) {
        if (num > 0) {
            num += den - 1;
        }
        return num/den;
    }

    private void prepareRead(int imageIndex, ImageReadParam param)
        throws IOException {
        if (stream == null) {
            throw new IllegalStateException("Input not set!");
        }

        // A null ImageReadParam means we use the default
        if (param == null) {
            param = getDefaultReadParam();
        }

        this.imageReadParam = param;

        seekToImage(imageIndex);

        this.tileOrStripWidth = getTileOrStripWidth();
        this.tileOrStripHeight = getTileOrStripHeight();
        this.planarConfiguration = getPlanarConfiguration();

        this.sourceBands = param.getSourceBands();
        if (sourceBands == null) {
            sourceBands = new int[numBands];
            for (int i = 0; i < numBands; i++) {
                sourceBands[i] = i;
            }
        }

        // Initialize the destination image
        Iterator imageTypes = getImageTypes(imageIndex);
        ImageTypeSpecifier theImageType =
            ImageUtil.getDestinationType(param, imageTypes);

        int destNumBands = theImageType.getSampleModel().getNumBands();

        this.destinationBands = param.getDestinationBands();
        if (destinationBands == null) {
            destinationBands = new int[destNumBands];
            for (int i = 0; i < destNumBands; i++) {
                destinationBands[i] = i;
            }
        }

        if (sourceBands.length != destinationBands.length) {
            throw new IllegalArgumentException(
                              "sourceBands.length != destinationBands.length");
        }

        for (int i = 0; i < sourceBands.length; i++) {
            int sb = sourceBands[i];
            if (sb < 0 || sb >= numBands) {
                throw new IllegalArgumentException(
                                                  "Source band out of range!");
            }
            int db = destinationBands[i];
            if (db < 0 || db >= destNumBands) {
                throw new IllegalArgumentException(
                                             "Destination band out of range!");
            }
        }
    }

    public RenderedImage readAsRenderedImage(int imageIndex,
                                             ImageReadParam param)
        throws IOException {
        prepareRead(imageIndex, param);
        return new TIFFRenderedImage(this, imageIndex, imageReadParam,
                                     width, height);
    }

    private void decodeTile(int ti, int tj, int band) throws IOException {
        if(DEBUG) {
            System.out.println("decodeTile("+ti+","+tj+","+band+")");
        }

        // Compute the region covered by the strip or tile
        Rectangle tileRect = new Rectangle(ti*tileOrStripWidth,
                                           tj*tileOrStripHeight,
                                           tileOrStripWidth,
                                           tileOrStripHeight);

        // Clip against the image bounds if the image is not tiled. If it
        // is tiled, the tile may legally extend beyond the image bounds.
        if(!isImageTiled(currIndex)) {
            tileRect =
                tileRect.intersection(new Rectangle(0, 0, width, height));
        }

        // Return if the intersection is empty.
        if(tileRect.width <= 0 || tileRect.height <= 0) {
            return;
        }

        int srcMinX = tileRect.x;
        int srcMinY = tileRect.y;
        int srcWidth = tileRect.width;
        int srcHeight = tileRect.height;

        // Determine dest region that can be derived from the
        // source region

        dstMinX = iceil(srcMinX - sourceXOffset, srcXSubsampling);
        int dstMaxX = ifloor(srcMinX + srcWidth - 1 - sourceXOffset,
                         srcXSubsampling);

        dstMinY = iceil(srcMinY - sourceYOffset, srcYSubsampling);
        int dstMaxY = ifloor(srcMinY + srcHeight - 1 - sourceYOffset,
                             srcYSubsampling);

        dstWidth = dstMaxX - dstMinX + 1;
        dstHeight = dstMaxY - dstMinY + 1;

        dstMinX += dstXOffset;
        dstMinY += dstYOffset;

        // Clip against image bounds

        Rectangle dstRect = new Rectangle(dstMinX, dstMinY,
                                          dstWidth, dstHeight);
        dstRect =
            dstRect.intersection(theImage.getRaster().getBounds());

        dstMinX = dstRect.x;
        dstMinY = dstRect.y;
        dstWidth = dstRect.width;
        dstHeight = dstRect.height;

        if (dstWidth <= 0 || dstHeight <= 0) {
            return;
        }

        // Backwards map dest region to source to determine
        // active source region

        int activeSrcMinX = (dstMinX - dstXOffset)*srcXSubsampling +
            sourceXOffset;
        int sxmax =
            (dstMinX + dstWidth - 1 - dstXOffset)*srcXSubsampling +
            sourceXOffset;
        int activeSrcWidth = sxmax - activeSrcMinX + 1;

        int activeSrcMinY = (dstMinY - dstYOffset)*srcYSubsampling +
            sourceYOffset;
        int symax =
            (dstMinY + dstHeight - 1 - dstYOffset)*srcYSubsampling +
            sourceYOffset;
        int activeSrcHeight = symax - activeSrcMinY + 1;

        decompressor.setSrcMinX(srcMinX);
        decompressor.setSrcMinY(srcMinY);
        decompressor.setSrcWidth(srcWidth);
        decompressor.setSrcHeight(srcHeight);

        decompressor.setDstMinX(dstMinX);
        decompressor.setDstMinY(dstMinY);
        decompressor.setDstWidth(dstWidth);
        decompressor.setDstHeight(dstHeight);

        decompressor.setActiveSrcMinX(activeSrcMinX);
        decompressor.setActiveSrcMinY(activeSrcMinY);
        decompressor.setActiveSrcWidth(activeSrcWidth);
        decompressor.setActiveSrcHeight(activeSrcHeight);

        int tileIndex = tj*tilesAcross + ti;

        if (planarConfiguration ==
            BaselineTIFFTagSet.PLANAR_CONFIGURATION_PLANAR) {
            tileIndex += band*tilesAcross*tilesDown;
        }

        long offset = getTileOrStripOffset(tileIndex);
        long byteCount = getTileOrStripByteCount(tileIndex);

        decompressor.setStream(stream);
        decompressor.setOffset(offset);
        decompressor.setByteCount((int)byteCount);

        decompressor.beginDecoding();

        stream.mark();
        decompressor.decode();
        stream.reset();
    }

    private void reportProgress() {
        // Report image progress/update to listeners after each tile
        pixelsRead += dstWidth*dstHeight;
        processImageProgress(100.0f*pixelsRead/pixelsToRead);
        processImageUpdate(theImage,
                           dstMinX, dstMinY, dstWidth, dstHeight,
                           1, 1,
                           destinationBands);
    }

    public BufferedImage read(int imageIndex, ImageReadParam param)
        throws IOException {
        prepareRead(imageIndex, param);
        this.theImage = getDestination(param,
                                       getImageTypes(imageIndex),
                                       width, height);

        srcXSubsampling = imageReadParam.getSourceXSubsampling();
        srcYSubsampling = imageReadParam.getSourceYSubsampling();

        Point p = imageReadParam.getDestinationOffset();
        dstXOffset = p.x;
        dstYOffset = p.y;

        // This could probably be made more efficient...
        Rectangle srcRegion = new Rectangle(0, 0, 0, 0);
        Rectangle destRegion = new Rectangle(0, 0, 0, 0);

        computeRegions(imageReadParam, width, height, theImage,
                       srcRegion, destRegion);

        // Initial source pixel, taking source region and source
        // subsamplimg offsets into account
        sourceXOffset = srcRegion.x;
        sourceYOffset = srcRegion.y;

        pixelsToRead = destRegion.width*destRegion.height;
        pixelsRead = 0;

        processImageStarted(imageIndex);
        processImageProgress(0.0f);

        tilesAcross = (width + tileOrStripWidth - 1)/tileOrStripWidth;
        tilesDown = (height + tileOrStripHeight - 1)/tileOrStripHeight;

        int compression = getCompression();

        // Attempt to get decompressor and color converted from the read param

        TIFFColorConverter colorConverter = null;
        if (imageReadParam instanceof TIFFImageReadParam) {
            TIFFImageReadParam tparam =
                (TIFFImageReadParam)imageReadParam;
            this.decompressor = tparam.getTIFFDecompressor();
            colorConverter = tparam.getColorConverter();
        }

        // If we didn't find one, use a standard decompressor
        if (this.decompressor == null) {
            if (compression ==
                BaselineTIFFTagSet.COMPRESSION_NONE) {
                // Get the fillOrder field.
                TIFFField fillOrderField =
                    imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_FILL_ORDER);

                // Set the decompressor based on the fill order.
                if(fillOrderField != null && fillOrderField.getAsInt(0) == 2) {
                    this.decompressor = new TIFFLSBDecompressor();
                } else {
                    this.decompressor = new TIFFNullDecompressor();
                }
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {

                // Try to create the codecLib decompressor.
                if(PackageUtil.isCodecLibAvailable()) {
                    try {
                        this.decompressor = null;
                            //new TIFFCodecLibFaxDecompressor(compression);
                        if(DEBUG) {
                            System.out.println
                                ("Using codecLib T.6 decompressor");
                        }
                    } catch (RuntimeException re) {
                        if(DEBUG) {
                            System.out.println(re);
                        }
                    }
                }

                // Fall back to the Java decompressor.
                if (this.decompressor == null) {
                    if(DEBUG) {
                        System.out.println("Using Java T.6 decompressor");
                    }
                    this.decompressor = new TIFFFaxDecompressor();
                }
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_CCITT_T_4) {

                if(PackageUtil.isCodecLibAvailable()) {
                    // Try to create the codecLib decompressor.
                    try {
                        this.decompressor = null;
                            //new TIFFCodecLibFaxDecompressor(compression);
                        if(DEBUG) {
                            System.out.println
                                ("Using codecLib T.4 decompressor");
                        }
                    } catch (RuntimeException re) {
                        if(DEBUG) {
                            System.out.println(re);
                        }
                    }
                }

                // Fall back to the Java decompressor.
                if (this.decompressor == null) {
                    if(DEBUG) {
                        System.out.println("Using Java T.4 decompressor");
                    }
                    this.decompressor = new TIFFFaxDecompressor();
                }
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_CCITT_RLE) {
                this.decompressor = new TIFFFaxDecompressor();
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_PACKBITS) {
                if(DEBUG) {
                    System.out.println("Using TIFFPackBitsDecompressor");
                }
                this.decompressor = new TIFFPackBitsDecompressor();
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_LZW) {
                if(DEBUG) {
                    System.out.println("Using TIFFLZWDecompressor");
                }
		TIFFField predictorField =
                    imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_PREDICTOR);
		int predictor = ((predictorField == null) ?
                                 BaselineTIFFTagSet.PREDICTOR_NONE :
                                 predictorField.getAsInt(0));
                this.decompressor = new TIFFLZWDecompressor(predictor);
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_JPEG) {
                this.decompressor = new TIFFJPEGDecompressor();
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_ZLIB ||
                       compression ==
                       BaselineTIFFTagSet.COMPRESSION_DEFLATE) {
		TIFFField predictorField =
                    imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_PREDICTOR);
		int predictor = ((predictorField == null) ?
                                 BaselineTIFFTagSet.PREDICTOR_NONE :
                                 predictorField.getAsInt(0));
                this.decompressor = new TIFFDeflateDecompressor(predictor);
            } else if (compression ==
                       BaselineTIFFTagSet.COMPRESSION_OLD_JPEG) {
                TIFFField JPEGProcField =
                    imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_PROC);
                if(JPEGProcField == null) {
                    processWarningOccurred
                        ("JPEGProc field missing; assuming baseline sequential JPEG process.");
                } else if(JPEGProcField.getAsInt(0) !=
                   BaselineTIFFTagSet.JPEG_PROC_BASELINE) {
                    throw new IIOException
                        ("Old-style JPEG supported for baseline sequential JPEG process only!");
                }
                this.decompressor = new TIFFOldJPEGDecompressor();
                //throw new IIOException("Old-style JPEG not supported!");
            } else {
                throw new IIOException
                    ("Unsupported compression type (tag number = "+
                     compression+")!");
            }

            if (photometricInterpretation ==
                BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_Y_CB_CR &&
                compression != BaselineTIFFTagSet.COMPRESSION_JPEG &&
                compression != BaselineTIFFTagSet.COMPRESSION_OLD_JPEG) {
                boolean convertYCbCrToRGB =
                    theImage.getColorModel().getColorSpace().getType() ==
                    ColorSpace.TYPE_RGB;
                TIFFDecompressor wrappedDecompressor =
                    this.decompressor instanceof TIFFNullDecompressor ?
                    null : this.decompressor;
                this.decompressor =
                    new TIFFYCbCrDecompressor(wrappedDecompressor,
                                              convertYCbCrToRGB);
            }
        }

        if(DEBUG) {
            System.out.println("\nDecompressor class = "+
                               decompressor.getClass().getName()+"\n");
        }

        if (colorConverter == null) {
            if (photometricInterpretation ==
                BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_CIELAB &&
                theImage.getColorModel().getColorSpace().getType() ==
                ColorSpace.TYPE_RGB) {
                colorConverter = new TIFFCIELabColorConverter();
             } else if (photometricInterpretation ==
                        BaselineTIFFTagSet.PHOTOMETRIC_INTERPRETATION_Y_CB_CR &&
                        !(this.decompressor instanceof TIFFYCbCrDecompressor) &&
                        compression != BaselineTIFFTagSet.COMPRESSION_JPEG &&
                        compression != BaselineTIFFTagSet.COMPRESSION_OLD_JPEG) {
                 colorConverter = new TIFFYCbCrColorConverter(imageMetadata);
            }
        }

        decompressor.setReader(this);
        decompressor.setMetadata(imageMetadata);
        decompressor.setImage(theImage);

        decompressor.setPhotometricInterpretation(photometricInterpretation);
        decompressor.setCompression(compression);
        decompressor.setSamplesPerPixel(samplesPerPixel);
        decompressor.setBitsPerSample(bitsPerSample);
        decompressor.setSampleFormat(sampleFormat);
        decompressor.setExtraSamples(extraSamples);
        decompressor.setColorMap(colorMap);

        decompressor.setColorConverter(colorConverter);

        decompressor.setSourceXOffset(sourceXOffset);
        decompressor.setSourceYOffset(sourceYOffset);
        decompressor.setSubsampleX(srcXSubsampling);
        decompressor.setSubsampleY(srcYSubsampling);

        decompressor.setDstXOffset(dstXOffset);
        decompressor.setDstYOffset(dstYOffset);

        decompressor.setSourceBands(sourceBands);
        decompressor.setDestinationBands(destinationBands);

        // Compute bounds on the tile indices for this source region.
        int minTileX =
            TIFFImageWriter.XToTileX(srcRegion.x, 0, tileOrStripWidth);
        int minTileY =
            TIFFImageWriter.YToTileY(srcRegion.y, 0, tileOrStripHeight);
        int maxTileX =
            TIFFImageWriter.XToTileX(srcRegion.x + srcRegion.width - 1,
                                     0, tileOrStripWidth);
        int maxTileY =
            TIFFImageWriter.YToTileY(srcRegion.y + srcRegion.height - 1,
                                     0, tileOrStripHeight);

        if (planarConfiguration ==
            BaselineTIFFTagSet.PLANAR_CONFIGURATION_PLANAR) {

            decompressor.setPlanar(true);

            int[] sb = new int[1];
            int[] db = new int[1];
            for (int tj = minTileY; tj <= maxTileY; tj++) {
                for (int ti = minTileX; ti <= maxTileX; ti++) {
                    for (int band = 0; band < numBands; band++) {
                        sb[0] = sourceBands[band];
                        decompressor.setSourceBands(sb);
                        db[0] = destinationBands[band];
                        decompressor.setDestinationBands(db);
                        //XXX decompressor.beginDecoding();

                        decodeTile(ti, tj, band);
                    }

                    reportProgress();
                }
            }
        } else {
            //XXX decompressor.beginDecoding();

            for (int tj = minTileY; tj <= maxTileY; tj++) {
                for (int ti = minTileX; ti <= maxTileX; ti++) {
                    decodeTile(ti, tj, -1);

                    reportProgress();
                }
            }
        }

        if (abortRequested()) {
            processReadAborted();
        } else {
            processImageComplete();
        }

        return theImage;
    }

    public void reset() {
        super.reset();
        resetLocal();
    }

    protected void resetLocal() {
        stream = null;
        gotHeader = false;
        imageReadParam = getDefaultReadParam();
        streamMetadata = null;
        currIndex = -1;
        imageMetadata = null;
        imageStartPosition = new ArrayList();
        numImages = -1;
        imageTypeMap = new HashMap();
        width = -1;
        height = -1;
        numBands = -1;
        tileOrStripWidth = -1;
        tileOrStripHeight = -1;
        planarConfiguration = BaselineTIFFTagSet.PLANAR_CONFIGURATION_CHUNKY;
        rowsDone = 0;
    }

    /**
     * Package scope method to allow decompressors, for example, to
     * emit warning messages.
     */
    void forwardWarningMessage(String warning) {
        processWarningOccurred(warning);
    }
}