text:
package core

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"

	"github.com/scaleway/scaleway-cli/v2/internal/account"
	"github.com/scaleway/scaleway-cli/v2/internal/interactive"
	"github.com/scaleway/scaleway-sdk-go/logger"
	"github.com/scaleway/scaleway-sdk-go/scw"
	"github.com/spf13/pflag"
)

type BootstrapConfig struct {
	// Args to use for the command. Usually os.Args
	Args []string

	// A list of all available commands
	Commands *Commands

	// BuildInfo contains information about cli build
	BuildInfo *BuildInfo

	// Stdout stream to use. Usually os.Stdout
	Stdout io.Writer

	// Stderr stream to use. Usually os.Stderr
	Stderr io.Writer

	// Stdin stream to use. Usually os.Stdin
	Stdin io.Reader

	// If provided this client will be passed to all commands.
	// If not a client will be automatically created by the CLI using Config, Env and flags see createClient().
	Client *scw.Client

	// DisableTelemetry, if set to true this will disable telemetry report no matter what the config send_telemetry is set to.
	// This is useful when running test to avoid sending meaningless telemetries.
	DisableTelemetry bool

	// OverrideEnv overrides environment variables returned by core.ExtractEnv function.
	// This is useful for tests as it allows overriding env without relying on global state.
	OverrideEnv map[string]string

	// OverrideExec allow to override exec.Cmd.Run method. In order for this to work
	// your code must call le core.ExecCmd function to execute a given command.
	// If this function is not defined the exec.Cmd.Run function will be called directly.
	// This function is intended to be use for tests purposes.
	OverrideExec OverrideExecFunc

	// BaseContest is the base context that will be used across all function call from top to bottom.
	Ctx context.Context

	// Optional we use it if defined
	Logger *Logger

	// Default HTTPClient to use. If not provided it will use a basic http client with a simple retry policy
	// This client will be used to create SDK client, account call, version checking and telemetry
	HTTPClient *http.Client
}

// Bootstrap is the main entry point. It is directly called from main.
// BootstrapConfig.Args is usually os.Args
// BootstrapConfig.Commands is a list of command available in CLI.
func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err error) {
	// Handles Flags
	var debug bool
	var profileFlag string
	var configPathFlag string
	var outputFlag string

	flags := pflag.NewFlagSet(config.Args[0], pflag.ContinueOnError)
	flags.StringVarP(&profileFlag, "profile", "p", "", "The config profile to use")
	flags.StringVarP(&configPathFlag, "config", "c", "", "The path to the config file")
	flags.StringVarP(&outputFlag, "output", "o", "human", "Output format: json or human")
	flags.BoolVarP(&debug, "debug", "D", os.Getenv("SCW_DEBUG") == "true", "Enable debug mode")
	// Ignore unknown flag
	flags.ParseErrorsWhitelist.UnknownFlags = true
	// Make sure usage is never print by the parse method. (It should only be print by cobra)
	flags.Usage = func() {}

	// We don't do any error validation as:
	// - debug is a boolean, no possible error
	// - profileName will return proper error when we try to load profile
	// - printerType will return proper error when we create the printer
	// Furthermore additional flag can be added on a per-command basis inside cobra
	// parse would fail as these flag are not known at this time.
	_ = flags.Parse(config.Args)

	// If debug flag is set enable debug mode in SDK logger
	logLevel := logger.LogLevelWarning
	if debug {
		logLevel = logger.LogLevelDebug // enable debug mode
	}

	// We force log to os.Stderr because we dont have a scoped logger feature and it create
	// concurrency situation with golden files
	log := config.Logger
	if log == nil {
		log = &Logger{
			writer: os.Stderr,
		}
	}
	log.level = logLevel
	logger.SetLogger(log)
	log.Debugf("running: %s\n", config.Args)

	// The printer must be the first thing set in order to print errors
	printer, err := NewPrinter(&PrinterConfig{
		OutputFlag: outputFlag,
		Stdout:     config.Stdout,
		Stderr:     config.Stderr,
	})
	if err != nil {
		_, _ = fmt.Fprintln(config.Stderr, err)
		return 1, nil, err
	}
	interactive.SetOutputWriter(config.Stderr) // set printer for interactive function (always stderr).

	httpClient := config.HTTPClient
	if httpClient == nil {
		httpClient = &http.Client{
			Transport: &retryableHTTPTransport{transport: http.DefaultTransport},
		}
	}

	// An authenticated client will be created later if required.
	client := config.Client
	isClientFromBootstrapConfig := true
	if client == nil {
		isClientFromBootstrapConfig = false
		client, err = createAnonymousClient(httpClient, config.BuildInfo)
		if err != nil {
			printErr := printer.Print(err, nil)
			if printErr != nil {
				_, _ = fmt.Fprintln(config.Stderr, printErr)
			}
			return 1, nil, err
		}
	}

	// Meta store globally available variables like SDK client.
	// Meta is injected in a context object that will be passed to all commands.
	meta := &meta{
		ProfileFlag:    profileFlag,
		BinaryName:     config.Args[0],
		BuildInfo:      config.BuildInfo,
		Client:         client,
		Commands:       config.Commands,
		OverrideEnv:    config.OverrideEnv,
		OverrideExec:   config.OverrideExec,
		ConfigPathFlag: configPathFlag,
		Logger:         log,

		stdout:                      config.Stdout,
		stderr:                      config.Stderr,
		stdin:                       config.Stdin,
		result:                      nil, // result is later injected by cobra_utils.go/cobraRun()
		command:                     nil, // command is later injected by cobra_utils.go/cobraRun()
		httpClient:                  httpClient,
		isClientFromBootstrapConfig: isClientFromBootstrapConfig,
	}
	// We make sure OverrideEnv is never nil in meta.
	if meta.OverrideEnv == nil {
		meta.OverrideEnv = map[string]string{}
	}

	// If OverrideExec was not set in the config, we set a default value.
	if meta.OverrideExec == nil {
		meta.OverrideExec = defaultOverrideExec
	}

	ctx := config.Ctx
	if ctx == nil {
		ctx = context.Background()
	}
	ctx = account.InjectHTTPClient(ctx, httpClient)
	ctx = injectMeta(ctx, meta)

	// Check CLI new version when exiting the bootstrap
	defer func() { // if we plan to remove defer, do not forget logger is not set until cobra pre init func
		config.BuildInfo.checkVersion(ctx)
	}()

	// cobraBuilder will build a Cobra root command from a list of Command
	builder := cobraBuilder{
		commands: config.Commands.GetSortedCommand(),
		meta:     meta,
		ctx:      ctx,
	}

	rootCmd := builder.build()

	// ShellMode
	if len(config.Args) >= 2 && config.Args[1] == "shell" {
		RunShell(ctx, printer, meta, rootCmd, config.Args)
		return 0, meta.result, nil
	}

	// These flag are already handle at the beginning of this function but we keep this
	// declaration in order for them to be shown in the cobra usage documentation.
	rootCmd.PersistentFlags().StringVarP(&profileFlag, "profile", "p", "", "The config profile to use")
	rootCmd.PersistentFlags().StringVarP(&configPathFlag, "config", "c", "", "The path to the config file")
	rootCmd.PersistentFlags().StringVarP(&outputFlag, "output", "o", "human", "Output format: json or human, see 'scw help output' for more info")
	rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false, "Enable debug mode")
	rootCmd.SetArgs(config.Args[1:])
	err = rootCmd.Execute()

	if err != nil {
		if _, ok := err.(*interactive.InterruptError); ok {
			return 130, nil, err
		}
		errorCode := 1
		if cliErr, ok := err.(*CliError); ok && cliErr.Code != 0 {
			errorCode = cliErr.Code
		}
		printErr := printer.Print(err, nil)
		if printErr != nil {
			_, _ = fmt.Fprintln(os.Stderr, err)
		}
		return errorCode, nil, err
	}

	if meta.command != nil {
		printErr := printer.Print(meta.result, meta.command.getHumanMarshalerOpt())
		if printErr != nil {
			_, _ = fmt.Fprintln(config.Stderr, printErr)
		}
	}

	return 0, meta.result, nil
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

abc אבג xyz דהו def

אבג xyz דהו def זחט

אבג דהו אבג

abc efd dabeb

Lorem ipsum dolor sit amet

Lorem ipsum dolor
 just a test
 sit amet

Lorem ipsum dolor sit amet

Lorem
ipsum dolor sit
 amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor
 just a test
 sit amet

Lorem ipsum dolor sit amet

Lorem
ipsum dolor sit
 amet

 Just
 testing רק
 בודק

 Just
 testing what
 ever

car means אבג.

car דהו אבג.

they said "car דהו אבג."

זחט יךכ לםמ 'they said "car דהו אבג"'?

אבג abc דהו
edf זחט abrebg

abcdefg abcdefg abcdefg a abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg

abcdefg abcdefg abcdefg a abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg

redpajama_set_name: RedPajamaGithub


text:
VERSION="0.0"

# Check dependencies

PROGRAM_DEPENDENCIES=( 'antsRegistration' 'antsApplyTransforms' 'N4BiasFieldCorrection' 'Atropos' 'KellyKapowski' )
SCRIPTS_DEPENDENCIES=( 'antsBrainExtraction.sh' 'antsAtroposN4.sh' 'antsMultivariateTemplateConstruction2.sh' 'antsJointLabelFusion.sh' )

for D in ${PROGRAM_DEPENDENCIES[@]};
  do
    if [[ ! -s ${ANTSPATH}/${D} ]];
      then
        echo "Error:  we can't find the $D program."
        echo "Perhaps you need to \(re\)define \$ANTSPATH in your environment."
        exit
      fi
  done

for D in ${SCRIPT_DEPENDENCIES[@]};
  do
    if [[ ! -s ${ANTSPATH}/${D} ]];
      then
        echo "We can't find the $D script."
        echo "Perhaps you need to \(re\)define \$ANTSPATH in your environment."
        exit
      fi
  done

function Usage {
    cat <<USAGE

`basename $0` performs a longitudinal cortical thickness estimation.  The following steps
are performed:
  1. Create a single-subject template (SST) from all the anatomical images.
  2. Create priors for the SST
     a. Run the SST through the individual cortical thickness pipeline using the group
        template and associated priors.
     b. The brain extraction SST prior is created by smoothing the brain extraction
        mask created during 2a.
     c. If labeled atlases are not provided, we smooth the posteriors from 2a to create
        the SST segmentation priors, otherwise we use antsJointFusion to create a set of
        posteriors (https://github.com/ntustison/antsCookTemplatePriorsExample).
  3. Using the SST + priors, we run each time point image through the antsCorticalThickness
     pipeline.
  4. Compose (time point) -> SST and SST -> (group template) warps to deform images from the
     native anatomical space to the group template.

Usage:

`basename $0` -d imageDimension
              -e brainTemplate
              -m brainExtractionProbabilityMask
              -p brainSegmentationPriors
              <OPTARGS>
              -o outputPrefix
              \${anatomicalImages[@]}

Example:

  bash $0 -d 3 -e brainWithSkullTemplate.nii.gz -m brainPrior.nii.gz -p segmentationPriors%d.nii.gz -o output \${anatomicalImages[@]}

Required arguments:

     -d:  Image dimension                       2 or 3 (for 2- or 3-dimensional image)

     -e:  Brain segmentation template           Anatomical *intensity* template. This template is *not* skull-stripped.
                                                The following images must be in the same space as this template:
                                                    * Brain probability mask (-m)
                                                    * Segmentation priors (-p).
                                                If used, the following optional images must also be in the same space as
                                                this template:
                                                    * Registration metric mask (-f).

     -m:  Brain extraction probability mask     Brain *probability* mask in the segmentation template space. A binary mask
                                                is an acceptable probability image.

     -p:  Brain segmentation priors             Tissue *probability* priors corresponding to the image specified
                                                with the -e option.  Specified using c-style formatting, e.g.
                                                -p labelsPriors%02d.nii.gz.  We assume that the first four priors
                                                are ordered as follows
                                                  1:  csf
                                                  2:  cortical gm
                                                  3:  wm
                                                  4:  deep gm.

     -o:  Output prefix                         The following subdirectory and images are created for the single
                                                subject template
                                                  * \${OUTPUT_PREFIX}SingleSubjectTemplate/
                                                  * \${OUTPUT_PREFIX}SingleSubjectTemplate/T_template*.nii.gz
                                                A subdirectory is created for each anatomical image.

     anatomical images                          Set of multimodal input data assumed to be specified ordered as
                                                follows:
                                                  \${time1_modality1} \${time1_modality2} ... \${time1_modalityN} \\
                                                  \${time2_modality1} \${time2_modality2} ...
                                                  .
                                                  .
                                                  .
                                                  \${timeN_modality1} ...

                                                A single modality is expected by default, in which case the input images
                                                are simply ordered by time:

                                                  \${time1_modality1} \${time2_modality1} ... \${timeN_modality1}

                                                If there are multiple modalities, use the -k option to specify how many.

Optional arguments:

     -s:  image file suffix                     Any of the standard ITK IO formats e.g. nrrd, nii.gz (default), mhd

     -c:  control type                          Control for parallel computation (default 0):
                                                  0 = run serially
                                                  1 = SGE qsub
                                                  2 = use PEXEC (localhost)
                                                  3 = Apple XGrid
                                                  4 = PBS qsub
                                                  5 = SLURM.

     -t:  template for t1 registration          Anatomical *intensity* template. This template *must* be skull-stripped.
                                                This template is used to produce a final, high-quality registration between
                                                the skull-stripped single-subject template and this template.

     -a:                                        Atlases (assumed to be skull-stripped) used to cook template priors. If atlases
                                                aren't used then we simply smooth the single-subject template posteriors after
                                                passing through antsCorticalThickness.sh. Example:

                                                  -a atlas1.nii.gz -a atlas2.nii.gz ... -a atlasN.nii.gz

     -l:                                        Labels associated with each atlas, in the same order as they are specified
                                                with the -a option. The number of labels in each image is assumed to be equal
                                                to the number of priors.

     -f:  extraction registration mask          Binary metric mask defined in the segmentation template space (-e). During the
                                                registration for brain extraction, the similarity metric is only computed within
                                                this mask.

     -g:  denoise anatomical images             Denoise anatomical images (default = 0).

     -j:  number of cpu cores                   Number of cpu cores to use locally for pexec option (default 2; requires "-c 2").

     -k:  number of modalities                  Number of modalities used to construct the template (default 1):  For example,
                                                if one wanted to use multiple modalities consisting of T1, T2, and FA
                                                components ("-k 3").

     -n:  use SST cortical thickness prior      If set to '1', the cortical thickness map from the single-subject template is used
                                                as a prior constraint for each of the individual calls to antsCorticalThickness.sh
                                                (default = 0).

     -u:  use single float precision            If 1, use single float precision in registrations (default = 0).

     -v:  Atropos segmentation weight (SST)     Atropos spatial prior *probability* weight for the segmentation of the
                                                single-subject template (default = 0.25).

     -w:  Atropos segmentation weight (Indiv.)  Atropos spatial prior *probability* weight for the segmentation of the individual
                                                time points (default = 0.5).

     -x:                                        Number of iterations within Atropos (default 5).

     -q:  Use quick registration parameters     Use antsRegistrationSyNQuick.sh for some or all of the registrations.
                                                The higher the number, the more registrations are performed quickly. The options are
                                                as follows:
                                                  '-q 0' = antsRegistrationSyN.sh for everything (default)
                                                  '-q 1' = Quick registration of time points to the SST
                                                  '-q 2' = Adds quick registrations for prior cooking
                                                  '-q 3' = Quick registrations throughout.

     -r:  rigid alignment to SST                If 1, register anatomical images to the single-subject template before processing
                                                with antsCorticalThickness. This potentially reduces bias caused by variable
                                                orientation and voxel spacing (default = 0).

     -b:  keep temporary files                  Keep brain extraction/segmentation warps, etc (default = 0).

     -y:  rigid template update component       Update the single-subject template with the full affine transform (default 0).
                                                If 1, the rigid component of the affine transform will be used to update the
                                                template. Using the rigid component is desireable to reduce bias, but variations
                                                in the origin or head position across time points can cause the template head to
                                                drift out of the field of view.

     -z:  Test / debug mode                     If > 0, runs a faster version of the script. Only for testing. Implies -u 0
                                                in the antsCorticalThickness.sh script (i.e., no random seeding).
                                                Requires single thread computation for complete reproducibility.
USAGE
    exit 1
}

echoParameters() {
    cat <<PARAMETERS

    Using antsLongitudinalCorticalThickness with the following arguments:
      image dimension         = ${DIMENSION}
      anatomical image        = ${ANATOMICAL_IMAGES[@]}
      brain template          = ${BRAIN_TEMPLATE}
      extraction prior        = ${EXTRACTION_PRIOR}
      segmentation prior      = ${SEGMENTATION_PRIOR}
      output prefix           = ${OUTPUT_PREFIX}
      output image suffix     = ${OUTPUT_SUFFIX}
      registration template   = ${REGISTRATION_TEMPLATE}

    Other parameters:
      run quick               = ${RUN_QUICK}
      debug mode              = ${DEBUG_MODE}
      float precision         = ${USE_FLOAT_PRECISION}
      denoise                 = ${DENOISE}
      use random seeding      = ${USE_RANDOM_SEEDING}
      number of modalities    = ${NUMBER_OF_MODALITIES}
      number of cores         = ${CORES}
      control type            = ${DOQSUB}
      rigid alignment to SST  = ${RIGID_ALIGNMENT_TO_SST}
      average rigid component = ${AFFINE_UPDATE_FULL}

PARAMETERS
}

# Echos a command to stdout, then runs it
# Will immediately exit on error unless you set debug flag here
DEBUG_MODE=0

function logCmd() {
  cmd="$@"
  echo "BEGIN >>>>>>>>>>>>>>>>>>>>"
  echo $cmd
  ( "$@" )

  cmdExit=$?

  if [[ $cmdExit -gt 0 ]];
    then
      echo "ERROR: command exited with nonzero status $cmdExit"
      echo "Command: $cmd"
      echo
      if [[ ! $DEBUG_MODE -gt 0 ]];
        then
          exit 1
        fi
    fi

  echo "END   <<<<<<<<<<<<<<<<<<<<"
  echo
  echo

  return $cmdExit
}

################################################################################
#
# Main routine
#
################################################################################

HOSTNAME=`hostname`
DATE=`date`

CURRENT_DIR=`pwd`/
OUTPUT_DIR=${CURRENT_DIR}/tmp$RANDOM/
OUTPUT_PREFIX=${OUTPUT_DIR}/tmp
OUTPUT_SUFFIX="nii.gz"

DIMENSION=3

NUMBER_OF_MODALITIES=1

ANATOMICAL_IMAGES=()
RUN_QUICK=1
USE_RANDOM_SEEDING=1

BRAIN_TEMPLATE=""
EXTRACTION_PRIOR=""
EXTRACTION_REGISTRATION_MASK=""
SEGMENTATION_PRIOR=""
USE_SST_CORTICAL_THICKNESS_PRIOR=0
REGISTRATION_TEMPLATE=""
DO_REGISTRATION_TO_TEMPLATE=0
DENOISE=0

ATROPOS_SEGMENTATION_PRIOR_WEIGHT_SST=0.25
ATROPOS_SEGMENTATION_PRIOR_WEIGHT_TIMEPOINT=0.5
ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS=5

AFFINE_UPDATE_FULL=0

DOQSUB=0
CORES=2
RIGID_ALIGNMENT_TO_SST=0

MALF_ATLASES=()
MALF_LABELS=()
MALF_LABEL_STRINGS_FOR_PRIORS=()

################################################################################
#
# Programs and their parameters
#
################################################################################

USE_FLOAT_PRECISION=0
KEEP_TMP_IMAGES=0

if [[ $# -lt 3 ]] ; then
  Usage >&2
  exit 1
else
  while getopts "a:b:c:d:e:f:g:h:j:k:l:m:n:o:p:q:r:s:t:u:v:x:w:y:z:" OPT
    do
      case $OPT in
          a)
       MALF_ATLASES[${#MALF_ATLASES[@]}]=$OPTARG
       ;;
          b)
       KEEP_TMP_IMAGES=$OPTARG
       ;;
          c)
       DOQSUB=$OPTARG
       if [[ $DOQSUB -gt 5 ]];
         then
           echo " DOQSUB must be an integer value (0=serial, 1=SGE qsub, 2=try pexec, 3=XGrid, 4=PBS qsub, 5=SLURM ) you passed  -c $DOQSUB "
           exit 1
         fi
       ;;
          d) #dimensions
       DIMENSION=$OPTARG
       if [[ ${DIMENSION} -gt 3 || ${DIMENSION} -lt 2 ]];
         then
           echo " Error:  ImageDimension must be 2 or 3 "
           exit 1
         fi
       ;;
          e) #brain extraction anatomical image
       BRAIN_TEMPLATE=$OPTARG
       ;;
          f) #brain extraction registration mask
       EXTRACTION_REGISTRATION_MASK=$OPTARG
       ;;
          g) #denoise
       DENOISE=$OPTARG
       ;;
          h) #help
       Usage >&2
       exit 0
       ;;
          j) #number of cpu cores to use (default = 2)
       CORES=$OPTARG
       ;;
          k) #number of modalities
       NUMBER_OF_MODALITIES=$OPTARG
       ;;
          l)
       MALF_LABELS[${#MALF_LABELS[@]}]=$OPTARG
       ;;
          m) #brain extraction prior probability mask
       EXTRACTION_PRIOR=$OPTARG
       ;;
          n) # use
       USE_SST_CORTICAL_THICKNESS_PRIOR=$OPTARG
       ;;
          x) #atropos segmentation internal iterations
       ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS=$OPTARG
       ;;
          o) #output prefix
       OUTPUT_PREFIX=$OPTARG
       ;;
          p) #brain segmentation label prior image
       SEGMENTATION_PRIOR=$OPTARG
       ;;
          r) #rigid alignment to SST
       RIGID_ALIGNMENT_TO_SST=$OPTARG
       ;;
          t) #template registration image
       REGISTRATION_TEMPLATE=$OPTARG
       DO_REGISTRATION_TO_TEMPLATE=1
       ;;
          q) # run quick
       RUN_QUICK=$OPTARG
       ;;
          u) #use floating point precision
       USE_FLOAT_PRECISION=$OPTARG
       ;;
          v) #atropos prior weight for single subject template
       ATROPOS_SEGMENTATION_PRIOR_WEIGHT_SST=$OPTARG
       ;;
          w) #atropos prior weight for each individual time point
       ATROPOS_SEGMENTATION_PRIOR_WEIGHT_TIMEPOINT=$OPTARG
       ;;
          y) # 1 update with full affine, 0 for no rigid (default = 0)
       AFFINE_UPDATE_FULL=$OPTARG
       ;;
          z) #debug mode
       DEBUG_MODE=$OPTARG
       ;;
          *) # getopts issues an error message
       echo "ERROR:  unrecognized option -$OPT $OPTARG"
       exit 1
       ;;
      esac
  done
fi

FORMAT=${SEGMENTATION_PRIOR}
PREFORMAT=${FORMAT%%\%*}
POSTFORMAT=${FORMAT##*d}
FORMAT=${FORMAT#*\%}
FORMAT=${FORMAT%%d*}

REPCHARACTER=''
TOTAL_LENGTH=0
if [[ ${#FORMAT} -eq 2 ]]
  then
    REPCHARACTER=${FORMAT:0:1}
    TOTAL_LENGTH=${FORMAT:1:1}
  fi

# MAXNUMBER=$(( 10 ** $TOTAL_LENGTH ))
MAXNUMBER=1000

PRIOR_IMAGE_FILENAMES=()
WARPED_PRIOR_IMAGE_FILENAMES=()
BRAIN_SEGMENTATION_OUTPUT=${OUTPUT_PREFIX}BrainSegmentation
SEGMENTATION_WARP_OUTPUT_PREFIX=${BRAIN_SEGMENTATION_OUTPUT}Prior
SEGMENTATION_PRIOR_WARPED=${SEGMENTATION_WARP_OUTPUT_PREFIX}Warped
for (( i = 1; i < $MAXNUMBER; i++ ))
  do
    NUMBER_OF_REPS=$(( $TOTAL_LENGTH - ${#i} ))
    ROOT='';
    for(( j=0; j < $NUMBER_OF_REPS; j++ ))
      do
        ROOT=${ROOT}${REPCHARACTER}
      done
    FILENAME=${PREFORMAT}${ROOT}${i}${POSTFORMAT}
    WARPED_FILENAME=${SEGMENTATION_PRIOR_WARPED}${ROOT}${i}.${OUTPUT_SUFFIX}
    if [[ -f $FILENAME ]];
      then
        PRIOR_IMAGE_FILENAMES=( ${PRIOR_IMAGE_FILENAMES[@]} $FILENAME )
        WARPED_PRIOR_IMAGE_FILENAMES=( ${WARPED_PRIOR_IMAGE_FILENAMES[@]} $WARPED_FILENAME )
      else
        break 1
      fi
  done

NUMBER_OF_PRIOR_IMAGES=${#WARPED_PRIOR_IMAGE_FILENAMES[*]}

# Shiftsize is calculated because a variable amount of arguments can be used on the command line.
# The shiftsize variable will give the correct number of arguments to skip. Issuing shift $shiftsize will
# result in skipping that number of arguments on the command line, so that only the input images remain.
shiftsize=$(($OPTIND - 1))
shift $shiftsize
# The invocation of $* will now read all remaining arguments into the variable IMAGESETVARIABLE
IMAGESETVARIABLE=$*
NINFILES=$(($nargs - $shiftsize))
IMAGESETARRAY=()

for IMG in $IMAGESETVARIABLE
  do
    ANATOMICAL_IMAGES[${#ANATOMICAL_IMAGES[@]}]=$IMG
  done

if [[ ${#ANATOMICAL_IMAGES[@]} -eq 0 ]];
  then
    echo "Error:  no anatomical images specified."
    exit 1
  fi

if [[ $NUMBER_OF_MODALITIES -gt 1 ]];
  then
    echo "--------------------------------------------------------------------------------------"
    echo " Cortical thickness using the following ${NUMBER_OF_MODALITIES}-tuples:  "
    echo "--------------------------------------------------------------------------------------"
    for (( i = 0; i < ${#ANATOMICAL_IMAGES[@]}; i+=$NUMBER_OF_MODALITIES ))
      do
        IMAGEMETRICSET=""
        for (( j = 0; j < $ANATOMICAL_IMAGES; j++ ))
          do
            k=0
            let k=$i+$j
            IMAGEMETRICSET="$IMAGEMETRICSET ${ANATOMICAL_IMAGES[$k]}"
          done
        echo $IMAGEMETRICSET
      done
    echo "--------------------------------------------------------------------------------------"
fi

if [[ ${#MALF_ATLASES[@]} -ne ${#MALF_LABELS[@]} ]]
  then
    echo "Error:  The number of malf atlases and labels aren't equal."
  fi

# Set up various things related to RUN_QUICK

# Can't do everything fast and still get good results if there is large deformation.
# Initiate levels of fast:

# 0 - Fast SST (old ANTS) but everything else slower for quality
# 1 - + Fast antsct to SST
# 2 - + Fast MALF cooking
# 3 - + Fast everything

RUN_OLD_ANTS_SST_CREATION=1
RUN_ANTSCT_TO_SST_QUICK=0
RUN_FAST_MALF_COOKING=0
RUN_FAST_ANTSCT_TO_GROUP_TEMPLATE=0

if [[ $RUN_QUICK -gt 0 ]];
  then
    RUN_ANTSCT_TO_SST_QUICK=1
  fi

if [[ $RUN_QUICK -gt 1 ]];
  then
    RUN_FAST_MALF_COOKING=1
  fi

if [[ $RUN_QUICK -gt 2 ]];
  then
    RUN_FAST_ANTSCT_TO_GROUP_TEMPLATE=1
  fi

################################################################################
#
# Preliminaries:
#  1. Check existence of inputs
#  2. Figure out output directory and mkdir if necessary
#  3. See if $REGISTRATION_TEMPLATE is the same as $BRAIN_TEMPLATE
#
################################################################################

for (( i = 0; i < ${#ANATOMICAL_IMAGES[@]}; i++ ))
  do
  if [[ ! -f ${ANATOMICAL_IMAGES[$i]} ]];
    then
      echo "The specified image \"${ANATOMICAL_IMAGES[$i]}\" does not exist."
      exit 1
    fi
  done

if [[ ${#ANATOMICAL_IMAGES[@]} -eq ${NUMBER_OF_MODALITIES} ]];
  then
    #echo "Only one set of anatomical images.  Running antsCorticalThickness.sh on the single subject."

    #SUBJECT_ANATOMICAL_IMAGES=''
    #for (( j=0; j < $NUMBER_OF_MODALITIES; j++ ))
    # do
    #   SUBJECT_ANATOMICAL_IMAGES="${SUBJECT_ANATOMICAL_IMAGES} -a ${ANATOMICAL_IMAGES[$j]}"
    # done

    # Won't be quick unless -q 3 was specified
    # But if you are running a longitudinal script without longitudinal data, that may not be the only problem
    #if [[ $DO_REGISTRATION_TO_TEMPLATE -eq 1 ]];
    #    then
    #      logCmd ${ANTSPATH}/antsCorticalThickness.sh \
    #        -d ${DIMENSION} \
    #        -x ${ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS} \
    #        -t ${REGISTRATION_TEMPLATE} \
    #        -q ${RUN_FAST_ANTSCT_TO_GROUP_TEMPLATE} \
    #        -e ${BRAIN_TEMPLATE} \
    #        -f ${EXTRACTION_REGISTRATION_MASK} \
    #        -m ${EXTRACTION_PRIOR} \
    #        -k ${KEEP_TMP_IMAGES} \
    #        -g ${DENOISE} \
    #        -w ${ATROPOS_SEGMENTATION_PRIOR_WEIGHT_TIMEPOINT} \
    #        -z ${DEBUG_MODE} \
    #        -p ${SEGMENTATION_PRIOR} \
    #        -o ${OUTPUT_PREFIX} \
    #        ${SUBJECT_ANATOMICAL_IMAGES}
    #  fi

    #if [[ $DO_REGISTRATION_TO_TEMPLATE -eq 0 ]];
    #  then
    #     logCmd ${ANTSPATH}/antsCorticalThickness.sh \
    #       -d ${DIMENSION} \
    #       -x ${ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS} \
    #       -q ${RUN_FAST_ANTSCT_TO_GROUP_TEMPLATE} \
    #       -e ${BRAIN_TEMPLATE} \
    #       -f ${EXTRACTION_REGISTRATION_MASK} \
    #       -m ${EXTRACTION_PRIOR} \
    #       -k ${KEEP_TMP_IMAGES} \
    #       -g ${DENOISE} \
    #       -w ${ATROPOS_SEGMENTATION_PRIOR_WEIGHT_TIMEPOINT} \
    #       -z ${DEBUG_MODE} \
    #       -p ${SEGMENTATION_PRIOR} \
    #       -o ${OUTPUT_PREFIX} \
    #       ${SUBJECT_ANATOMICAL_IMAGES}
    # fi
    #exit 0

    # Use single timepoint as template
    echo "Only one set of anatomical images. Treating subject as its own template."
    OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE="${OUTPUT_PREFIX}SingleSubjectTemplate/"
    SINGLE_SUBJECT_TEMPLATE=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_template0.nii.gz
    logCmd mkdir -p ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}
    logCmd ${ANTSPATH}/DenoiseImage -d ${DIMENSION} -i ${ANATOMICAL_IMAGES[0]} -o ${SINGLE_SUBJECT_TEMPLATE}  --verbose 1
  fi

if [[ ! -f ${BRAIN_TEMPLATE} ]];
  then
    echo "The extraction template doesn't exist:"
    echo "   $BRAIN_TEMPLATE"
    exit 1
  fi
if [[ ! -f ${EXTRACTION_PRIOR} ]];
  then
    echo "The brain extraction prior doesn't exist:"
    echo "   $EXTRACTION_PRIOR"
    exit 1
  fi

if [[ $DO_REGISTRATION_TO_TEMPLATE -eq 1 ]];
  then
    if [[ ! -f ${REGISTRATION_TEMPLATE} ]]
      then
        echo "Template for registration, ${REGISTRATION_TEMPLATE}, does not exist."
        exit 1
      fi
  fi

OUTPUT_DIR=${OUTPUT_PREFIX%\/*}
if [[ ! -d $OUTPUT_DIR ]];
  then
    echo "The output directory \"$OUTPUT_DIR\" does not exist. Making it."
    mkdir -p $OUTPUT_DIR
  fi

echoParameters >&2

echo "---------------------  Running `basename $0` on $HOSTNAME  ---------------------"

time_start=`date +%s`

################################################################################
#
# Single-subject template creation
#
################################################################################

echo
echo "--------------------------------------------------------------------------------------"
echo " Creating single-subject template                                                     "
echo "--------------------------------------------------------------------------------------"
echo

TEMPLATE_MODALITY_WEIGHT_VECTOR='1'
for(( i=1; i < ${NUMBER_OF_MODALITIES}; i++ ))
  do
    TEMPLATE_MODALITY_WEIGHT_VECTOR="${TEMPLATE_MODALITY_WEIGHT_VECTOR}x1"
  done

TEMPLATE_Z_IMAGES=''

OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE="${OUTPUT_PREFIX}SingleSubjectTemplate/"

logCmd mkdir -p ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}

# Pad initial template image to avoid problems with SST drifting out of FOV
for(( i=0; i < ${NUMBER_OF_MODALITIES}; i++ ))
  do
    TEMPLATE_INPUT_IMAGE="${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}initTemplateModality${i}.nii.gz"

    logCmd ${ANTSPATH}/ImageMath 3 ${TEMPLATE_INPUT_IMAGE} PadImage ${ANATOMICAL_IMAGES[$i]} 5

    TEMPLATE_Z_IMAGES="${TEMPLATE_Z_IMAGES} -z ${TEMPLATE_INPUT_IMAGE}"
  done

SINGLE_SUBJECT_TEMPLATE=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_template0.nii.gz

time_start_sst_creation=`date +%s`

if [[ ! -f $SINGLE_SUBJECT_TEMPLATE ]];
  then

    if [[ $RUN_OLD_ANTS_SST_CREATION -gt 0 ]];
      then
        logCmd ${ANTSPATH}/antsMultivariateTemplateConstruction.sh \
          -d ${DIMENSION} \
          -o ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_ \
          -b 0 \
          -g 0.25 \
          -i 4 \
          -c ${DOQSUB} \
          -j ${CORES} \
          -k ${NUMBER_OF_MODALITIES} \
          -w ${TEMPLATE_MODALITY_WEIGHT_VECTOR} \
          -m 100x70x30x3  \
          -n 1 \
          -r 1 \
          -s CC \
          -t GR \
          -y ${AFFINE_UPDATE_FULL} \
          ${TEMPLATE_Z_IMAGES} \
          ${ANATOMICAL_IMAGES[@]}
    else
       logCmd ${ANTSPATH}/antsMultivariateTemplateConstruction2.sh \
         -d ${DIMENSION} \
         -o ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_ \
         -a 0 \
         -b 0 \
         -g 0.25 \
         -i 4 \
         -c ${DOQSUB} \
         -j ${CORES} \
         -e ${USE_FLOAT_PRECISION} \
         -k ${NUMBER_OF_MODALITIES} \
         -w ${TEMPLATE_MODALITY_WEIGHT_VECTOR} \
         -q 100x70x30x3  \
         -f 8x4x2x1 \
         -s 3x2x1x0 \
         -n 1 \
         -r 1 \
         -l 1 \
         -m CC[ 4 ] \
         -t SyN \
         -y ${AFFINE_UPDATE_FULL} \
         ${TEMPLATE_Z_IMAGES} \
         ${ANATOMICAL_IMAGES[@]}
    fi

  fi

if [[ ! -f ${SINGLE_SUBJECT_TEMPLATE} ]];
  then
    echo "Error:  The single subject template was not created.  Exiting."
    exit 1
  fi

# clean up

SINGLE_SUBJECT_ANTSCT_PREFIX=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/T_template

logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}job*.sh
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}job*.txt
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}rigid*
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}*Repaired*
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}*WarpedToTemplate*
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_template0warp.nii.gz
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_template0Affine.txt
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_templatewarplog.txt
logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}initTemplateModality*.nii.gz

# Also remove the warp files but we have to be careful to not remove the affine and
# warp files generated in subsequent steps (specifically from running the SST through
# the cortical thickness pipeline if somebody has to re-run the longitudinal pipeline

if [[ -f ${SINGLE_SUBJECT_ANTSCT_PREFIX}SubjectToTemplate1Warp.nii.gz ]];
  then

    logCmd mkdir -p ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/TmpFiles/
    logCmd mv -f ${SINGLE_SUBJECT_ANTSCT_PREFIX}SubjectToTemplate1*Warp.nii.gz \
                 ${SINGLE_SUBJECT_ANTSCT_PREFIX}SubjectToTemplate0GenericAffine.mat \
                 ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/TmpFiles/
    logCmd mv -f ${SINGLE_SUBJECT_ANTSCT_PREFIX}TemplateToSubject0*Warp.nii.gz \
                 ${SINGLE_SUBJECT_ANTSCT_PREFIX}TemplateToSubject1GenericAffine.mat \
                 ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/TmpFiles/

    logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_*Warp.nii.gz
    logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_*Affine.txt
    logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_*GenericAffine*

    logCmd mv -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/TmpFiles/* ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}
    logCmd rm -rf ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/TmpFiles/

  else

    logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_*Warp.nii.gz
    logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_*Affine.txt
    logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}T_*GenericAffine*

  fi

# Need to change the number of iterations to  -q \

time_end_sst_creation=`date +%s`
time_elapsed_sst_creation=$((time_end_sst_creation - time_start_sst_creation))

echo
echo "--------------------------------------------------------------------------------------"
echo " Done with single subject template:  $(( time_elapsed_sst_creation / 3600 ))h $(( time_elapsed_sst_creation %3600 / 60 ))m $(( time_elapsed_sst_creation % 60 ))s"
echo "--------------------------------------------------------------------------------------"
echo

################################################################################
#
#  Create template priors
#
################################################################################

SINGLE_SUBJECT_TEMPLATE_EXTRACTION_MASK=${SINGLE_SUBJECT_ANTSCT_PREFIX}BrainExtractionMask.${OUTPUT_SUFFIX}
SINGLE_SUBJECT_TEMPLATE_EXTRACTION_REGISTRATION_MASK=${SINGLE_SUBJECT_ANTSCT_PREFIX}BrainExtractionRegistrationMask.${OUTPUT_SUFFIX}
SINGLE_SUBJECT_TEMPLATE_PRIOR=${SINGLE_SUBJECT_ANTSCT_PREFIX}Priors\%${FORMAT}d.${OUTPUT_SUFFIX}
SINGLE_SUBJECT_TEMPLATE_EXTRACTION_PRIOR=${SINGLE_SUBJECT_ANTSCT_PREFIX}BrainExtractionMaskPrior.${OUTPUT_SUFFIX}
SINGLE_SUBJECT_TEMPLATE_CORTICAL_THICKNESS=${SINGLE_SUBJECT_ANTSCT_PREFIX}CorticalThickness.${OUTPUT_SUFFIX}
SINGLE_SUBJECT_TEMPLATE_SKULL_STRIPPED=${SINGLE_SUBJECT_ANTSCT_PREFIX}BrainExtractionBrain.${OUTPUT_SUFFIX}

echo
echo "--------------------------------------------------------------------------------------"
echo " Creating template priors:  running SST through antsCorticalThickness                 "
echo "--------------------------------------------------------------------------------------"
echo

time_start_priors=`date +%s`

if [[ ! -f ${SINGLE_SUBJECT_TEMPLATE_CORTICAL_THICKNESS} ]];
  then
    if [[ $DO_REGISTRATION_TO_TEMPLATE -eq 0 ]];
      then
        logCmd ${ANTSPATH}/antsCorticalThickness.sh \
          -d ${DIMENSION} -x ${ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS} \
          -q ${RUN_FAST_ANTSCT_TO_GROUP_TEMPLATE} \
          -a ${SINGLE_SUBJECT_TEMPLATE} \
          -e ${BRAIN_TEMPLATE} \
          -f ${EXTRACTION_REGISTRATION_MASK} \
          -g ${DENOISE} \
          -m ${EXTRACTION_PRIOR} \
          -k ${KEEP_TMP_IMAGES} \
          -z ${DEBUG_MODE} \
          -p ${SEGMENTATION_PRIOR} \
          -w ${ATROPOS_SEGMENTATION_PRIOR_WEIGHT_SST} \
          -o ${SINGLE_SUBJECT_ANTSCT_PREFIX}
      else
        logCmd ${ANTSPATH}/antsCorticalThickness.sh \
          -d ${DIMENSION} -x ${ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS}  \
          -t ${REGISTRATION_TEMPLATE} \
          -q ${RUN_FAST_ANTSCT_TO_GROUP_TEMPLATE} \
          -a ${SINGLE_SUBJECT_TEMPLATE} \
          -e ${BRAIN_TEMPLATE} \
          -f ${EXTRACTION_REGISTRATION_MASK} \
          -g ${DENOISE} \
          -m ${EXTRACTION_PRIOR} \
          -k ${KEEP_TMP_IMAGES} \
          -z ${DEBUG_MODE} \
          -p ${SEGMENTATION_PRIOR} \
          -w ${ATROPOS_SEGMENTATION_PRIOR_WEIGHT_SST} \
          -o ${SINGLE_SUBJECT_ANTSCT_PREFIX}
      fi
  fi

SINGLE_SUBJECT_TEMPLATE_POSTERIORS=( ${SINGLE_SUBJECT_ANTSCT_PREFIX}BrainSegmentationPosteriors*.${OUTPUT_SUFFIX} )

SINGLE_SUBJECT_TEMPLATE_POSTERIORS_EXIST=1
SINGLE_SUBJECT_TEMPLATE_PRIORS_EXIST=1

SINGLE_SUBJECT_TEMPLATE_PRIORS=()
for (( j = 0; j < ${#SINGLE_SUBJECT_TEMPLATE_POSTERIORS[@]}; j++ ))
  do
    POSTERIOR=${SINGLE_SUBJECT_TEMPLATE_POSTERIORS[$j]}

    if [[ ! -f ${POSTERIOR} ]];
      then
        SINGLE_SUBJECT_TEMPLATE_POSTERIORS_EXIST=0
        SINGLE_SUBJECT_TEMPLATE_PRIORS_EXIST=0
        break;
      fi

    SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]=${POSTERIOR/BrainSegmentationPosteriors/Priors}

    if [[ ! -f ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} ]];
      then
        SINGLE_SUBJECT_TEMPLATE_PRIORS_EXIST=0
      fi
  done

if [[ ${SINGLE_SUBJECT_TEMPLATE_POSTERIORS_EXIST} -eq 0 ]];
  then
    echo "Error:  Posteriors for the single-subject template do not exist."
    exit 1
  fi

logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_SKULL_STRIPPED} m ${SINGLE_SUBJECT_TEMPLATE} ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_MASK}
logCmd ${ANTSPATH}/SmoothImage ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_MASK} 1 ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_PRIOR} 1
logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_REGISTRATION_MASK} MD ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_MASK} 40

if [[ ${SINGLE_SUBJECT_TEMPLATE_PRIORS_EXIST} -eq 0 ]];
  then
    if [[ ${#MALF_ATLASES[@]} -eq 0 ]];
      then

        echo
        echo "   ---> Smoothing single-subject template posteriors as priors."
        echo

        for j in ${SINGLE_SUBJECT_TEMPLATE_POSTERIORS[@]}
          do
            PRIOR=${j/BrainSegmentationPosteriors/Priors}
            logCmd ${ANTSPATH}/SmoothImage ${DIMENSION} $j 1 $PRIOR 1
          done

      else

        echo
        echo "   ---> Cooking single-subject priors using antsJointLabelFusion."
        echo

        SINGLE_SUBJECT_TEMPLATE_MALF_LABELS_PREFIX=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_TEMPLATE}/T_template
        SINGLE_SUBJECT_TEMPLATE_MALF_LABELS=${SINGLE_SUBJECT_TEMPLATE_MALF_LABELS_PREFIX}Labels.nii.gz

        ATLAS_AND_LABELS_STRING=''
        for (( j=0; j < ${#MALF_ATLASES[@]}; j++ ))
          do
            ATLAS_AND_LABELS_STRING="${ATLAS_AND_LABELS_STRING} -g ${MALF_ATLASES[$j]} -l ${MALF_LABELS[$j]}"
          done

        if [[ ! -f ${SINGLE_SUBJECT_TEMPLATE_MALF_LABELS} ]];
          then
            logCmd ${ANTSPATH}/antsJointLabelFusion.sh \
              -d ${DIMENSION} \
              -q ${RUN_FAST_MALF_COOKING} \
              -x ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_MASK} \
              -c ${DOQSUB} \
              -j ${CORES} \
              -t ${SINGLE_SUBJECT_TEMPLATE_SKULL_STRIPPED} \
              -o ${SINGLE_SUBJECT_TEMPLATE_MALF_LABELS_PREFIX} \
              ${ATLAS_AND_LABELS_STRING}
          fi

        SINGLE_SUBJECT_TEMPLATE_PRIORS=()
        for (( j = 0; j < ${#SINGLE_SUBJECT_TEMPLATE_POSTERIORS[@]}; j++ ))
          do
            POSTERIOR=${SINGLE_SUBJECT_TEMPLATE_POSTERIORS[$j]}

            SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]=${POSTERIOR/BrainSegmentationPosteriors/Priors}

            let PRIOR_LABEL=$j+1
            logCmd ${ANTSPATH}/ThresholdImage ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_MALF_LABELS} ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} ${PRIOR_LABEL} ${PRIOR_LABEL} 1 0
            logCmd ${ANTSPATH}/SmoothImage ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} 1 ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} 1
          done

        TMP_CSF_POSTERIOR=${SINGLE_SUBJECT_ANTSCT_PREFIX}BrainSegmentationCsfPosteriorTmp.${OUTPUT_SUFFIX}
        logCmd ${ANTSPATH}/SmoothImage ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_POSTERIORS[0]} 1 ${TMP_CSF_POSTERIOR} 1
        logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_PRIORS[0]} max ${SINGLE_SUBJECT_TEMPLATE_PRIORS[0]} ${TMP_CSF_POSTERIOR}

        # Brian's finishing touches on "cooking"---subtract out CSF from all other priors
        for (( j = 1; j < ${#SINGLE_SUBJECT_TEMPLATE_PRIORS[@]}; j++ ))
          do
            let PRIOR_LABEL=$j+1

            logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} - ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} ${SINGLE_SUBJECT_TEMPLATE_PRIORS[0]}
            logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} WindowImage ${SINGLE_SUBJECT_TEMPLATE_PRIORS[$j]} 0 1 0 1
          done

        logCmd rm -f $TMP_CSF_POSTERIOR
        logCmd rm -f ${SINGLE_SUBJECT_TEMPLATE_MALF_LABELS_PREFIX}*log.txt
      fi
  fi

time_end_priors=`date +%s`
time_elapsed_priors=$((time_end_priors - time_start_priors))

echo
echo "--------------------------------------------------------------------------------------"
echo " Done with creating template priors:  $(( time_elapsed_priors / 3600 ))h $(( time_elapsed_priors %3600 / 60 ))m $(( time_elapsed_priors % 60 ))s"
echo "--------------------------------------------------------------------------------------"
echo

################################################################################
#
#  Run each individual subject through antsCorticalThickness
#
################################################################################

echo
echo "--------------------------------------------------------------------------------------"
echo " Run each individual through antsCorticalThickness                                    "
echo "--------------------------------------------------------------------------------------"
echo

time_start_antsct=`date +%s`

SUBJECT_COUNT=0
for (( i=0; i < ${#ANATOMICAL_IMAGES[@]}; i+=$NUMBER_OF_MODALITIES ))
  do

    BASENAME_ID=`basename ${ANATOMICAL_IMAGES[$i]}`
    BASENAME_ID=${BASENAME_ID/\.nii\.gz/}
    BASENAME_ID=${BASENAME_ID/\.nii/}

    OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS=${OUTPUT_DIR}/${BASENAME_ID}
    OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}_${SUBJECT_COUNT}

    echo $OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS

    if [[ ! -d $OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS ]];
      then
        echo "The output directory \"$OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS\" does not exist. Making it."
        mkdir -p $OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS
      fi

    let SUBJECT_COUNT=${SUBJECT_COUNT}+1

    ANATOMICAL_REFERENCE_IMAGE=${ANATOMICAL_IMAGES[$i]}

    SUBJECT_ANATOMICAL_IMAGES=''
    if [[ ${RIGID_ALIGNMENT_TO_SST} -ne 0 ]];
      then
        logCmd ${ANTSPATH}/antsRegistrationSyN.sh \
          -d ${DIMENSION} \
          -o ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_ID}RigidToSST \
          -m ${ANATOMICAL_IMAGES[$i]} \
          -f ${SINGLE_SUBJECT_TEMPLATE} \
          -t r
        logCmd rm -f ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_ID}RigidToSSTInverseWarped.nii.gz

        ANATOMICAL_REFERENCE_IMAGE=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_ID}RigidToSSTWarped.nii.gz

        let k=$i+$NUMBER_OF_MODALITIES
        for (( j=$i; j < $k; j++ ))
          do
            BASENAME_LOCAL_ID=`basename ${ANATOMICAL_IMAGES[$j]}`
            BASENAME_LOCAL_ID=${BASENAME_LOCAL_ID/\.nii\.gz/}
            BASENAME_LOCAL_ID=${BASENAME_LOCAL_ID/\.nii/}

            logCmd ${ANTSPATH}/antsApplyTransforms \
              -d ${DIMENSION} \
              -i ${ANATOMICAL_IMAGES[$j]} \
              -r ${SINGLE_SUBJECT_TEMPLATE} \
              -o ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_LOCAL_ID}RigidToSSTWarped.nii.gz \
              -n Linear \
              -t ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_ID}RigidToSST0GenericAffine.mat

            SUBJECT_ANATOMICAL_IMAGES="${SUBJECT_ANATOMICAL_IMAGES} -a ${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_LOCAL_ID}RigidToSSTWarped.nii.gz"
          done
      else
        let k=$i+$NUMBER_OF_MODALITIES
        for (( j=$i; j < $k; j++ ))
          do
            SUBJECT_ANATOMICAL_IMAGES="${SUBJECT_ANATOMICAL_IMAGES} -a ${ANATOMICAL_IMAGES[$j]}"
          done
      fi

    if [[ ${USE_SST_CORTICAL_THICKNESS_PRIOR} -ne 0 ]];
      then
        SUBJECT_ANATOMICAL_IMAGES="${SUBJECT_ANATOMICAL_IMAGES} -r ${SINGLE_SUBJECT_TEMPLATE_CORTICAL_THICKNESS}"
      fi

    OUTPUT_LOCAL_PREFIX=${OUTPUT_DIRECTORY_FOR_SINGLE_SUBJECT_CORTICAL_THICKNESS}/${BASENAME_ID}

    logCmd ${ANTSPATH}/antsCorticalThickness.sh \
      -d ${DIMENSION} -x ${ATROPOS_SEGMENTATION_INTERNAL_ITERATIONS}  \
      -q ${RUN_ANTSCT_TO_SST_QUICK} \
      ${SUBJECT_ANATOMICAL_IMAGES} \
      -e ${SINGLE_SUBJECT_TEMPLATE} \
      -m ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_PRIOR} \
      -f ${SINGLE_SUBJECT_TEMPLATE_EXTRACTION_REGISTRATION_MASK} \
      -g ${DENOISE} \
      -k ${KEEP_TMP_IMAGES} \
      -z ${DEBUG_MODE} \
      -w ${ATROPOS_SEGMENTATION_PRIOR_WEIGHT_TIMEPOINT} \
      -p ${SINGLE_SUBJECT_TEMPLATE_PRIOR} \
      -t ${SINGLE_SUBJECT_TEMPLATE_SKULL_STRIPPED} \
      -o ${OUTPUT_LOCAL_PREFIX}

    if [[ $DO_REGISTRATION_TO_TEMPLATE -eq 1 ]];
      then

        if [[ ! -f ${OUTPUT_LOCAL_PREFIX}SubjectToGroupTemplateWarp.nii.gz ]];
          then
            logCmd ${ANTSPATH}/antsApplyTransforms \
              -d ${DIMENSION} \
              -r ${REGISTRATION_TEMPLATE} \
              -o [ ${OUTPUT_LOCAL_PREFIX}SubjectToGroupTemplateWarp.nii.gz,1 ] \
              -t ${SINGLE_SUBJECT_ANTSCT_PREFIX}SubjectToTemplate1Warp.nii.gz \
              -t ${SINGLE_SUBJECT_ANTSCT_PREFIX}SubjectToTemplate0GenericAffine.mat \
              -t ${OUTPUT_LOCAL_PREFIX}SubjectToTemplate1Warp.nii.gz \
              -t ${OUTPUT_LOCAL_PREFIX}SubjectToTemplate0GenericAffine.mat
          fi

        if [[ ! -f ${OUTPUT_LOCAL_PREFIX}GroupTemplateToSubjectWarp.nii.gz ]];
          then
            logCmd ${ANTSPATH}/antsApplyTransforms \
              -d ${DIMENSION} \
              -r ${ANATOMICAL_REFERENCE_IMAGE} \
              -o [ ${OUTPUT_LOCAL_PREFIX}GroupTemplateToSubjectWarp.nii.gz,1 ] \
              -t ${OUTPUT_LOCAL_PREFIX}TemplateToSubject1GenericAffine.mat \
              -t ${OUTPUT_LOCAL_PREFIX}TemplateToSubject0Warp.nii.gz \
              -t ${SINGLE_SUBJECT_ANTSCT_PREFIX}TemplateToSubject1GenericAffine.mat \
              -t ${SINGLE_SUBJECT_ANTSCT_PREFIX}TemplateToSubject0Warp.nii.gz
          fi

        if [[ -f ${CORTICAL_LABEL_IMAGE} ]];
          then

            SUBJECT_CORTICAL_LABELS=${OUTPUT_LOCAL_PREFIX}CorticalLabels.${OUTPUT_SUFFIX}
            SUBJECT_CORTICAL_THICKNESS=${OUTPUT_LOCAL_PREFIX}CorticalThickness.${OUTPUT_SUFFIX}
            SUBJECT_TMP=${OUTPUT_LOCAL_PREFIX}Tmp.${OUTPUT_SUFFIX}
            SUBJECT_STATS=${OUTPUT_LOCAL_PREFIX}LabelThickness.csv

            if [[ ! -f ${SUBJECT_CORTICAL_LABELS} ]];
              then
                logCmd ${ANTSPATH}/antsApplyTransforms \
                  -d ${DIMENSION} \
                  -i ${CORTICAL_LABEL_IMAGE} \
                  -r ${ANATOMICAL_REFERENCE_IMAGE} \
                  -o ${SUBJECT_CORTICAL_LABELS} \
                  -n MultiLabel \
                  -t ${OUTPUT_LOCAL_PREFIX}GroupTemplateToSubjectWarp.nii.gz

                logCmd ${ANTSPATH}/ThresholdImage ${DIMENSION} ${OUTPUT_LOCAL_PREFIX}BrainSegmentation.${OUTPUT_SUFFIX} ${SUBJECT_TMP} 2 2 1 0
                logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SUBJECT_CORTICAL_LABELS} m ${SUBJECT_TMP} ${SUBJECT_CORTICAL_LABELS}
                logCmd ${ANTSPATH}/ImageMath ${DIMENSION} ${SUBJECT_STATS} LabelStats ${SUBJECT_CORTICAL_LABELS} ${SUBJECT_CORTICAL_THICKNESS}
              fi

            logCmd rm -f $SUBJECT_TMP
          fi
      fi

  done

time_end_antsct=`date +%s`
time_elapsed_antsct=$((time_end_antsct - time_start_antsct))

echo
echo "--------------------------------------------------------------------------------------"
echo " Done with individual cortical thickness:  $(( time_elapsed_antsct / 3600 ))h $(( time_elapsed_antsct %3600 / 60 ))m $(( time_elapsed_antsct % 60 ))s"
echo "--------------------------------------------------------------------------------------"
echo

time_end=`date +%s`
time_elapsed=$((time_end - time_start))

echo
echo "--------------------------------------------------------------------------------------"
echo " Done with ANTs longitudinal processing pipeline"
echo " Script executed in $time_elapsed seconds"
echo " $(( time_elapsed / 3600 ))h $(( time_elapsed %3600 / 60 ))m $(( time_elapsed % 60 ))s"
echo "--------------------------------------------------------------------------------------"

exit 0


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Extended_Description__c</name>
    <help>Käytä tätä kenttää kuvaamaan kurssia enintään 131 000 merkillä. Tämä kenttä korvaa Kuvaus-kentän.</help>
    <label>Laajennettu kuvaus</label>
</CustomFieldTranslation>


text:
require 'forwardable'

Module.module_eval do
  # Adds ability to forward methods to other objects using 'def_delegator'
  include Forwardable
end

class Object

  #extend Forwardable

  # Adds methods to put instance variables in rfm_metaclass, plus getter/setters
  # This is useful to hide instance variables in objects that would otherwise show "too much" information.
  def self.meta_attr_accessor(*names)
    meta_attr_reader(*names)
    meta_attr_writer(*names)
  end

  def self.meta_attr_reader(*names)
    names.each do |n|
      define_method(n.to_s) {rfm_metaclass.instance_variable_get("@#{n}")}
    end
  end

  def self.meta_attr_writer(*names)
    names.each do |n|
      define_method(n.to_s + "=") {|val| rfm_metaclass.instance_variable_set("@#{n}", val)}
    end
  end

  # Wrap an object in Array, if not already an Array,
  # since XmlMini doesn't know which will be returnd for any particular element.
  # See Rfm Layout & Record where this is used.
  def rfm_force_array
    return [] if self.nil?
    self.is_a?(Array) ? self : [self]
  end

  # Just testing this functionality
  def rfm_local_methods
    self.methods - self.class.superclass.methods
  end

  private

  # Like singleton_method or 'metaclass' from ActiveSupport.
  def rfm_metaclass
    class << self
      self
    end
  end

  # Get the superclass object of self.
  def rfm_super
    SuperProxy.new(self)
  end

end # Object

class Array
  # Taken from ActiveSupport extract_options!.
  def rfm_extract_options!
    last.is_a?(::Hash) ? pop : {}
  end

  # These methods allow dynamic extension of array members with other modules.
  # These methods also carry the @root object for reference, when you don't have the
  # root object explicity referenced anywhere.
  #
  # These methods might slow down array traversal, as
  # they add interpreted code to methods that were otherwise pure C.
  def rfm_extend_members(klass, caller=nil)
    @parent = caller
    @root = caller.instance_variable_get(:@root)
    @member_extension = klass
    self.instance_eval do
      class << self
        attr_accessor :parent

        alias_method 'old_reader', '[]'
        def [](*args)
          member = old_reader(*args)
          rfm_extend_member(member, @member_extension, args[0]) if args[0].is_a? Integer
          member
        end

        alias_method 'old_each', 'each'
        def each
          i = -1
          old_each do |member|
            i = i + 1
            rfm_extend_member(member, @member_extension, i)
            yield(member)
          end
        end
      end
    end unless defined? old_reader
    self
  end

  def rfm_extend_member(member, extension, i=nil)
    if member and extension
      unless member.instance_variable_get(:@root)
        member.instance_variable_set(:@root, @root)
        member.instance_variable_set(:@parent, self)
        member.instance_variable_set(:@index, i)
        member.instance_eval(){def root; @root; end}
        member.instance_eval(){def parent; @parent; end}
        member.instance_eval(){def get_index; @index; end}
      end
      member.extend(extension)
    end
  end

end # Array

class Hash
  # TODO: Possibly deprecated, delete if not used.
  def rfm_only(*keepers)
    self.dup.each_key {|k| self.delete(k) if !keepers.include?(k)}
  end

  def rfm_filter(*args)
    options = args.rfm_extract_options!
    delete = options[:delete]
    self.dup.each_key do |k|
      self.delete(k) if (delete ? args.include?(k) : !args.include?(k))
    end
  end

  # Convert hash to Rfm::CaseInsensitiveHash
  def to_cih
    new = Rfm::CaseInsensitiveHash.new
    self.each{|k,v| new[k] = v}
    new
  end
end # Hash

# Allows access to superclass object
class SuperProxy
  def initialize(obj)
    @obj = obj
  end

  def method_missing(meth, *args, &blk)
    @obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk)
  end
end # SuperProxy

class Time
  # Returns array of [date,time] in format suitable for FMP.
  def to_fm_components(reset_time_if_before_today=false)
    d = self.strftime('%m/%d/%Y')
    t = if (Date.parse(self.to_s) < Date.today) and reset_time_if_before_today==true
          "00:00:00"
        else
          self.strftime('%T')
        end
    [d,t]
  end
end # Time

class String
  def title_case
    self.gsub(/\w+/) do |word|
      word.capitalize
    end
  end
end # String


text:
module Thin
  module Backends
    # A Backend connects the server to the client. It handles:
    # * connection/disconnection to the server
    # * initialization of the connections
    # * manitoring of the active connections.
    #
    # == Implementing your own backend
    # You can create your own minimal backend by inheriting this class and
    # defining the +connect+ and +disconnect+ method.
    # If your backend is not based on EventMachine you also need to redefine
    # the +start+, +stop+, <tt>stop!</tt> and +config+ methods.
    class Base
      # Server serving the connections throught the backend
      attr_accessor :server

      # Maximum time for incoming data to arrive
      attr_accessor :timeout

      # Maximum number of file or socket descriptors that the server may open.
      attr_accessor :maximum_connections

      # Maximum number of connections that can be persistent
      attr_accessor :maximum_persistent_connections

      #allows setting of the eventmachine threadpool size
      attr_reader :threadpool_size
      def threadpool_size=(size)
        @threadpool_size = size
        EventMachine.threadpool_size = size
      end

      # Allow using threads in the backend.
      attr_writer :threaded
      def threaded?; @threaded end

      # Allow using SSL in the backend.
      attr_writer :ssl, :ssl_options
      def ssl?; @ssl end

      # Number of persistent connections currently opened
      attr_accessor :persistent_connection_count

      # Disable the use of epoll under Linux
      attr_accessor :no_epoll

      def initialize
        @connections                    = {}
        @timeout                        = Server::DEFAULT_TIMEOUT
        @persistent_connection_count    = 0
        @maximum_connections            = Server::DEFAULT_MAXIMUM_CONNECTIONS
        @maximum_persistent_connections = Server::DEFAULT_MAXIMUM_PERSISTENT_CONNECTIONS
        @no_epoll                       = false
        @ssl                            = nil
        @threaded                       = nil
        @started_reactor                = false
      end

      # Start the backend and connect it.
      def start
        @stopping = false
        starter   = proc do
          connect
          yield if block_given?
          @running = true
        end

        # Allow for early run up of eventmachine.
        if EventMachine.reactor_running?
          starter.call
        else
          @started_reactor = true
          EventMachine.run(&starter)
        end
      end

      # Stop of the backend from accepting new connections.
      def stop
        @running  = false
        @stopping = true

        # Do not accept anymore connection
        disconnect
        # Close idle persistent connections
        @connections.each_value { |connection| connection.close_connection if connection.idle? }
        stop! if @connections.empty?
      end

      # Force stop of the backend NOW, too bad for the current connections.
      def stop!
        @running  = false
        @stopping = false

        EventMachine.stop if @started_reactor && EventMachine.reactor_running?
        @connections.each_value { |connection| connection.close_connection }
        close
      end

      # Configure the backend. This method will be called before droping superuser privileges,
      # so you can do crazy stuff that require godlike powers here.
      def config
        # See http://rubyeventmachine.com/pub/rdoc/files/EPOLL.html
        EventMachine.epoll unless @no_epoll

        # Set the maximum number of socket descriptors that the server may open.
        # The process needs to have required privilege to set it higher the 1024 on
        # some systems.
        @maximum_connections = EventMachine.set_descriptor_table_size(@maximum_connections) unless Thin.win?
      end

      # Free up resources used by the backend.
      def close
      end

      # Returns +true+ if the backend is connected and running.
      def running?
        @running
      end

      def started_reactor?
        @started_reactor
      end

      # Called by a connection when it's unbinded.
      def connection_finished(connection)
        @persistent_connection_count -= 1 if connection.can_persist?
        @connections.delete(connection.__id__)

        # Finalize gracefull stop if there's no more active connection.
        stop! if @stopping && @connections.empty?
      end

      # Returns +true+ if no active connection.
      def empty?
        @connections.empty?
      end

      # Number of active connections.
      def size
        @connections.size
      end

      protected
        # Initialize a new connection to a client.
        def initialize_connection(connection)
          connection.backend                 = self
          connection.app                     = @server.app
          connection.comm_inactivity_timeout = @timeout
          connection.threaded                = @threaded

          if @ssl
            connection.start_tls(@ssl_options)
          end

          # We control the number of persistent connections by keeping
          # a count of the total one allowed yet.
          if @persistent_connection_count < @maximum_persistent_connections
            connection.can_persist!
            @persistent_connection_count += 1
          end

          @connections[connection.__id__] = connection
        end

    end
  end
end


text:
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Threading;
using namespace thomas;

namespace ThomasEngine {

	public ref class ThomasWrapper
	{
	private:

		static bool updateEditor = false;

		static Thread^ mainThread;
		static Thread^ renderThread;
		static bool playing = false;
		static ManualResetEvent^ RenderFinished;
		static ManualResetEvent^ UpdateFinished;
	public:
		delegate void UpdateEditor();
		static event UpdateEditor^ OnEditorUpdate;

		enum class ManipulatorOperation {
			TRANSLATE,
			ROTATE,
			SCALE
		};

		static void Start() {
			thomas::ThomasCore::Init();
			if (ThomasCore::Initialized())
			{
				Resources::LoadAll(Application::editorAssets);
				RenderFinished = gcnew ManualResetEvent(true);
				UpdateFinished = gcnew ManualResetEvent(false);
				ScriptingManger::Init();
				Scene::CurrentScene = gcnew Scene("test");
				LOG("Thomas fully initiated, Chugga-chugga-whoo-whoo!");
				mainThread = gcnew Thread(gcnew ThreadStart(StartEngine));
				mainThread->Name = "Thomas Engine (Main Thread)";
				mainThread->Start();

				renderThread = gcnew Thread(gcnew ThreadStart(StartRenderer));
				renderThread->Name = "Thomas Engine (Render Thread)";
				renderThread->Start();
			}

		}

		static void UpdateEditor()
		{
			updateEditor = true;
		}

		static void StartRenderer()
		{

			while (ThomasCore::Initialized())
			{
				UpdateFinished->WaitOne();
				UpdateFinished->Reset();
				Window::ClearAllWindows();
				thomas::graphics::Renderer::ProcessCommands();
				thomas::Window::PresentAllWindows();
				RenderFinished->Set();
				thomas::ThomasTime::Update();
			}
		}

		static void CopyCommandList()
		{
			thomas::Window::EndFrame(true);
			thomas::graphics::Renderer::TransferCommandList();
			thomas::editor::Gizmos::TransferGizmoCommands();
		}

		static void StartEngine()
		{
			while (ThomasCore::Initialized())
			{

				if (Scene::IsLoading())
				{
					Thread::Sleep(1000);
					continue;
				}

				Object^ lock = Scene::CurrentScene->GetGameObjectsLock();

				if (Window::WaitingForUpdate()) //Make sure that we are not rendering when resizing the window.
					RenderFinished->WaitOne();
				Window::Update();

				ThomasCore::Update();
				Monitor::Enter(lock);

				if (playing)
				{
					//Physics
					thomas::Physics::UpdateRigidbodies();
					for (int i = 0; i < Scene::CurrentScene->GameObjects->Count; i++)
					{
						GameObject^ gameObject = Scene::CurrentScene->GameObjects[i];
						if (gameObject->GetActive())
							gameObject->FixedUpdate(); //Should only be ran at fixed timeSteps.
					}
					thomas::Physics::Simulate();
				}

				//Logic
				for (int i = 0; i < Scene::CurrentScene->GameObjects->Count; i++)
				{
					GameObject^ gameObject = Scene::CurrentScene->GameObjects[i];
					if(gameObject->GetActive())
						gameObject->Update();
				}

				//Rendering

				graphics::Renderer::ClearCommands();
				editor::Gizmos::ClearGizmos();
				if (Window::GetEditorWindow() && Window::GetEditorWindow()->Initialized())
				{

					editor::EditorCamera::Render();
					for (int i = 0; i < Scene::CurrentScene->GameObjects->Count; i++)
					{
						GameObject^ gameObject = Scene::CurrentScene->GameObjects[i];
						if(gameObject->GetActive())
							gameObject->RenderGizmos();
					}

					Monitor::Enter(SelectedGameObjects);
					for each(ThomasEngine::GameObject^ gameObject in SelectedGameObjects)
					{
						if(gameObject->GetActive())
							gameObject->RenderSelectedGizmos();
					}
					Monitor::Exit(SelectedGameObjects);
					//end editor rendering

					for (object::component::Camera* camera : object::component::Camera::s_allCameras)
					{
						camera->Render();
					}
					RenderFinished->WaitOne();
					CopyCommandList();
					RenderFinished->Reset();
					UpdateFinished->Set();
				}
				Monitor::Exit(lock);

				if (updateEditor)
					OnEditorUpdate();
				updateEditor = false;
			}
			Resources::UnloadAll();
			ThomasCore::Destroy();

		}

		static void Exit() {
			thomas::ThomasCore::Exit();
		}
		static ObservableCollection<GameObject^>^ SelectedGameObjects = gcnew ObservableCollection<GameObject^>();
		static ObservableCollection<String^>^ OutputLog = gcnew ObservableCollection<String^>();

		static void CreateThomasWindow(IntPtr hWnd, bool isEditor)
		{
			if (thomas::ThomasCore::Initialized()) {
				if (isEditor)
					thomas::Window::InitEditor((HWND)hWnd.ToPointer());
				else
					thomas::Window::Create((HWND)hWnd.ToPointer());

			}

		}

		static property float FrameRate
		{
			float get() { return float(thomas::ThomasTime::GetFPS()); }
		}

		static void eventHandler(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam) {
			thomas::Window::EventHandler((HWND)hWnd.ToPointer(), msg, (WPARAM)wParam.ToPointer(), (LPARAM)lParam.ToPointer());
		}

		static void Resize(IntPtr hWnd, double width, double height)
		{
			Window* window = thomas::Window::GetWindow((HWND)hWnd.ToPointer());
			if (window)
				window->QueueResize();
		}

		static void Update()
		{
			Window::UpdateFocus();
			UpdateLog();
			if (thomas::editor::EditorCamera::HasSelectionChanged())
				UpdateSelectedObjects();
		}

		static Guid selectedGUID;
		static void Play()
		{
			ThomasEngine::Resources::OnPlay();
			Scene::CurrentScene->Play();
			playing = true;

		}

		static bool IsPlaying()
		{
			return playing;
		}

		static void Stop()
		{
			if (SelectedGameObjects->Count > 0)
				selectedGUID = SelectedGameObjects[0]->m_guid;
			else
				selectedGUID = Guid::Empty;
			playing = false;
			Scene::RestartCurrentScene();
			ThomasEngine::Resources::OnStop();
			if (selectedGUID != Guid::Empty)
			{
				GameObject^ gObj = (GameObject^)ThomasEngine::Object::Find(selectedGUID);
				if (gObj)
					SelectGameObject(gObj);
			}

		}

		static void SelectGameObject(GameObject^ gObj)
		{
			Monitor::Enter(SelectedGameObjects);
			SelectedGameObjects->Clear();
			SelectedGameObjects->Add(gObj);
			thomas::editor::EditorCamera::SelectObject((thomas::object::GameObject*)gObj->nativePtr);
			Monitor::Exit(SelectedGameObjects);

		}

		static void UnselectGameObjects()
		{
			Monitor::Enter(SelectedGameObjects);
			SelectedGameObjects->Clear();
			thomas::editor::EditorCamera::SelectObject(nullptr);
			Monitor::Exit(SelectedGameObjects);
		}

		static void UpdateSelectedObjects() {
			List<GameObject^> tempSelectedGameObjects;
			Monitor::Enter(SelectedGameObjects);
			for (thomas::object::GameObject* gameObject : thomas::editor::EditorCamera::GetSelectedObjects())
			{
				GameObject^ gObj = (GameObject^)ThomasEngine::Object::GetObject(gameObject);
				if (gObj)
					tempSelectedGameObjects.Add(gObj);
			}
			if (tempSelectedGameObjects.Count == SelectedGameObjects->Count)
			{
				if(tempSelectedGameObjects.Count > 0)
					if (tempSelectedGameObjects[0] != SelectedGameObjects[0])
					{
						SelectedGameObjects->Clear();
						for each(GameObject^ gObj in tempSelectedGameObjects)
							SelectedGameObjects->Add(gObj);
					}
			}
			else
			{
				SelectedGameObjects->Clear();
				for each(GameObject^ gObj in tempSelectedGameObjects)
					SelectedGameObjects->Add(gObj);
			}
			Monitor::Exit(SelectedGameObjects);
			thomas::editor::EditorCamera::SetHasSelectionChanged(false);
		}

		static void SetEditorGizmoManipulatorOperation(ManipulatorOperation op)
		{
			thomas::editor::EditorCamera::SetManipulatorOperation((ImGuizmo::OPERATION)op);
		}

		static ManipulatorOperation GetEditorGizmoManipulatorOperation()
		{
			return (ManipulatorOperation)thomas::editor::EditorCamera::GetManipulatorOperation();
		}

		static void ToggleEditorGizmoManipulatorMode()
		{
			thomas::editor::EditorCamera::ToggleManipulatorMode();
		}

		static void UpdateLog() {
			std::vector<std::string> nativeOutputs = thomas::ThomasCore::GetLogOutput();

			for (int i = 0; i < nativeOutputs.size(); i++) {
				String^ output = gcnew String(nativeOutputs.at(i).c_str());
				if (OutputLog->Count == 0 || OutputLog[OutputLog->Count - 1] != output)
				{
					OutputLog->Add(output);
					if (OutputLog->Count > 10)
						OutputLog->RemoveAt(0);
				}
			}
			thomas::ThomasCore::ClearLogOutput();
		}

	};

}


text:
import os
import scrapy

from scrapy.selector import Selector
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem

class CSDNImagesPipeline(ImagesPipeline):

    def file_path(self, request, response = None, info = None):
        # handle such image(with watermark) url:
        #    http://img.blog.csdn.net/20140917165912117?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFpdGk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast
        return os.sep.join((lambda x: x if '?' not in x else x.split('?')[0]+'.png')(request.url)[7:].split('/'))

    def get_media_requests(self, item, info):
        for image_url in item['image_urls']:
            yield scrapy.Request(image_url)

    def item_completed(self, results, item, info):
        if not [x['url'] for ok, x in results if ok]:
            raise DropItem("Item contains no images")
        return item


text:
package org.apache.ignite.startup.servlet;

import org.apache.ignite.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.resource.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;

/**
 * This class defines servlet-based Ignite startup. This startup can be used to start Ignite
 * inside any web container as servlet.
 *

 * This startup must be defined in {@code web.xml} file.
 *

 * <servlet>
 *     <servlet-name>Ignite</servlet-name>
 *     <servlet-class>org.apache.ignite.startup.servlet.IgniteServletStartup</servlet-class>
 *     <init-param>
 *         <param-name>cfgFilePath</param-name>
 *         <param-value>config/default-config.xml</param-value>
 *     </init-param>
 *     <load-on-startup>1</load-on-startup>
 * </servlet>
 *

 *

 * Servlet-based startup may be used in any web container like Tomcat, Jetty and etc.
 * Depending on the way this startup is deployed the Ignite instance can be accessed
 * by either all web applications or by only one. See web container class loading architecture:
 *

 *
http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html

 *
http://docs.codehaus.org/display/JETTY/Classloading

 *

 *

 *
Tomcat

 * There are two ways to start Ignite on Tomcat.
 *

 *
Ignite started when web container starts and Ignite instance is accessible only to all web applications.
 *

 *
Add Ignite libraries in Tomcat common loader.
 *         Add in file {@code $TOMCAT_HOME/conf/catalina.properties} for property {@code shared.loader}
 *         the following {@code $IGNITE_HOME/ignite.jar,$IGNITE_HOME/libs/*.jar}
 *         (replace {@code $IGNITE_HOME} with absolute path).
 *

 *
Configure startup in {@code $TOMCAT_HOME/conf/web.xml}
 *

 *         <servlet>
 *             <servlet-name>Ignite</servlet-name>
 *             <servlet-class>org.apache.ignite.startup.servlet.IgniteServletStartup</servlet-class>
 *             <init-param>
 *                 <param-name>cfgFilePath</param-name>
 *                 <param-value>config/default-config.xml</param-value>
 *             </init-param>
 *             <load-on-startup>1</load-on-startup>
 *         </servlet>
 *

 *

 *

 *

 *

 * Ignite started from WAR-file and Ignite instance is accessible only to that web application.
 * Difference with approach described above is that {@code web.xml} file and all libraries should
 * be added in WAR file without changes in Tomcat configuration files.
 *

 *

 *

 *
Jetty

 * Below is Java code example with Jetty API:
 *

 * Server service = new Server();
 *
 * service.addListener("localhost:8090");
 *
 * ServletHttpContext ctx = (ServletHttpContext)service.getContext("/");
 *
 * ServletHolder servlet = ctx.addServlet("Ignite", "/IgniteStartup",
 *      "org.apache.ignite.startup.servlet.IgniteServletStartup");
 *
 * servlet.setInitParameter("cfgFilePath", "config/default-config.xml");
 *
 * servlet.setInitOrder(1);
 *
 * servlet.start();
 *
 * service.start();
 *

 */
public class IgniteServletStartup extends HttpServlet {
    /** */
    private static final long serialVersionUID = 0L;

    /** Grid loaded flag. */
    private static boolean loaded;

    /** Configuration file path variable name. */
    private static final String cfgFilePathParam = "cfgFilePath";

    /** */
    private Collection<String> gridNames = new ArrayList<>();

    /** {@inheritDoc} */
    @SuppressWarnings({"unchecked"})
    @Override public void init() throws ServletException {
        // Avoid multiple servlet instances. Ignite should be loaded once.
        if (loaded)
            return;

        String cfgFile = getServletConfig().getInitParameter(cfgFilePathParam);

        if (cfgFile == null)
            throw new ServletException("Failed to read property: " + cfgFilePathParam);

        URL cfgUrl = U.resolveIgniteUrl(cfgFile);

        if (cfgUrl == null)
            throw new ServletException("Failed to find Spring configuration file (path provided should be " +
                "either absolute, relative to IGNITE_HOME, or relative to META-INF folder): " + cfgFile);

        try {
            IgniteBiTuple<Collection<IgniteConfiguration>, ? extends GridSpringResourceContext> t =
                IgnitionEx.loadConfigurations(cfgUrl);

            Collection<IgniteConfiguration> cfgs = t.get1();

            if (cfgs == null)
                throw new ServletException("Failed to find a single grid factory configuration in: " + cfgUrl);

            for (IgniteConfiguration cfg : cfgs) {
                assert cfg != null;

                IgniteConfiguration adapter = new IgniteConfiguration(cfg);

                Ignite ignite = IgnitionEx.start(adapter, t.get2());

                // Test if grid is not null - started properly.
                if (ignite != null)
                    gridNames.add(ignite.name());
            }
        }
        catch (IgniteCheckedException e) {
            // Stop started grids only.
            for (String name: gridNames)
                G.stop(name, true);

            throw new ServletException("Failed to start Ignite.", e);
        }

        loaded = true;
    }

    /** {@inheritDoc} */
    @Override public void destroy() {
        // Stop started grids only.
        for (String name: gridNames)
            G.stop(name, true);

        loaded = false;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(IgniteServletStartup.class, this);
    }
}


text:
package com.pi4j.device.gate;

import com.pi4j.device.access.Opener;

public interface GateOpener extends Opener {

}


text:
echo "Checking for Node.js installation..."
which node
if [ $? -eq 1 ];
then
	echo "Couldn't find a Node.js installation!"
	echo "Please follow the instruction in Readme.md"
else
	echo "Node.js installation found!"
	CURRENT=$PWD
	echo "Current Directory :${CURRENT} ! Please wait..."
	node r.js -o boilerplatejs.build.js
	echo "Created the optimized build at : ${CURRENT}/build"
fi


text:
package org.apache.helix.taskexecution;

import org.apache.helix.participant.statemachine.StateModelFactory;

public class TaskStateModelFactory extends StateModelFactory<TaskStateModel> {
  private final String _workerId;
  private final TaskFactory _taskFactory;
  private TaskResultStore _taskResultStore;

  public TaskStateModelFactory(String workerId, TaskFactory taskFactory,
      TaskResultStore taskResultStore) {
    _workerId = workerId;
    _taskFactory = taskFactory;
    _taskResultStore = taskResultStore;
  }

  @Override
  public TaskStateModel createNewStateModel(String resource, String partition) {
    TaskStateModel model = new TaskStateModel(_workerId, partition, _taskFactory, _taskResultStore);
    return model;
  }
}


text:
import React from 'react';
import { connect } from 'react-redux';

class Feature extends React.Component {
  render() {
    const {children, features, flag} = this.props;

    if (!features[flag]) {
      return null;
    }

    return React.Children.only(children);
  }
}

Feature.propTypes = {
  features: React.PropTypes.object,
  children: React.PropTypes.object,
  name: React.PropTypes.string
};

function mapStateToProps(state, ownProps) {
  const {features} = state;

  return {
    features
  };
}

export default connect(mapStateToProps)(Feature);


text:
	Back to instance list

Details for: {{widgetSetting.name}}

Instance ID

{{widgetSetting.id}}

Instance Mode

{{widgetSetting.settings.mode}}

Instance Sorting

{{widgetSetting.settings.sorting}}

Instance Source

{{widgetSetting.type}}

Widget Style Name

{{widgetSetting.name}}

Widget Style

{{widgetSetting.type}}

	<button type="button" class="btn btn-primary" ng-click="createGist()">Create gist</button>

	<button type="button" class="btn btn-default" slide-toggle="#code-output">Toggle Code Output</button>

{{generatedCode}}

		 Success! You can access the generated guide here: {{gistLink}}

Widget Preview


text:
#pragma once

#include <sys/stat.h>
#include <stdexcept>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cctype>
#include <cerrno>

#if defined(_WIN32)
# include <windows.h>
#else
# include <unistd.h>
#endif

#if defined(__linux)
# include <linux/limits.h>
#endif

namespace filesystem
{
	class Path
	{
	public:
		enum class Type
		{
			Windows = 0,
			Posix = 1,
#if defined(_WIN32)
			Native = static_cast<int>(Windows)
#else
			Native = static_cast<int>(Posix)
#endif
		};

		Path() : _type(Type::Native), _absolute(false)
		{ }

		Path(char const* str)
		{ set(str); }

		Path(std::string const& str)
		{ set(str); }

#if defined(_WIN32)
		Path(std::wstring const& wstring)
		{ set(wstring); }

		Path(wchar_t const* wstring)
		{ set(wstring); }
#endif

		Path(Path const&) = default;

		Path(Path&&) = default;

		Path& operator=(Path const&) = default;

		Path& operator=(Path&&) = default;

		size_t length() const { return _path.size(); }

		bool empty() const { return _path.empty(); }

		bool is_absolute() const { return _absolute; }

		Path make_absolute() const
		{
#if !defined(_WIN32)
			char temp[PATH_MAX];
			if (realpath(str().c_str(), temp) == NULL)
				throw std::runtime_error("Internal error in realpath(): " + std::string(strerror(errno)));
			return Path(temp);
#else
			std::wstring value = wstr(), out(MAX_PATH, '\0');
			DWORD length = GetFullPathNameW(value.c_str(), MAX_PATH, &out[0], NULL);
			if (length == 0)
				throw std::runtime_error("Internal error in realpath(): " + std::to_string(GetLastError()));
			return Path(out.substr(0, length));
#endif
		}

		bool exists() const
		{
#if defined(_WIN32)
			return GetFileAttributesW(wstr().c_str()) != INVALID_FILE_ATTRIBUTES;
#else
			struct stat sb;
        return stat(str().c_str(), &sb) == 0;
#endif
		}

		size_t file_size() const
		{
#if defined(_WIN32)
			struct _stati64 sb;
			if (_wstati64(wstr().c_str(), &sb) != 0)
				throw std::runtime_error("path::file_size(): cannot stat file \"" + str() + "\"!");
#else
			struct stat sb;
			if (stat(str().c_str(), &sb) != 0)
				throw std::runtime_error("path::file_size(): cannot stat file \"" + str() + "\"!");
#endif
			return (size_t) sb.st_size;
		}

		bool is_directory() const
		{
#if defined(_WIN32)
			DWORD result = GetFileAttributesW(wstr().c_str());
			if (result == INVALID_FILE_ATTRIBUTES)
				return false;
			return (result & FILE_ATTRIBUTE_DIRECTORY) != 0;
#else
			struct stat sb;
			if (stat(str().c_str(), &sb))
				return false;
			return S_ISDIR(sb.st_mode);
#endif
		}

		bool is_file() const
		{
#if defined(_WIN32)
			DWORD attr = GetFileAttributesW(wstr().c_str());
			return (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0);
#else
			struct stat sb;
			if (stat(str().c_str(), &sb))
				return false;
			return S_ISREG(sb.st_mode);
#endif
		}

		std::string extension() const
		{
			const std::string &name = filename();
			size_t pos = name.find_last_of(".");
			if (pos == std::string::npos)
				return "";
			return name.substr(pos + 1);
		}

		std::string filename() const
		{
			if (empty())
				return "";
			const std::string &last = _path[_path.size() - 1];
			return last;
		}

		Path parent_path() const
		{
			Path result;
			result._absolute = _absolute;

			if (_path.empty())
			{
				if (!_absolute)
					result._path.push_back("..");
			}
			else
			{
				size_t until = _path.size() - 1;
				for (size_t i = 0; i < until; ++i)
					result._path.push_back(_path[i]);
			}
			return result;
		}

		Path operator/(Path const& other) const
		{
			if (other._absolute)
				throw std::runtime_error("path::operator/(): expected a relative path!");
			if (_type != other._type)
				throw std::runtime_error("path::operator/(): expected a path of the same type!");

			Path result(*this);

			for(auto p : other._path)
				result._path.push_back(p);

			return result;
		}

		std::string str(Type type = Type::Native) const
		{
			std::ostringstream oss;

			if (_type == Type::Posix && _absolute)
				oss << "/";

			for (size_t i = 0; i < _path.size(); ++i)
			{
				oss << _path[i];
				if (i + 1 < _path.size())
					oss << (type == Type::Posix ? '/' : '\\');
			}

			return oss.str();
		}

		void set(std::string const& str, Type type = Type::Native)
		{
			_type = type;
			if (type == Type::Windows)
			{
				_path = tokenize(str, "/\\");
				_absolute = str.size() >= 2 && std::isalpha(str[0]) && str[1] == ':';
			}
			else
			{
				_path = tokenize(str, "/");
				_absolute = !str.empty() && str[0] == '/';
			}
		}

		friend std::ostream& operator<<(std::ostream& os, Path const& path)
		{
			os << path.str();
			return os;
		}

		bool remove_file()
		{
#if !defined(_WIN32)
			return std::remove(str().c_str()) == 0;
#else
			return DeleteFileW(wstr().c_str()) != 0;
#endif
		}

		bool resize_file(size_t target_length)
		{
#if !defined(_WIN32)
			return ::truncate(str().c_str(), (off_t) target_length) == 0;
#else
			HANDLE handle = CreateFileW(wstr().c_str(), GENERIC_WRITE, 0, nullptr, 0, FILE_ATTRIBUTE_NORMAL, nullptr);
			if (handle == INVALID_HANDLE_VALUE)
				return false;
			LARGE_INTEGER size;
			size.QuadPart = (LONGLONG) target_length;
			if (SetFilePointerEx(handle, size, NULL, FILE_BEGIN) == 0)
			{
				CloseHandle(handle);
				return false;
			}
			if (SetEndOfFile(handle) == 0)
			{
				CloseHandle(handle);
				return false;
			}
			CloseHandle(handle);
			return true;
#endif
		}

		static Path getcwd()
		{
#if !defined(_WIN32)
			char temp[PATH_MAX];
			if (::getcwd(temp, PATH_MAX) == NULL)
				throw std::runtime_error("Internal error in getcwd(): " + std::string(strerror(errno)));
			return Path(temp);
#else
			std::wstring temp(MAX_PATH, '\0');
			if (!_wgetcwd(&temp[0], MAX_PATH))
				throw std::runtime_error("Internal error in getcwd(): " + std::to_string(GetLastError()));
			return Path(temp.c_str());
#endif
		}

#if defined(_WIN32)
		std::wstring wstr(Type type = Type::Native) const
		{
			std::string temp = str(type);
			int size = MultiByteToWideChar(CP_UTF8, 0, &temp[0], (int)temp.size(), NULL, 0);
			std::wstring result(size, 0);
			MultiByteToWideChar(CP_UTF8, 0, &temp[0], (int)temp.size(), &result[0], size);
			return result;
		}

		void set(std::wstring const& wstring, Type type = Type::Native)
		{
			std::string string;
			if (!wstring.empty())
			{
				int size = WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(), NULL, 0, NULL, NULL);
				string.resize(size, 0);
				WideCharToMultiByte(CP_UTF8, 0, &wstring[0], (int)wstring.size(), &string[0], size, NULL, NULL);
			}
			set(string, type);
		}
#endif

		bool operator==(Path const& p) const { return p._path == _path; }
		bool operator!=(Path const& p) const { return p._path != _path; }

	private:
		static std::vector<std::string> tokenize(std::string const& string, std::string const& delim)
		{
			std::string::size_type lastPos = 0, pos = string.find_first_of(delim, lastPos);
			std::vector<std::string> tokens;

			while (lastPos != std::string::npos)
			{
				if (pos != lastPos)
					tokens.push_back(string.substr(lastPos, pos - lastPos));
				lastPos = pos;
				if (lastPos == std::string::npos || lastPos + 1 == string.length())
					break;
				pos = string.find_first_of(delim, ++lastPos);
			}

			return tokens;
		}

		Type _type;
		std::vector<std::string> _path;
		bool _absolute;
	};

	inline bool create_directory(Path const& p)
	{
#if defined(_WIN32)
		return CreateDirectoryW(p.wstr().c_str(), NULL) != 0;
#else
		return mkdir(p.str().c_str(), S_IRUSR | S_IWUSR | S_IXUSR) == 0;
#endif
	}
}


text:
import { Component, Input, NgModule, TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { McButton, McButtonModule } from '@ptsecurity/mosaic/button';
import { ThemePalette } from '@ptsecurity/mosaic/core';
import { McIconModule } from '@ptsecurity/mosaic/icon';
import { McModalModule, McModalRef, McModalService, ModalSize } from '@ptsecurity/mosaic/modal';

// tslint:disable:no-console
// tslint:disable:no-magic-numbers
// tslint:disable:no-unnecessary-class
@Component({
    selector: 'app',
    templateUrl: './template.html',
    styleUrls: ['../main.scss', './styles.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ModalDemoComponent {
    themePalette = ThemePalette;

    @ViewChild('confirmButton') confirmButton: McButton;
    @ViewChild('deleteButton') deleteButton: McButton;

    isVisible = false;
    tplModal: McModalRef;
    htmlModalVisible = false;

    isLoading = false;

    constructor(private modalService: McModalService) {}

    showConfirm() {
        const modalRef = this.modalService.success({
            mcSize: ModalSize.Small,
            mcMaskClosable: true,
            mcContent: 'Сохранить сделанные изменения в запросе "Все активы с виндой"?',
            mcOkText: 'Сохранить',
            mcCancelText: 'Отмена',
            mcOnOk: () => console.log('OK')
        });

        modalRef.afterClose.subscribe(() => this.confirmButton.focusViaKeyboard());
    }

    showDeleteConfirm() {
        const modalRef = this.modalService.delete({
            mcSize: ModalSize.Small,
            mcMaskClosable: true,
            mcContent: 'The selected action "Send to Arbor" is used in a rule' +
                ' or an alert. It will be deleted there too.

' +
                'Delete the selected action anyway?',
            mcOkText: 'Delete',
            mcCancelText: 'Cancel',
            mcWidth: '480px',
            mcOnOk: () => console.log('Delete'),
            mcOnCancel: () => console.log('Cancel')
        });

        modalRef.afterClose.subscribe(() => this.deleteButton.focusViaKeyboard());
        this.showConfirm();
    }

    createTplModal(tplTitle: TemplateRef<{}>, tplContent: TemplateRef<{}>, tplFooter: TemplateRef<{}>) {
        this.tplModal = this.modalService.create({
            mcTitle: tplTitle,
            mcContent: tplContent,
            mcFooter: tplFooter,
            mcClosable: true,
            mcOnOk: () => console.log('Click ok')
        });
    }

    createModalComponent() {
        this.modalService.open({
            mcComponent: McModalFullCustomComponent
        });
    }

    createLongModal() {
        this.modalService.create({
            mcTitle     : 'Modal Title',
            mcContent   : McModalLongCustomComponent,
            mcOkText    : 'Yes',
            mcCancelText: 'No',
            mcSize: ModalSize.Small
        });
    }

    createComponentModal() {
        let isLoading = false;
        const isShown = false;

        const modal = this.modalService.create({
            mcTitle: 'Modal Title',
            mcContent: McModalCustomComponent,
            mcComponentParams: {
                title: 'title in component',
                subtitle: 'component sub title,will be changed after 2 sec'
            },
            mcFooter: [{
                label: 'button 1',
                type: 'primary',
                mcModalMainAction: true,
                loading: () => isLoading,
                onClick: (componentInstance: any) => {
                    componentInstance.title = 'title in inner component is changed';
                }
            }, {
                label: 'button 2',
                type: 'primary',
                autoFocus: true,
                show: () => isShown,
                onClick: (componentInstance: any) => {
                    componentInstance.title = 'title in inner component is changed';
                }
            }]
        });

        modal.afterOpen.subscribe(() => {
            console.log('[afterOpen] emitted!');

            isLoading = true;
            setTimeout(() => isLoading = false, 3000);
            //
            // let isDisabled = true;
            // setTimeout(() => isDisabled = false, 2000);

            // isShown = true;
            // setTimeout(() => isShown = false, 4000);
        });

        // Return a result when closed
        modal.afterClose.subscribe((result) => console.log('[afterClose] The result is:', result));

        // delay until modal instance created
        setTimeout(
            () => {
                const instance = modal.getContentComponent();
                instance.subtitle = 'sub title is changed';
                modal.markForCheck();
            },
            2000
        );
    }

    openAndCloseAll() {
        let pos = 0;

        [ 'create', 'delete', 'success' ].forEach((method) => this.modalService[method]({
            mcOkText    : 'Confirm',
            mcCancelText: 'Cancel',
            mcMask: false,
            mcContent: `Test content: <b>${method}</b>`,
            mcStyle: { position: 'absolute', top: `${pos * 70}px`, left: `${(pos++) * 300}px` }
        }));

        this.htmlModalVisible = true;

        this.modalService.afterAllClose.subscribe(() => console.log('afterAllClose emitted!'));

        window.setTimeout(() => this.modalService.closeAll(), 5000);
    }

    destroyTplModal() {
        this.tplModal.destroy();
    }
}

@Component({
    selector: 'mc-modal-custom-long-component',
    template: `
    <ng-container *ngFor="let item of longText">

{{ item }}

    </ng-container>
  `
})
export class McModalLongCustomComponent {

    longText: any = [];

    constructor() {
        for (let i = 0; i < 50; i++) {
            this.longText.push(`text lint - ${i}`);
        }
    }
}

@Component({
    selector: 'mc-modal-custom-component',
    template: `

{{ title }}

{{ subtitle }}

        Get Modal instance in component
        <button mc-button [color]="themePalette.Primary" (click)="destroyModal()">destroy modal in the component</button>

  `
})
export class McModalCustomComponent {
    themePalette = ThemePalette;

    @Input() title: string;
    @Input() subtitle: string;

    constructor(private modal: McModalRef) { }

    destroyModal() {
        this.modal.destroy({ data: 'this the result data' });
    }
}

@Component({
    selector: 'mc-modal-full-custom-component',
    template: `
        <mc-modal-title>
            Modal Title
        </mc-modal-title>

        <mc-modal-body>

{{ title }}

{{ subtitle }}

                Get Modal instance in component
                <button mc-button [color]="themePalette.Primary" (click)="destroyModal()">destroy modal in the component</button>

        </mc-modal-body>

            <button mc-button [color]="themePalette.Primary" >Save</button>
            <button mc-button autofocus>Close</button>

  `
})
export class McModalFullCustomComponent {
    themePalette = ThemePalette;

    @Input() title: string;
    @Input() subtitle: string;

    constructor(private modal: McModalRef) { }

    destroyModal() {
        this.modal.destroy({ data: 'this the result data' });
    }
}

@NgModule({
    declarations: [
        ModalDemoComponent,
        McModalCustomComponent,
        McModalLongCustomComponent,
        McModalFullCustomComponent
    ],
    imports: [
        BrowserModule,
        McButtonModule,
        McIconModule,
        McModalModule
    ],
    bootstrap: [
        ModalDemoComponent
    ]
})
export class DemoModule {}


text:
package org.deviceconnect.android.manager.setting;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import org.deviceconnect.android.manager.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * テキストを表示するためのダイアログ.
 *
 * @author NTT DOCOMO, INC.
 */
public class TextDialogFragment extends DialogFragment {

    /**
     * バッファサイズ.
     */
    private static final int BUFFER_SIZE = 1024;

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_privacypolicy, null);
        TextView text = view.findViewById(android.R.id.text1);

        InputStream is = null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            is = getActivity().getResources().openRawResource(getArguments().getInt(Intent.EXTRA_TEXT));
            byte[] buf = new byte[BUFFER_SIZE];
            while (true) {
                int len = is.read(buf);
                if (len < 0) {
                    break;
                }
                os.write(buf, 0, len);
            }
            text.setText(new String(os.toByteArray(), "UTF-8"));
        } catch (IOException e) {
            // do-thing
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // do-thing
                }
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        builder.setTitle(getArguments().getInt(Intent.EXTRA_TITLE));
        builder.setPositiveButton(R.string.activity_settings_close, (dialog, which) -> {
            dialog.dismiss();
        });
        return builder.create();
    }
}