text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser.input;

import android.content.Context;
import android.os.IBinder;
import android.os.ResultReceiver;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

/**
 * Wrapper around Android's InputMethodManager
 */
public class InputMethodManagerWrapper {
    private final Context mContext;

    public InputMethodManagerWrapper(Context context) {
        mContext = context;
    }

    private InputMethodManager getInputMethodManager() {
        return (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    /**
     * @see android.view.inputmethod.InputMethodManager#restartInput(View)
     */
    public void restartInput(View view) {
        getInputMethodManager().restartInput(view);
    }

    /**
     * @see android.view.inputmethod.InputMethodManager#showSoftInput(View, int, ResultReceiver)
     */
    public void showSoftInput(View view, int flags, ResultReceiver resultReceiver) {
        getInputMethodManager().showSoftInput(view, flags, resultReceiver);
    }

    /**
     * @see android.view.inputmethod.InputMethodManager#isActive(View)
     */
    public boolean isActive(View view) {
        return getInputMethodManager().isActive(view);
    }

    /**
     * @see InputMethodManager#hideSoftInputFromWindow(IBinder, int, ResultReceiver)
     */
    public boolean hideSoftInputFromWindow(IBinder windowToken, int flags,
            ResultReceiver resultReceiver) {
        return getInputMethodManager().hideSoftInputFromWindow(windowToken, flags, resultReceiver);
    }

    /**
     * @see android.view.inputmethod.InputMethodManager#updateSelection(View, int, int, int, int)
     */
    public void updateSelection(View view, int selStart, int selEnd,
            int candidatesStart, int candidatesEnd) {
        getInputMethodManager().updateSelection(view, selStart, selEnd, candidatesStart,
                candidatesEnd);
    }

    /**
     * @see android.view.inputmethod.InputMethodManager#isWatchingCursor(View)
     */
    public boolean isWatchingCursor(View view) {
        return getInputMethodManager().isWatchingCursor(view);
    }

    /**
     * @see android.view.inputmethod.InputMethodManager#updateCursor(View, int, int, int, int)
     */
    public void updateCursor(View view, int left, int top, int right, int bottom) {
        getInputMethodManager().updateCursor(view, left, top, right, bottom);
    }
}


text:
You have no access here

First a Tourney System has to be chosen, in order to set up the deadlines

[back]

Setup Deadlines

	<form action="" method="post">
		<input name="sid" value="{I_ID_SEASON}" type="hidden"/>
		<input name="mod" value="deadlines" type="hidden"/>
		<input name="act" value="create" type="hidden"/>
		<input name="opt" value="" type="hidden"/>

			Startdate:
			<input class="text" name="startdate" value="{I_STARTDATE}" type="text" size="20"/> (yyyy-mm-dd)

			Length of WB round:
			<input class="text" name="wb_round_length" value="{I_WB_ROUND_LENGTH}" type="text" size="5"/> days

			Length of LB round:
			<input class="text" name="lb_round_length" value="{I_LB_ROUND_LENGTH}" type="text" size="5"/> days

			<input class="submit" type="submit" value=" Submit "/>

	</form>

	Enter how long a winners bracket round should last here.

	When you have chosen a double elimination system also enter where the half of the winners bracket length is.

	For instance you enter 7 days for winners bracket, and 4 days for losers bracket.

	The losers bracket rounds will last then alternately 4 and 3 days.

redpajama_set_name: RedPajamaGithub


text:
package org.fcrepo.client.actions;

import java.awt.event.ActionEvent;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import org.fcrepo.client.Administrator;

/**
 * Change an object or a group of object's state.
 *
 * @author Chris Wilper
 */
public class ChangeObjectState
        extends AbstractAction {

    private static final long serialVersionUID = 1L;

    private final Set<String> m_pids;

    private final String m_newState;

    public ChangeObjectState(String pid, String stateString) {
        super(stateString);
        m_pids = new HashSet<String>();
        m_pids.add(pid);
        m_newState = stateString.toUpperCase().substring(0, 1);
    }

    public ChangeObjectState(Set<String> pids, String stateString) {
        super(stateString);
        m_pids = pids;
        m_newState = stateString.toUpperCase().substring(0, 1);
    }

    public void actionPerformed(ActionEvent ae) {
        String reason =
                JOptionPane
                        .showInputDialog("Enter a log message for the state change.");
        if (reason != null) {
            try {
                Iterator<String> pidIter = m_pids.iterator();
                while (pidIter.hasNext()) {
                    String pid = pidIter.next();
                    Administrator.APIM.modifyObject(pid,
                                                    m_newState,
                                                    null,
                                                    null,
                                                    reason);
                }
                String s = "s";
                if (m_pids.size() == 1) {
                    s = "";
                }
                JOptionPane.showMessageDialog(Administrator.getDesktop(),
                                              "Success.\n" + "Set state of "
                                                      + m_pids.size()
                                                      + " object" + s + " to '"
                                                      + m_newState + "'.");
            } catch (Exception e) {
                String message = e.getMessage();
                if (message == null) {
                    message = e.getClass().getName();
                }
                Administrator.showErrorDialog(Administrator.getDesktop(),
                                              "Failure Changing State",
                                              message,
                                              e);
            }
        }
    }

}


text:
package co.cask.cdap.internal.specification;

import com.google.common.reflect.TypeToken;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 * Class representing either a {@link co.cask.cdap.api.annotation.ProcessInput}
 * or {@link co.cask.cdap.api.annotation.Tick} method. Comparing is done with method name
 * and generic parameter types.
 */
public final class FlowletMethod {
  private final Method method;
  private final TypeToken<?> inspectType;

  public FlowletMethod(Method method, TypeToken<?> inspectType) {
    this.method = method;
    this.inspectType = inspectType;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    FlowletMethod other = (FlowletMethod) o;

    // Method name have to match
    if (!method.getName().equals(other.method.getName())) {
      return false;
    }

    // Return type has to match
    if (!isSame(method.getGenericReturnType(), inspectType, other.method.getGenericReturnType(), other.inspectType)) {
      return false;
    }

    // Parameters has to match
    Type[] params1 = method.getGenericParameterTypes();
    Type[] params2 = other.method.getGenericParameterTypes();

    if (params1.length != params2.length) {
      return false;
    }

    for (int i = 0; i < params1.length; i++) {
      if (!isSame(params1[i], inspectType, params2[i], other.inspectType)) {
        return false;
      }
    }

    return true;
  }

  @Override
  public int hashCode() {
    return method.getName().hashCode();
  }

  private boolean isSame(Type type1, TypeToken<?> inspectType1, Type type2, TypeToken<?> inspectType2) {
    return inspectType1.resolveType(type1).equals(inspectType2.resolveType(type2));
  }
}


text:
import argparse
import logging
import sys
from argparse import Namespace

import nibabel as nib
import numpy as np

import rapidtide.io as tide_io
import rapidtide.util as tide_util
import rapidtide.workflows.parser_funcs as pf

LGR = logging.getLogger(__name__)

# Some default settings
DEFAULT_HISTLEN = 101
DEFAULT_DETREND_ORDER = 3
DEFAULT_GLOBAL_PCACOMPONENTS = 0.8
DEFAULT_CORRMASK_THRESHPCT = 1.0
DEFAULT_MUTUALINFO_SMOOTHINGTIME = 3.0
DEFAULT_LAGMIN = -30.0
DEFAULT_LAGMAX = 30.0
DEFAULT_SIGMALIMIT = 1000.0
DEFAULT_DESPECKLE_PASSES = 4
DEFAULT_DESPECKLE_THRESH = 5.0
DEFAULT_PASSES = 3
DEFAULT_LAGMIN_THRESH = 0.5
DEFAULT_LAGMAX_THRESH = 5.0
DEFAULT_AMPTHRESH = 0.3
DEFAULT_PICKLEFT_THRESH = 0.33
DEFAULT_SIGMATHRESH = 100.0
DEFAULT_REFINE_PCACOMPONENTS = 0.8
DEFAULT_MAXPASSES = 15
DEFAULT_REFINE_TYPE = "pca"
DEFAULT_INTERPTYPE = "univariate"
DEFAULT_WINDOW_TYPE = "hamming"
DEFAULT_GLOBALMASK_METHOD = "mean"
DEFAULT_GLOBALSIGNAL_METHOD = "sum"
DEFAULT_CORRWEIGHTING = "None"
DEFAULT_CORRTYPE = "circular"
DEFAULT_SIMILARITYMETRIC = "correlation"
DEFAULT_PEAKFIT_TYPE = "gauss"
DEFAULT_REFINE_PRENORM = "mean"
DEFAULT_REFINE_WEIGHTING = "R2"

DEFAULT_DENOISING_LAGMIN = -10.0
DEFAULT_DENOISING_LAGMAX = 10.0
DEFAULT_DENOISING_DESPECKLE_PASSES = 4
DEFAULT_DENOISING_PEAKFITTYPE = "gauss"

DEFAULT_DELAYMAPPING_LAGMIN = -10.0
DEFAULT_DELAYMAPPING_LAGMAX = 30.0
DEFAULT_DELAYMAPPING_DESPECKLE_PASSES = 4

def _get_parser():
    """
    Argument parser for rapidtide
    """
    parser = argparse.ArgumentParser(
        prog="rapidtide",
        description=("Perform a RIPTiDe time delay analysis on a dataset."),
        allow_abbrev=False,
    )

    # Required arguments
    parser.add_argument(
        "in_file",
        type=lambda x: pf.is_valid_file(parser, x),
        help="The input data file (BOLD fMRI file or NIRS text file).",
    )
    parser.add_argument(
        "outputname",
        type=str,
        help=(
            "The root name for the output files.  "
            "For BIDS compliance, this can only contain valid BIDS entities "
            "from the source data."
        ),
    )

    # Analysis types
    analysis_type = parser.add_argument_group(
        title="Analysis type",
        description=(
            "Single arguments that change default values for many "
            "arguments. "
            "Any parameter set by an analysis type can be overridden "
            "by setting that parameter explicitly. "
            "Analysis types are mutually exclusive with one another."
        ),
    ).add_mutually_exclusive_group()
    analysis_type.add_argument(
        "--denoising",
        dest="denoising",
        action="store_true",
        help=(
            "Preset for hemodynamic denoising - this is a macro that "
            f"sets lagmin={DEFAULT_DENOISING_LAGMIN}, lagmax={DEFAULT_DENOISING_LAGMAX}, "
            f"passes=3, despeckle_passes={DEFAULT_DENOISING_DESPECKLE_PASSES}, "
            f"refineoffset=True, peakfittype={DEFAULT_DENOISING_PEAKFITTYPE}, doglmfilt=True. "
            "Any of these options can be overridden with the appropriate "
            "additional arguments."
        ),
        default=False,
    )
    analysis_type.add_argument(
        "--delaymapping",
        dest="delaymapping",
        action="store_true",
        help=(
            "Preset for delay mapping analysis - this is a macro that "
            f"sets lagmin={DEFAULT_DELAYMAPPING_LAGMIN}, lagmax={DEFAULT_DELAYMAPPING_LAGMAX}, "
            f"passes=3, despeckle_passes={DEFAULT_DELAYMAPPING_DESPECKLE_PASSES}, "
            "refineoffset=True, pickleft=True, limitoutput=True, "
            "doglmfilt=False. "
            "Any of these options can be overridden with the appropriate "
            "additional arguments."
        ),
        default=False,
    )

    # Macros
    macros = parser.add_argument_group(
        title="Macros",
        description=(
            "Single arguments that change default values for many "
            "arguments. "
            "Macros override individually set parameters. "
            "Macros are mutually exclusive with one another."
        ),
    ).add_mutually_exclusive_group()
    macros.add_argument(
        "--venousrefine",
        dest="venousrefine",
        action="store_true",
        help=(
            "This is a macro that sets --lagminthresh=2.5, "
            "--lagmaxthresh=6.0, --ampthresh=0.5, and "
            "--refineupperlag to bias refinement towards "
            "voxels in the draining vasculature for an "
            "fMRI scan."
        ),
        default=False,
    )
    macros.add_argument(
        "--nirs",
        dest="nirs",
        action="store_true",
        help=(
            "This is a NIRS analysis - this is a macro that "
            "sets --nothresh,"
            "--refineprenorm=var, --ampthresh=0.7, and "
            "--lagminthresh=0.1. "
        ),
        default=False,
    )

    # Preprocessing options
    preproc = parser.add_argument_group("Preprocessing options")
    realtr = preproc.add_mutually_exclusive_group()
    realtr.add_argument(
        "--datatstep",
        dest="realtr",
        action="store",
        metavar="TSTEP",
        type=lambda x: pf.is_float(parser, x),
        help=(
            "Set the timestep of the data file to TSTEP. "
            "This will override the TR in an "
            "fMRI file. NOTE: if using data from a text "
            "file, for example with NIRS data, using one "
            "of these options is mandatory. "
        ),
        default="auto",
    )
    realtr.add_argument(
        "--datafreq",
        dest="realtr",
        action="store",
        metavar="FREQ",
        type=lambda x: pf.invert_float(parser, x),
        help=(
            "Set the timestep of the data file to 1/FREQ. "
            "This will override the TR in an "
            "fMRI file. NOTE: if using data from a text "
            "file, for example with NIRS data, using one "
            "of these options is mandatory. "
        ),
        default="auto",
    )
    preproc.add_argument(
        "--noantialias",
        dest="antialias",
        action="store_false",
        help="Disable antialiasing filter. ",
        default=True,
    )
    preproc.add_argument(
        "--invert",
        dest="invertregressor",
        action="store_true",
        help=("Invert the sign of the regressor before processing."),
        default=False,
    )
    preproc.add_argument(
        "--interptype",
        dest="interptype",
        action="store",
        type=str,
        choices=["univariate", "cubic", "quadratic"],
        help=(
            "Use specified interpolation type. Options "
            'are "cubic", "quadratic", and "univariate". '
            f"Default is {DEFAULT_INTERPTYPE}. "
        ),
        default=DEFAULT_INTERPTYPE,
    )
    preproc.add_argument(
        "--offsettime",
        dest="offsettime",
        action="store",
        type=float,
        metavar="OFFSETTIME",
        help="Apply offset OFFSETTIME to the lag regressors.",
        default=0.0,
    )
    preproc.add_argument(
        "--autosync",
        dest="autosync",
        action="store_true",
        help=(
            "Estimate and apply the initial offsettime of an external "
            "regressor using the global crosscorrelation. "
            "Overrides offsettime if present."
        ),
        default=False,
    )

    # Add filter options
    pf.addfilteropts(parser, filtertarget="data and regressors", details=True)

    # Add permutation options
    pf.addpermutationopts(parser)

    # add window options
    pf.addwindowopts(parser, windowtype=DEFAULT_WINDOW_TYPE)

    preproc.add_argument(
        "--detrendorder",
        dest="detrendorder",
        action="store",
        type=int,
        metavar="ORDER",
        help=(f"Set order of trend removal (0 to disable). Default is {DEFAULT_DETREND_ORDER}."),
        default=DEFAULT_DETREND_ORDER,
    )
    preproc.add_argument(
        "--spatialfilt",
        dest="gausssigma",
        action="store",
        type=float,
        metavar="GAUSSSIGMA",
        help=(
            "Spatially filter fMRI data prior to analysis "
            "using GAUSSSIGMA in mm.  Set GAUSSSIGMA negative "
            "to have rapidtide set it to half the mean voxel "
            "dimension (a rule of thumb for a good value)."
        ),
        default=0.0,
    )
    preproc.add_argument(
        "--globalmean",
        dest="useglobalref",
        action="store_true",
        help=(
            "Generate a global mean regressor and use that as the reference "
            "regressor.  If no external regressor is specified, this "
            "is enabled by default."
        ),
        default=False,
    )
    preproc.add_argument(
        "--globalmaskmethod",
        dest="globalmaskmethod",
        action="store",
        type=str,
        choices=["mean", "variance"],
        help=(
            "Select whether to use timecourse mean or variance to "
            "mask voxels prior to generating global mean. "
            f'Default is "{DEFAULT_GLOBALMASK_METHOD}".'
        ),
        default=DEFAULT_GLOBALMASK_METHOD,
    )
    preproc.add_argument(
        "--globalpreselect",
        dest="globalpreselect",
        action="store_true",
        help=(
            "Treat this run as an initial pass to locate good candidate voxels for global mean "
            "regressor generation."
        ),
        default=False,
    )
    preproc.add_argument(
        "--globalmeaninclude",
        dest="globalmeanincludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Only use voxels in mask file NAME for global regressor "
            "generation (if VALSPEC is given, only voxels "
            "with integral values listed in VALSPEC are used)."
        ),
        default=None,
    )
    preproc.add_argument(
        "--globalmeanexclude",
        dest="globalmeanexcludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Do not use voxels in mask file NAME for global regressor "
            "generation (if VALSPEC is given, only voxels "
            "with integral values listed in VALSPEC are excluded)."
        ),
        default=None,
    )
    preproc.add_argument(
        "--motionfile",
        dest="motionfilespec",
        metavar="MOTFILE",
        help=(
            "Read 6 columns of motion regressors out of MOTFILE file (.par or BIDS .json) "
            "(with timepoints rows) and regress their derivatives "
            "and delayed derivatives out of the data prior to analysis. "
        ),
        default=None,
    )
    preproc.add_argument(
        "--motpos",
        dest="mot_pos",
        action="store_true",
        help=(
            "Toggle whether displacement regressors will be used in motion "
            "regression. Default is False. "
        ),
        default=False,
    )
    preproc.add_argument(
        "--motderiv",
        dest="mot_deriv",
        action="store_false",
        help=(
            "Toggle whether derivatives will be used in motion regression.  " "Default is True. "
        ),
        default=True,
    )
    preproc.add_argument(
        "--motdelayderiv",
        dest="mot_delayderiv",
        action="store_true",
        help=(
            "Toggle whether delayed derivative regressors will be used in "
            "motion regression.  Default is False. "
        ),
        default=False,
    )
    preproc.add_argument(
        "--globalsignalmethod",
        dest="globalsignalmethod",
        action="store",
        type=str,
        choices=["sum", "meanscale", "pca"],
        help=(
            "The method for constructing the initial global signal regressor - straight summation, "
            "mean scaling each voxel prior to summation, or MLE PCA of the voxels in the global signal mask. "
            f'Default is "{DEFAULT_GLOBALSIGNAL_METHOD}."'
        ),
        default=DEFAULT_GLOBALSIGNAL_METHOD,
    )
    preproc.add_argument(
        "--globalpcacomponents",
        dest="globalpcacomponents",
        action="store",
        type=float,
        metavar="VALUE",
        help=(
            "Number of PCA components used for estimating the global signal.  If VALUE >= 1, will retain this"
            "many components.  If "
            "0.0 < VALUE < 1.0, enough components will be retained to explain the fraction VALUE of the "
            "total variance. If VALUE is negative, the number of components will be to retain will be selected "
            f"automatically using the MLE method.  Default is {DEFAULT_GLOBAL_PCACOMPONENTS}."
        ),
        default=DEFAULT_GLOBAL_PCACOMPONENTS,
    )
    preproc.add_argument(
        "--slicetimes",
        dest="slicetimes",
        action="store",
        type=lambda x: pf.is_valid_file(parser, x),
        metavar="FILE",
        help=("Apply offset times from FILE to each slice in the dataset."),
        default=None,
    )
    preproc.add_argument(
        "--numskip",
        dest="preprocskip",
        action="store",
        type=int,
        metavar="SKIP",
        help=(
            "SKIP TRs were previously deleted during "
            "preprocessing (e.g. if you have done your preprocessing "
            "in FSL and set dummypoints to a nonzero value.) Default is 0. "
        ),
        default=0,
    )
    preproc.add_argument(
        "--timerange",
        dest="timerange",
        action="store",
        nargs=2,
        type=int,
        metavar=("START", "END"),
        help=(
            "Limit analysis to data between timepoints "
            "START and END in the fmri file. If END is set to -1, "
            "analysis will go to the last timepoint.  Negative values "
            "of START will be set to 0. Default is to use all timepoints."
        ),
        default=(-1, -1),
    )
    preproc.add_argument(
        "--nothresh",
        dest="nothresh",
        action="store_true",
        help=("Disable voxel intensity threshold (especially useful for NIRS " "data)."),
        default=False,
    )

    # Correlation options
    corr = parser.add_argument_group("Correlation options")
    corr.add_argument(
        "--oversampfac",
        dest="oversampfactor",
        action="store",
        type=int,
        metavar="OVERSAMPFAC",
        help=(
            "Oversample the fMRI data by the following "
            "integral factor.  Set to -1 for automatic selection (default)."
        ),
        default=-1,
    )
    corr.add_argument(
        "--regressor",
        dest="regressorfile",
        action="store",
        type=lambda x: pf.is_valid_file(parser, x),
        metavar="FILE",
        help=(
            "Read the initial probe regressor from file FILE (if not "
            "specified, generate and use the global regressor)."
        ),
        default=None,
    )

    reg_group = corr.add_mutually_exclusive_group()
    reg_group.add_argument(
        "--regressorfreq",
        dest="inputfreq",
        action="store",
        type=lambda x: pf.is_float(parser, x),
        metavar="FREQ",
        help=(
            "Probe regressor in file has sample "
            "frequency FREQ (default is 1/tr) "
            "NB: --regressorfreq and --regressortstep) "
            "are two ways to specify the same thing."
        ),
        default="auto",
    )
    reg_group.add_argument(
        "--regressortstep",
        dest="inputfreq",
        action="store",
        type=lambda x: pf.invert_float(parser, x),
        metavar="TSTEP",
        help=(
            "Probe regressor in file has sample "
            "frequency FREQ (default is 1/tr) "
            "NB: --regressorfreq and --regressortstep) "
            "are two ways to specify the same thing."
        ),
        default="auto",
    )

    corr.add_argument(
        "--regressorstart",
        dest="inputstarttime",
        action="store",
        type=float,
        metavar="START",
        help=(
            "The time delay in seconds into the regressor "
            "file, corresponding in the first TR of the fMRI "
            "file (default is 0.0)."
        ),
        default=0.0,
    )
    corr.add_argument(
        "--corrweighting",
        dest="corrweighting",
        action="store",
        type=str,
        choices=["None", "phat", "liang", "eckart"],
        help=(
            "Method to use for cross-correlation weighting. "
            f'Default is "{DEFAULT_CORRWEIGHTING}".'
        ),
        default=DEFAULT_CORRWEIGHTING,
    )
    corr.add_argument(
        "--corrtype",
        dest="corrtype",
        action="store",
        type=str,
        choices=["linear", "circular"],
        help=("Cross-correlation type (linear or circular). " f'Default is "{DEFAULT_CORRTYPE}".'),
        default=DEFAULT_CORRTYPE,
    )

    mask_group = corr.add_mutually_exclusive_group()
    mask_group.add_argument(
        "--corrmaskthresh",
        dest="corrmaskthreshpct",
        action="store",
        type=float,
        metavar="PCT",
        help=(
            "Do correlations in voxels where the mean "
            "exceeds this percentage of the robust max. "
            f"Default is {DEFAULT_CORRMASK_THRESHPCT}. "
        ),
        default=DEFAULT_CORRMASK_THRESHPCT,
    )
    mask_group.add_argument(
        "--corrmask",
        dest="corrmaskincludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Only do correlations in nonzero voxels in NAME "
            "(if VALSPEC is given, only voxels "
            "with integral values listed in VALSPEC are used). "
        ),
        default=None,
    )

    corr.add_argument(
        "--similaritymetric",
        dest="similaritymetric",
        action="store",
        type=str,
        choices=["correlation", "mutualinfo", "hybrid"],
        help=(
            "Similarity metric for finding delay values.  "
            'Choices are "correlation", "mutualinfo", and "hybrid". '
            f"Default is {DEFAULT_SIMILARITYMETRIC}."
        ),
        default=DEFAULT_SIMILARITYMETRIC,
    )
    corr.add_argument(
        "--mutualinfosmoothingtime",
        dest="smoothingtime",
        action="store",
        type=float,
        metavar="TAU",
        help=(
            "Time constant of a temporal smoothing function to apply to the "
            "mutual information function. "
            f"Default is {DEFAULT_MUTUALINFO_SMOOTHINGTIME} seconds.  "
            "TAU <=0.0 disables smoothing."
        ),
        default=DEFAULT_MUTUALINFO_SMOOTHINGTIME,
    )

    # Correlation fitting options
    corr_fit = parser.add_argument_group("Correlation fitting options")

    fixdelay = corr_fit.add_mutually_exclusive_group()
    fixdelay.add_argument(
        "--fixdelay",
        dest="fixeddelayvalue",
        action="store",
        type=float,
        metavar="DELAYTIME",
        help=("Don't fit the delay time - set it to DELAYTIME seconds for all " "voxels."),
        default=None,
    )
    fixdelay.add_argument(
        "--searchrange",
        dest="lag_extrema",
        action=pf.IndicateSpecifiedAction,
        nargs=2,
        type=float,
        metavar=("LAGMIN", "LAGMAX"),
        help=(
            "Limit fit to a range of lags from LAGMIN to "
            f"LAGMAX.  Default is {DEFAULT_LAGMIN} to {DEFAULT_LAGMAX} seconds. "
        ),
        default=(DEFAULT_LAGMIN, DEFAULT_LAGMAX),
    )
    corr_fit.add_argument(
        "--sigmalimit",
        dest="widthlimit",
        action="store",
        type=float,
        metavar="SIGMALIMIT",
        help=(
            "Reject lag fits with linewidth wider than "
            f"SIGMALIMIT Hz. Default is {DEFAULT_SIGMALIMIT} Hz."
        ),
        default=DEFAULT_SIGMALIMIT,
    )
    corr_fit.add_argument(
        "--bipolar",
        dest="bipolar",
        action="store_true",
        help=("Bipolar mode - match peak correlation ignoring sign."),
        default=False,
    )
    corr_fit.add_argument(
        "--nofitfilt",
        dest="zerooutbadfit",
        action="store_false",
        help=("Do not zero out peak fit values if fit fails."),
        default=True,
    )
    corr_fit.add_argument(
        "--peakfittype",
        dest="peakfittype",
        action="store",
        type=str,
        choices=["gauss", "fastgauss", "quad", "fastquad", "COM", "None"],
        help=(
            "Method for fitting the peak of the similarity function "
            '"gauss" performs a Gaussian fit, and is most accurate. '
            '"quad" and "fastquad" use a quadratic fit, '
            "which is faster, but not as well tested. "
            f'Default is "{DEFAULT_PEAKFIT_TYPE}".'
        ),
        default=DEFAULT_PEAKFIT_TYPE,
    )
    corr_fit.add_argument(
        "--despecklepasses",
        dest="despeckle_passes",
        action=pf.IndicateSpecifiedAction,
        type=int,
        metavar="PASSES",
        help=(
            "Detect and refit suspect correlations to "
            "disambiguate peak locations in PASSES "
            f"passes.  Default is to perform {DEFAULT_DESPECKLE_PASSES} passes. "
            "Set to 0 to disable."
        ),
        default=DEFAULT_DESPECKLE_PASSES,
    )
    corr_fit.add_argument(
        "--despecklethresh",
        dest="despeckle_thresh",
        action="store",
        type=float,
        metavar="VAL",
        help=(
            "Refit correlation if median discontinuity "
            "magnitude exceeds VAL. "
            f"Default is {DEFAULT_DESPECKLE_THRESH} seconds."
        ),
        default=DEFAULT_DESPECKLE_THRESH,
    )

    # Regressor refinement options
    reg_ref = parser.add_argument_group("Regressor refinement options")
    reg_ref.add_argument(
        "--refineprenorm",
        dest="refineprenorm",
        action="store",
        type=str,
        choices=["None", "mean", "var", "std", "invlag"],
        help=(
            "Apply TYPE prenormalization to each "
            "timecourse prior to refinement. "
            f'Default is "{DEFAULT_REFINE_PRENORM}".'
        ),
        default=DEFAULT_REFINE_PRENORM,
    )
    reg_ref.add_argument(
        "--refineweighting",
        dest="refineweighting",
        action="store",
        type=str,
        choices=["None", "NIRS", "R", "R2"],
        help=(
            "Apply TYPE weighting to each timecourse prior "
            f'to refinement. Default is "{DEFAULT_REFINE_WEIGHTING}".'
        ),
        default=DEFAULT_REFINE_WEIGHTING,
    )
    reg_ref.add_argument(
        "--passes",
        dest="passes",
        action="store",
        type=int,
        metavar="PASSES",
        help=("Set the number of processing passes to PASSES.  " f"Default is {DEFAULT_PASSES}."),
        default=DEFAULT_PASSES,
    )
    reg_ref.add_argument(
        "--refineinclude",
        dest="refineincludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Only use voxels in file MASK for regressor refinement "
            "(if VALSPEC is given, only voxels "
            "with integral values listed in VALSPEC are used). "
        ),
        default=None,
    )
    reg_ref.add_argument(
        "--refineexclude",
        dest="refineexcludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Do not use voxels in file MASK for regressor refinement "
            "(if VALSPEC is given, voxels "
            "with integral values listed in VALSPEC are excluded). "
        ),
        default=None,
    )
    reg_ref.add_argument(
        "--norefinedespeckled",
        dest="refinedespeckled",
        action="store_false",
        help=("Do not use despeckled pixels in calculating the refined regressor."),
        default=True,
    )
    reg_ref.add_argument(
        "--lagminthresh",
        dest="lagminthresh",
        action="store",
        metavar="MIN",
        type=float,
        help=(
            "For refinement, exclude voxels with delays "
            f"less than MIN. Default is {DEFAULT_LAGMIN_THRESH} seconds. "
        ),
        default=DEFAULT_LAGMIN_THRESH,
    )
    reg_ref.add_argument(
        "--lagmaxthresh",
        dest="lagmaxthresh",
        action="store",
        metavar="MAX",
        type=float,
        help=(
            "For refinement, exclude voxels with delays "
            f"greater than MAX. Default is {DEFAULT_LAGMAX_THRESH} seconds. "
        ),
        default=DEFAULT_LAGMAX_THRESH,
    )
    reg_ref.add_argument(
        "--ampthresh",
        dest="ampthresh",
        action="store",
        metavar="AMP",
        type=float,
        help=(
            "For refinement, exclude voxels with correlation "
            f"coefficients less than AMP (default is {DEFAULT_AMPTHRESH}).  "
            "NOTE: ampthresh will automatically be set to the p<0.05 "
            "significance level determined by the --numnull option if NREPS "
            "is set greater than 0 and this is not manually specified."
        ),
        default=-1.0,
    )
    reg_ref.add_argument(
        "--sigmathresh",
        dest="sigmathresh",
        action="store",
        metavar="SIGMA",
        type=float,
        help=(
            "For refinement, exclude voxels with widths "
            f"greater than SIGMA seconds. Default is {DEFAULT_SIGMATHRESH} seconds."
        ),
        default=DEFAULT_SIGMATHRESH,
    )
    reg_ref.add_argument(
        "--offsetinclude",
        dest="offsetincludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Only use voxels in file MASK for determining the zero time offset value "
            "(if VALSPEC is given, only voxels "
            "with integral values listed in VALSPEC are used). "
        ),
        default=None,
    )
    reg_ref.add_argument(
        "--offsetexclude",
        dest="offsetexcludespec",
        metavar="MASK[:VALSPEC]",
        help=(
            "Do not use voxels in file MASK for determining the zero time offset value "
            "(if VALSPEC is given, voxels "
            "with integral values listed in VALSPEC are excluded). "
        ),
        default=None,
    )
    reg_ref.add_argument(
        "--norefineoffset",
        dest="refineoffset",
        action="store_false",
        help=("Disable realigning refined regressor to zero lag."),
        default=True,
    )
    reg_ref.add_argument(
        "--psdfilter",
        dest="psdfilter",
        action="store_true",
        help=("Apply a PSD weighted Wiener filter to " "shifted timecourses prior to refinement."),
        default=False,
    )
    reg_ref.add_argument(
        "--pickleft",
        dest="pickleft",
        action="store_true",
        help=("Will select the leftmost delay peak when setting the refine " "offset."),
        default=False,
    )
    reg_ref.add_argument(
        "--pickleftthresh",
        dest="pickleftthresh",
        action="store",
        metavar="THRESH",
        type=float,
        help=(
            "Threshhold value (fraction of maximum) in a histogram "
            f"to be considered the start of a peak.  Default is {DEFAULT_PICKLEFT_THRESH}."
        ),
        default=DEFAULT_PICKLEFT_THRESH,
    )

    refine = reg_ref.add_mutually_exclusive_group()
    refine.add_argument(
        "--refineupperlag",
        dest="lagmaskside",
        action="store_const",
        const="upper",
        help=("Only use positive lags for regressor refinement."),
        default="both",
    )
    refine.add_argument(
        "--refinelowerlag",
        dest="lagmaskside",
        action="store_const",
        const="lower",
        help=("Only use negative lags for regressor refinement."),
        default="both",
    )
    reg_ref.add_argument(
        "--refinetype",
        dest="refinetype",
        action="store",
        type=str,
        choices=["pca", "ica", "weighted_average", "unweighted_average"],
        help=(
            "Method with which to derive refined regressor. "
            f'Default is "{DEFAULT_REFINE_TYPE}".'
        ),
        default=DEFAULT_REFINE_TYPE,
    )
    reg_ref.add_argument(
        "--pcacomponents",
        dest="pcacomponents",
        action="store",
        type=float,
        metavar="VALUE",
        help=(
            "Number of PCA components used for refinement.  If VALUE >= 1, will retain this many components.  If "
            "0.0 < VALUE < 1.0, enough components will be retained to explain the fraction VALUE of the "
            "total variance. If VALUE is negative, the number of components will be to retain will be selected "
            f"automatically using the MLE method.  Default is {DEFAULT_REFINE_PCACOMPONENTS}."
        ),
        default=DEFAULT_REFINE_PCACOMPONENTS,
    )
    reg_ref.add_argument(
        "--convergencethresh",
        dest="convergencethresh",
        action="store",
        type=float,
        metavar="THRESH",
        help=(
            "Continue refinement until the MSE between regressors becomes <= THRESH.  "
            "By default, this is not set, so refinement will run for the specified number of passes. "
        ),
        default=None,
    )
    reg_ref.add_argument(
        "--maxpasses",
        dest="maxpasses",
        action="store",
        type=int,
        metavar="MAXPASSES",
        help=(
            "Terminate refinement after MAXPASSES passes, whether or not convergence has occured. "
            f"Default is {DEFAULT_MAXPASSES}."
        ),
        default=DEFAULT_MAXPASSES,
    )

    # Output options
    output = parser.add_argument_group("Output options")
    output.add_argument(
        "--nolimitoutput",
        dest="limitoutput",
        action="store_false",
        help=("Save some of the large and rarely used files."),
        default=True,
    )
    output.add_argument(
        "--savelags",
        dest="savecorrtimes",
        action="store_true",
        help="Save a table of lagtimes used.",
        default=False,
    )
    output.add_argument(
        "--histlen",  # was -h
        dest="histlen",
        action="store",
        type=int,
        metavar="HISTLEN",
        help=(f"Change the histogram length to HISTLEN.  Default is {DEFAULT_HISTLEN}."),
        default=DEFAULT_HISTLEN,
    )
    output.add_argument(
        "--glmsourcefile",
        dest="glmsourcefile",
        action="store",
        type=lambda x: pf.is_valid_file(parser, x),
        metavar="FILE",
        help=(
            "Regress delayed regressors out of FILE instead "
            "of the initial fmri file used to estimate "
            "delays."
        ),
        default=None,
    )
    output.add_argument(
        "--noglm",
        dest="doglmfilt",
        action="store_false",
        help=(
            "Turn off GLM filtering to remove delayed "
            "regressor from each voxel (disables output of "
            "fitNorm)."
        ),
        default=True,
    )
    output.add_argument(
        "--preservefiltering",
        dest="preservefiltering",
        action="store_true",
        help="Don't reread data prior to performing GLM.",
        default=False,
    )
    output.add_argument(
        "--saveintermediatemaps",
        dest="saveintermediatemaps",
        action="store_true",
        help="Save lag times, strengths, widths, and mask for each pass.",
        default=False,
    )
    output.add_argument(
        "--legacyoutput",
        dest="bidsoutput",
        action="store_false",
        help=(
            "Use legacy file naming and formats rather than BIDS naming and "
            "format conventions for output files."
        ),
        default=True,
    )
    output.add_argument(
        "--calccoherence",
        dest="calccoherence",
        action="store_true",
        help=("Calculate and save the coherence between the final regressor and the data."),
        default=False,
    )

    # Miscellaneous options
    misc = parser.add_argument_group("Miscellaneous options")
    misc.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {tide_util.version()[0]}",
    )
    # misc.add_argument(
    #    "--detailedversion",
    #    dest="printversion",
    #    action="store",
    #    type=pf.detailedversion(),
    #    help=("Print exhaustive version information and exit."),
    #    default=None,
    # )
    misc.add_argument(
        "--noprogressbar",
        dest="showprogressbar",
        action="store_false",
        help=("Will disable showing progress bars (helpful if stdout is going " "to a file)."),
        default=True,
    )
    misc.add_argument(
        "--checkpoint",
        dest="checkpoint",
        action="store_true",
        help="Enable run checkpoints.",
        default=False,
    )
    misc.add_argument(
        "--wiener",
        dest="dodeconv",
        action="store_true",
        help=("Do Wiener deconvolution to find voxel transfer function."),
        default=False,
    )
    misc.add_argument(
        "--spcalculation",
        dest="internalprecision",
        action="store_const",
        const="single",
        help=(
            "Use single precision for internal calculations "
            "(may be useful when RAM is limited)."
        ),
        default="double",
    )
    misc.add_argument(
        "--dpoutput",
        dest="outputprecision",
        action="store_const",
        const="double",
        help=("Use double precision for output files."),
        default="single",
    )
    misc.add_argument(
        "--cifti",
        dest="isgrayordinate",
        action="store_true",
        help="Data file is a converted CIFTI.",
        default=False,
    )
    misc.add_argument(
        "--simulate",
        dest="fakerun",
        action="store_true",
        help="Simulate a run - just report command line options.",
        default=False,
    )
    misc.add_argument(
        "--displayplots",
        dest="displayplots",
        action="store_true",
        help="Display plots of interesting timecourses.",
        default=False,
    )
    misc.add_argument(
        "--nonumba",
        dest="nonumba",
        action="store_true",
        help="Disable jit compilation with numba.",
        default=False,
    )
    misc.add_argument(
        "--nosharedmem",
        dest="sharedmem",
        action="store_false",
        help=("Disable use of shared memory for large array storage."),
        default=True,
    )
    misc.add_argument(
        "--memprofile",
        dest="memprofile",
        action="store_true",
        help=("Enable memory profiling - " "warning: this slows things down a lot."),
        default=False,
    )
    misc.add_argument(
        "--mklthreads",
        dest="mklthreads",
        action="store",
        type=int,
        metavar="MKLTHREADS",
        help=("Use no more than MKLTHREADS worker threads in accelerated numpy " "calls."),
        default=1,
    )
    misc.add_argument(
        "--nprocs",
        dest="nprocs",
        action="store",
        type=int,
        metavar="NPROCS",
        help=(
            "Use NPROCS worker processes for multiprocessing. "
            "Setting NPROCS to less than 1 sets the number of "
            "worker processes to n_cpus - 1."
        ),
        default=1,
    )

    # Experimental options (not fully tested, may not work)
    experimental = parser.add_argument_group(
        "Experimental options (not fully tested, may not work)"
    )
    experimental.add_argument(
        "--echocancel",
        dest="echocancel",
        action="store_true",
        help=("Attempt to perform echo cancellation."),
        default=False,
    )
    experimental.add_argument(
        "--respdelete",
        dest="respdelete",
        action="store_true",
        help=("Attempt to detect and remove respiratory signal that strays into " "the LFO band."),
        default=False,
    )
    experimental.add_argument(
        "--negativegradient",
        dest="negativegradient",
        action="store_true",
        help=(
            "Calculate the negative gradient of the fmri data after spectral filtering "
            "so you can look for CSF flow à la https://www.biorxiv.org/content/10.1101/2021.03.29.437406v1.full. "
        ),
        default=False,
    )
    experimental.add_argument(
        "--negativegradregressor",
        dest="negativegradregressor",
        action="store_true",
        help=argparse.SUPPRESS,
        default=False,
    )
    experimental.add_argument(
        "--cleanrefined",
        dest="cleanrefined",
        action="store_true",
        help=(
            "Perform additional processing on refined "
            "regressor to remove spurious "
            "components."
        ),
        default=False,
    )
    experimental.add_argument(
        "--dispersioncalc",
        dest="dodispersioncalc",
        action="store_true",
        help=("Generate extra data during refinement to " "allow calculation of dispersion."),
        default=False,
    )
    experimental.add_argument(
        "--acfix",
        dest="fix_autocorrelation",
        action="store_true",
        help=("Perform a secondary correlation to " "disambiguate peak location. Experimental."),
        default=False,
    )
    experimental.add_argument(
        "--tmask",
        dest="tmaskname",
        action="store",
        type=lambda x: pf.is_valid_file(parser, x),
        metavar="FILE",
        help=(
            "Only correlate during epochs specified "
            "in MASKFILE (NB: each line of FILE "
            "contains the time and duration of an "
            "epoch to include."
        ),
        default=None,
    )

    # Debugging options
    debugging = parser.add_argument_group(
        "Debugging options.  You probably don't want to use any of these unless I ask you to to help diagnose a problem"
    )
    debugging.add_argument(
        "--debug",
        dest="debug",
        action="store_true",
        help=("Enable additional debugging output."),
        default=False,
    )
    debugging.add_argument(
        "--verbose",
        dest="verbose",
        action="store_true",
        help=("Enable additional runtime information output."),
        default=False,
    )
    debugging.add_argument(
        "--alwaysmultiproc",
        dest="alwaysmultiproc",
        action="store_true",
        help=("Use the multiprocessing code path even when nprocs=1."),
        default=False,
    )
    debugging.add_argument(
        "--singleproc_getNullDist",
        dest="singleproc_getNullDist",
        action="store_true",
        help=("Force single proc path for getNullDist."),
        default=False,
    )
    debugging.add_argument(
        "--singleproc_calcsimilarity",
        dest="singleproc_calcsimilarity",
        action="store_true",
        help=("Force single proc path for calcsimilarity."),
        default=False,
    )
    debugging.add_argument(
        "--singleproc_peakeval",
        dest="singleproc_peakeval",
        action="store_true",
        help=("Force single proc path for peakeval."),
        default=False,
    )
    debugging.add_argument(
        "--singleproc_fitcorr",
        dest="singleproc_fitcorr",
        action="store_true",
        help=("Force single proc path for fitcorr."),
        default=False,
    )
    debugging.add_argument(
        "--singleproc_glm",
        dest="singleproc_glm",
        action="store_true",
        help=("Force single proc path for glm."),
        default=False,
    )

    return parser

def process_args(inputargs=None):
    """
    Compile arguments for rapidtide workflow.
    """
    inargs, argstowrite = pf.setargs(_get_parser, inputargs=inputargs)
    args = vars(inargs)

    sh = logging.StreamHandler()
    if args["debug"]:
        logging.basicConfig(level=logging.DEBUG, handlers=[sh])
    else:
        logging.basicConfig(level=logging.INFO, handlers=[sh])

    # save the raw and formatted command lines
    args["commandlineargs"] = argstowrite[1:]
    thecommandline = " ".join(argstowrite)
    tide_io.writevec([thecommandline], args["outputname"] + "_commandline.txt")
    formattedcommandline = []
    for thetoken in argstowrite[0:3]:
        formattedcommandline.append(thetoken)
    for thetoken in argstowrite[3:]:
        if thetoken[0:2] == "--":
            formattedcommandline.append(thetoken)
        else:
            formattedcommandline[-1] += " " + thetoken
    for i in range(len(formattedcommandline)):
        if i > 0:
            prefix = "    "
        else:
            prefix = ""
        if i < len(formattedcommandline) - 1:
            suffix = " \\"
        else:
            suffix = ""
        formattedcommandline[i] = prefix + formattedcommandline[i] + suffix
    tide_io.writevec(formattedcommandline, args["outputname"] + "_formattedcommandline.txt")

    LGR.debug("\nbefore postprocessing:\n{}".format(args))

    # some tunable parameters for internal debugging
    args["dodemean"] = True
    # what fraction of the correlation window to avoid on either end when
    # fitting
    args["edgebufferfrac"] = 0.0
    # only do fits in voxels that exceed threshhold
    args["enforcethresh"] = True
    # if set to the location of the first autocorrelation sidelobe,
    # this will fold back sidelobes
    args["lagmod"] = 1000.0
    # zero out peaks with correlations lower than this value
    args["lthreshval"] = 0.0
    # zero out peaks with correlations higher than this value
    args["uthreshval"] = 1.0
    # width of the reference autocorrelation function
    args["absmaxsigma"] = 10000.0
    # width of the reference autocorrelation function
    args["absminsigma"] = 0.25

    # correlation fitting
    # Peak value must be within specified range.
    # If false, allow max outside if maximum
    # correlation value is that one end of the range.
    args["hardlimit"] = True
    # The fraction of the main peak over which points are included in the peak
    args["searchfrac"] = 0.5
    args["mp_chunksize"] = 50000

    # significance estimation
    args["sighistlen"] = 1000
    args["dosighistfit"] = True
    if args["corrtype"] == "linear":
        args["corrpadding"] = -1
        pf.setifnotset(args, "windowfunc", "None")
    else:
        args["corrpadding"] = 0

    # output options
    args["savedespecklemasks"] = True
    args["saveglmfiltered"] = True
    args["savemotionfiltered"] = False
    args["savecorrmask"] = True

    # refinement options
    args["filterbeforePCA"] = True
    args["dispersioncalc_step"] = 0.50

    # autocorrelation processing
    args["check_autocorrelation"] = True
    args["acwidth"] = 0.0  # width of the reference autocorrelation function

    # diagnostic information about version
    (
        args["release_version"],
        args["git_longtag"],
        args["git_date"],
        args["git_isdirty"],
    ) = tide_util.version()
    args["python_version"] = str(sys.version_info)

    # configure the filter
    theobj, theprefilter = pf.postprocessfilteropts(Namespace(**args))
    args = vars(theobj)

    # Additional argument parsing not handled by argparse
    args["despeckle_passes"] = np.max([args["despeckle_passes"], 0])

    if "lag_extrema_nondefault" in args.keys():
        args["lagmin_nondefault"] = True
        args["lagmax_nondefault"] = True

    args["lagmin"] = args["lag_extrema"][0]
    args["lagmax"] = args["lag_extrema"][1]
    args["startpoint"] = args["timerange"][0]
    if args["timerange"][1] == -1:
        args["endpoint"] = 100000000
    else:
        args["endpoint"] = args["timerange"][1]

    args["offsettime_total"] = args["offsettime"] + 0.0

    reg_ref_used = (
        (args["lagminthresh"] != 0.5)
        or (args["lagmaxthresh"] != 5.0)
        or (args["ampthresh"] != DEFAULT_AMPTHRESH)
        or (args["sigmathresh"] != 100.0)
        or (args["refineoffset"])
    )
    if reg_ref_used and args["passes"] == 1:
        LGR.warning(
            "One or more arguments have been set that are only "
            "relevant if performing refinement.  "
            "If you want to do refinement, set passes > 1."
        )

    if args["numestreps"] == 0:
        args["ampthreshfromsig"] = False
    else:
        args["ampthreshfromsig"] = True

    if args["ampthresh"] < 0.0:
        args["ampthresh"] = DEFAULT_AMPTHRESH
    else:
        args["ampthreshfromsig"] = False

    if args["despeckle_thresh"] != 5.0 and args["despeckle_passes"] == 0:
        args["despeckle_passes"] = 1

    if args["zerooutbadfit"]:
        args["nohistzero"] = False
    else:
        args["nohistzero"] = True

    if args["fixeddelayvalue"] is not None:
        args["fixdelay"] = True
        args["lag_extrema"] = (
            args["fixeddelayvalue"] - 10.0,
            args["fixeddelayvalue"] + 10.0,
        )
    else:
        args["fixdelay"] = False

    if args["in_file"].endswith("txt") and args["realtr"] == "auto":
        raise ValueError(
            "Either --datatstep or --datafreq must be provided " "if data file is a text file."
        )

    if args["realtr"] != "auto":
        fmri_tr = float(args["realtr"])
    else:
        if tide_io.checkifcifti(args["in_file"]):
            fmri_tr, dummy = tide_io.getciftitr(nib.load(args["in_file"]).header)
        else:
            fmri_tr = nib.load(args["in_file"]).header.get_zooms()[3]
    args["realtr"] = fmri_tr

    if args["inputfreq"] == "auto":
        args["inputfreq"] = 1.0 / fmri_tr

    # mask processing
    if args["corrmaskincludespec"] is not None:
        (args["corrmaskincludename"], args["corrmaskincludevals"],) = tide_io.processnamespec(
            args["corrmaskincludespec"],
            "Including voxels where ",
            "in correlation calculations.",
        )
    else:
        args["corrmaskincludename"] = None

    if args["globalmeanincludespec"] is not None:
        (args["globalmeanincludename"], args["globalmeanincludevals"],) = tide_io.processnamespec(
            args["globalmeanincludespec"], "Including voxels where ", "in global mean."
        )
    else:
        args["globalmeanincludename"] = None
        args["globalmeanincludevals"] = None

    if args["globalmeanexcludespec"] is not None:
        (args["globalmeanexcludename"], args["globalmeanexcludevals"],) = tide_io.processnamespec(
            args["globalmeanexcludespec"],
            "Excluding voxels where ",
            "from global mean.",
        )
    else:
        args["globalmeanexcludename"] = None
        args["globalmeanexcludevals"] = None

    if args["refineincludespec"] is not None:
        (args["refineincludename"], args["refineincludevals"],) = tide_io.processnamespec(
            args["refineincludespec"], "Including voxels where ", "in refinement."
        )
    else:
        args["refineincludename"] = None
        args["refineincludevals"] = None

    if args["refineexcludespec"] is not None:
        (args["refineexcludename"], args["refineexcludevals"],) = tide_io.processnamespec(
            args["refineexcludespec"], "Excluding voxels where ", "from refinement."
        )
    else:
        args["refineexcludename"] = None
        args["refineexcludevals"] = None

    if args["offsetincludespec"] is not None:
        (args["offsetincludename"], args["offsetincludevals"],) = tide_io.processnamespec(
            args["offsetincludespec"], "Including voxels where ", "in offset calculation."
        )
    else:
        args["offsetincludename"] = None
        args["offsetincludevals"] = None

    if args["offsetexcludespec"] is not None:
        (args["offsetexcludename"], args["offsetexcludevals"],) = tide_io.processnamespec(
            args["offsetexcludespec"], "Excluding voxels where ", "from offset calculation."
        )
    else:
        args["offsetexcludename"] = None
        args["offsetexcludevals"] = None

    # motion processing
    if args["motionfilespec"] is not None:
        (args["motionfilename"], args["motionfilevals"]) = tide_io.processnamespec(
            args["motionfilespec"], "Using columns in ", "as motion regressors."
        )
    else:
        args["motionfilename"] = None

    if args["venousrefine"]:
        LGR.warning('Using "venousrefine" macro. Overriding any affected arguments.')
        args["lagminthresh"] = 2.5
        args["lagmaxthresh"] = 6.0
        args["ampthresh"] = 0.5
        args["ampthreshfromsig"] = False
        args["lagmaskside"] = "upper"

    if args["nirs"]:
        LGR.warning('Using "nirs" macro. Overriding any affected arguments.')
        args["nothresh"] = True
        pf.setifnotset(args, "preservefiltering", False)
        args["refineprenorm"] = "var"
        args["ampthresh"] = 0.7
        args["ampthreshfromsig"] = False
        args["lagmaskthresh"] = 0.1
        args["despeckle_passes"] = 0

    if args["delaymapping"]:
        pf.setifnotset(args, "despeckle_passes", 4)
        pf.setifnotset(args, "lagmin", DEFAULT_DELAYMAPPING_LAGMIN)
        pf.setifnotset(args, "lagmax", DEFAULT_DELAYMAPPING_LAGMAX)
        args["passes"] = 3
        args["refineoffset"] = True
        args["pickleft"] = True
        args["limitoutput"] = True
        pf.setifnotset(args, "doglmfilt", False)

    if args["denoising"]:
        pf.setifnotset(args, "despeckle_passes", 4)
        pf.setifnotset(args, "lagmin", DEFAULT_DENOISING_LAGMIN)
        pf.setifnotset(args, "lagmax", DEFAULT_DENOISING_LAGMAX)
        pf.setifnotset(args, "peakfittype", DEFAULT_DENOISING_PEAKFITTYPE)
        args["passes"] = 3
        args["refineoffset"] = True
        args["doglmfilt"] = True

    if args["globalpreselect"]:
        args["passes"] = 1
        args["pickleft"] = True
        args["despeckle_passes"] = 0
        args["refinedespeckle"] = False
        args["limitoutput"] = True
        pf.setifnotset(args, "doglmfilt", False)
        args["saveintermediatemaps"] = False

    # process limitoutput
    if args["limitoutput"]:
        args["savemovingsignal"] = False
        args["savelagregressors"] = False
    else:
        args["savemovingsignal"] = True
        args["savelagregressors"] = True

    # dispersion calculation
    args["dispersioncalc_lower"] = args["lagmin"]
    args["dispersioncalc_upper"] = args["lagmax"]
    args["dispersioncalc_step"] = np.max(
        [
            (args["dispersioncalc_upper"] - args["dispersioncalc_lower"]) / 25,
            args["dispersioncalc_step"],
        ]
    )

    LGR.debug("\nafter postprocessing\n{}".format(args))

    # start the clock!
    tide_util.checkimports(args)

    return args, theprefilter


text:
package com.appeaser.sublimenavigationviewlibrary;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Borrowed from Support Design library
 */
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;
    private Rect mInsets;
    private Rect mTempRect;

    public ScrimInsetsFrameLayout(Context context) {
        this(context, null);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mTempRect = new Rect();
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SnvScrimInsetsFrameLayout,
                defStyleAttr,
                R.style.SnvScrimInsetsFrameLayout);
        this.mInsetForeground = a.getDrawable(R.styleable.SnvScrimInsetsFrameLayout_snvInsetForeground);
        a.recycle();
        this.setWillNotDraw(true);
        ViewCompat.setOnApplyWindowInsetsListener(this,
                new android.support.v4.view.OnApplyWindowInsetsListener() {
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        if (null == ScrimInsetsFrameLayout.this.mInsets) {
                            ScrimInsetsFrameLayout.this.mInsets = new Rect();
                        }

                        ScrimInsetsFrameLayout.this.mInsets.set(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
                        ScrimInsetsFrameLayout.this.setWillNotDraw(ScrimInsetsFrameLayout.this.mInsets.isEmpty() || ScrimInsetsFrameLayout.this.mInsetForeground == null);
                        ViewCompat.postInvalidateOnAnimation(ScrimInsetsFrameLayout.this);
                        return insets.consumeSystemWindowInsets();
                    }
                });
    }

    public void draw(@NonNull Canvas canvas) {
        super.draw(canvas);
        int width = this.getWidth();
        int height = this.getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            this.mTempRect.set(0, 0, width, this.mInsets.top);
            this.mInsetForeground.setBounds(this.mTempRect);
            this.mInsetForeground.draw(canvas);

            this.mTempRect.set(0, height - this.mInsets.bottom, width, height);
            this.mInsetForeground.setBounds(this.mTempRect);
            this.mInsetForeground.draw(canvas);

            this.mTempRect.set(0, this.mInsets.top, this.mInsets.left, height - this.mInsets.bottom);
            this.mInsetForeground.setBounds(this.mTempRect);
            this.mInsetForeground.draw(canvas);

            this.mTempRect.set(width - this.mInsets.right, this.mInsets.top, width, height - this.mInsets.bottom);
            this.mInsetForeground.setBounds(this.mTempRect);
            this.mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (this.mInsetForeground != null) {
            this.mInsetForeground.setCallback(this);
        }
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (this.mInsetForeground != null) {
            this.mInsetForeground.setCallback(null);
        }
    }
}


text:
package org.osgl.util;

import org.osgl.$;

import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: luog
 * Date: 9/11/13
 * Time: 5:05 PM
 * To change this template use File | Settings | File Templates.
 */
class FilteredTrav<T> extends IterableTrav<T> {
    private $.Predicate<? super T> filter;

    FilteredTrav(Iterable<? extends T> iterable, $.Function<? super T, Boolean> predicate) {
        super(iterable);
        E.NPE(predicate);
        filter = $.predicate(predicate);
    }

    @Override
    public Iterator<T> iterator() {
        return Iterators.filter(super.iterator(), filter);
    }

    public static <T> C.Traversable<T> of(Iterable<? extends T> iterable, $.Function<? super T, Boolean> predicate) {
        return new FilteredTrav<T>(iterable, predicate);
    }
}


text:
package serveur;

import java.util.Collection;

import reseau.AbstractClient;
import divers.Liste;

public class ListeClients extends Liste<AbstractClient> {
	private static final long serialVersionUID = 1L;

	public <E extends AbstractClient> ListeClients(Collection<E> clients) {
		for(final AbstractClient a : clients)
			add(a);
	}

}


text:
package com.smartdevicelink.proxy.rpc;

import com.smartdevicelink.proxy.RPCStruct;

import java.util.Hashtable;

/**
 * Describes the hour, minute and second values used to set the media clock.
 *
 Parameter List

 *

 *

 * 			Name
 * 			Type
 * 			Description
 * 			SmartDeviceLink Ver. Available
 *

 *

 * 			hours
 * 			Integer
 * 			The hour. Minvalue="0", maxvalue="59"
 *
Note:
Some display types only support a max value of 19. If out of range, it will be rejected.
 *
 * 			SmartDeviceLink 1.0
 *

  *

 * 			minutes
 * 			Integer
 * 			The minute. Minvalue="0", maxvalue="59".
 * 			SmartDeviceLink 1.0
 *

 *

 * 			seconds
 * 			Integer
 * 			The second. Minvalue="0", maxvalue="59".
 * 			SmartDeviceLink 1.0
 *

 *

 * @since SmartDeviceLink 1.0
 */
public class StartTime extends RPCStruct {
	public static final String KEY_MINUTES = "minutes";
	public static final String KEY_SECONDS = "seconds";
	public static final String KEY_HOURS = "hours";

	/**
	 * Constructs a newly allocated StartTime object
	 */
	public StartTime() { }
    /**
     * Constructs a newly allocated StartTime object indicated by the Hashtable parameter
     * @param hash The Hashtable to use
     */
    public StartTime(Hashtable<String, Object> hash) {
        super(hash);
    }
    /**
     * Get the hour. Minvalue="0", maxvalue="59"
 *
Note:
Some display types only support a max value of 19. If out of range, it will be rejected.
     * @return hours Minvalue="0", maxvalue="59"
     */
    public Integer getHours() {
        return getInteger( KEY_HOURS );
    }
    /**
     * Set the hour. Minvalue="0", maxvalue="59"
 *
Note:
Some display types only support a max value of 19. If out of range, it will be rejected.
     * @param hours min: 0; max: 59
     */
    public void setHours( Integer hours ) {
        setValue(KEY_HOURS, hours);
    }
    /**
     * Get the minute. Minvalue="0", maxvalue="59".
     * @return minutes Minvalue="0", maxvalue="59"
     */
    public Integer getMinutes() {
        return getInteger( KEY_MINUTES );
    }
    /**
     * Set the minute. Minvalue="0", maxvalue="59".
     * @param minutes min: 0; max: 59
     */
    public void setMinutes( Integer minutes ) {
        setValue(KEY_MINUTES, minutes);
    }
    /**
     * Get the second. Minvalue="0", maxvalue="59".
     * @return seconds. Minvalue="0", maxvalue="59".
     */
    public Integer getSeconds() {
        return getInteger( KEY_SECONDS );
    }
    /**
     * Set the second. Minvalue="0", maxvalue="59".
     * @param seconds min: 0 max: 59
     */
    public void setSeconds( Integer seconds ) {
        setValue(KEY_SECONDS, seconds);
    }
}


text:
#ifndef _EVDNS_H_
#define _EVDNS_H_

/** @file evdns.h

  A dns subsystem for Libevent.

  The <evdns.h> header is deprecated in Libevent 2.0 and later; please
  use <event2/evdns.h> instead.  Depending on what functionality you
  need, you may also want to include more of the other <event2/...>
  headers.
 */

#include <event.h>
#include <event2/dns.h>
#include <event2/dns_compat.h>
#include <event2/dns_struct.h>

#endif /* _EVDNS_H_ */


text:
package org.apache.accumulo.server.fs;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

/**
 *
 */
public class ViewFSUtils {

  public static final String VIEWFS_CLASSNAME = "org.apache.hadoop.fs.viewfs.ViewFileSystem";

  public static boolean isViewFSSupported() {
    try {
      Class.forName(VIEWFS_CLASSNAME);
      return true;
    } catch (ClassNotFoundException e) {
      return false;
    }
  }

  public static boolean isViewFS(Path source, Configuration conf) throws IOException {
    return isViewFS(source.getFileSystem(conf));
  }

  public static boolean isViewFS(FileSystem fs) {
    return fs.getClass().getName().equals(VIEWFS_CLASSNAME);
  }

  public static Path matchingFileSystem(Path source, String[] options, Configuration conf) throws IOException {

    if (!isViewFS(source, conf))
      throw new IllegalArgumentException("source " + source + " is not view fs");

    String sourceUriPath = source.toUri().getPath();

    Path match = null;
    int matchPrefixLen = 0;

    // find the option with the longest commmon path prefix
    for (String option : options) {
      Path optionPath = new Path(option);
      if (isViewFS(optionPath, conf)) {
        String optionUriPath = optionPath.toUri().getPath();

        int commonPrefixLen = 0;
        for (int i = 0; i < Math.min(sourceUriPath.length(), optionUriPath.length()); i++) {
          if (sourceUriPath.charAt(i) == optionUriPath.charAt(i)) {
            if (sourceUriPath.charAt(i) == '/')
              commonPrefixLen++;
          } else {
            break;
          }
        }

        if (commonPrefixLen > matchPrefixLen) {
          matchPrefixLen = commonPrefixLen;
          match = optionPath;
        } else if (match != null && commonPrefixLen == matchPrefixLen && optionPath.depth() < match.depth()) {
          // take path with less depth when match perfix length is the same
          match = optionPath;
        }
      }
    }

    return match;
  }

}


text:
package org.apache.beam.runners.spark.translation.streaming;

import static org.apache.beam.sdk.metrics.MetricResultsMatchers.attemptedMetricsResult;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.beam.runners.spark.ReuseSparkContextRule;
import org.apache.beam.runners.spark.SparkPipelineResult;
import org.apache.beam.runners.spark.TestSparkPipelineOptions;
import org.apache.beam.runners.spark.TestSparkRunner;
import org.apache.beam.runners.spark.UsesCheckpointRecovery;
import org.apache.beam.runners.spark.aggregators.AggregatorsAccumulator;
import org.apache.beam.runners.spark.io.MicrobatchSource;
import org.apache.beam.runners.spark.metrics.MetricsAccumulator;
import org.apache.beam.runners.spark.translation.streaming.utils.EmbeddedKafkaCluster;
import org.apache.beam.runners.spark.util.GlobalWatermarkHolder;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.io.kafka.KafkaIO;
import org.apache.beam.sdk.io.kafka.serialization.InstantDeserializer;
import org.apache.beam.sdk.io.kafka.serialization.InstantSerializer;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.MetricNameFilter;
import org.apache.beam.sdk.metrics.MetricResult;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.metrics.MetricsFilter;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.Keys;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Values;
import org.apache.beam.sdk.transforms.View;
import org.apache.beam.sdk.transforms.WithKeys;
import org.apache.beam.sdk.transforms.windowing.AfterWatermark;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.FixedWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.PDone;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Optional;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.Uninterruptibles;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;

/**
 * Tests DStream recovery from checkpoint.
 *
 * <p>Runs the pipeline reading from a Kafka backlog with a WM function that will move to infinity
 * on a EOF signal. After resuming from checkpoint, a single output (guaranteed by the WM) is
 * asserted, along with {@link Metrics} values that are expected to resume from previous count and a
 * side-input that is expected to recover as well.
 */
public class ResumeFromCheckpointStreamingTest implements Serializable {
  private static final EmbeddedKafkaCluster.EmbeddedZookeeper EMBEDDED_ZOOKEEPER =
      new EmbeddedKafkaCluster.EmbeddedZookeeper();
  private static final EmbeddedKafkaCluster EMBEDDED_KAFKA_CLUSTER =
      new EmbeddedKafkaCluster(EMBEDDED_ZOOKEEPER.getConnection(), new Properties());
  private static final String TOPIC = "kafka_beam_test_topic";

  private transient TemporaryFolder temporaryFolder;

  @Rule public final transient ReuseSparkContextRule noContextReuse = ReuseSparkContextRule.no();

  @BeforeClass
  public static void setup() throws IOException {
    EMBEDDED_ZOOKEEPER.startup();
    EMBEDDED_KAFKA_CLUSTER.startup();
  }

  @Before
  public void init() {
    temporaryFolder = new TemporaryFolder();
    try {
      temporaryFolder.create();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @SuppressWarnings("FutureReturnValueIgnored")
  private static void produce(Map<String, Instant> messages) {
    Properties producerProps = new Properties();
    producerProps.putAll(EMBEDDED_KAFKA_CLUSTER.getProps());
    producerProps.put("request.required.acks", 1);
    producerProps.put("bootstrap.servers", EMBEDDED_KAFKA_CLUSTER.getBrokerList());
    Serializer<String> stringSerializer = new StringSerializer();
    Serializer<Instant> instantSerializer = new InstantSerializer();

    try (KafkaProducer<String, Instant> kafkaProducer =
        new KafkaProducer(producerProps, stringSerializer, instantSerializer)) {
      for (Map.Entry<String, Instant> en : messages.entrySet()) {
        kafkaProducer.send(new ProducerRecord<>(TOPIC, en.getKey(), en.getValue()));
      }
    }
  }

  @Test
  @Category(UsesCheckpointRecovery.class)
  public void testWithResume() throws Exception {
    // write to Kafka
    produce(
        ImmutableMap.of(
            "k1", new Instant(100),
            "k2", new Instant(200),
            "k3", new Instant(300),
            "k4", new Instant(400)));

    MetricsFilter metricsFilter =
        MetricsFilter.builder()
            .addNameFilter(MetricNameFilter.inNamespace(ResumeFromCheckpointStreamingTest.class))
            .build();

    // first run should expect EOT matching the last injected element.
    SparkPipelineResult res = run(Optional.of(new Instant(400)), 0);

    assertThat(
        res.metrics().queryMetrics(metricsFilter).getCounters(),
        hasItem(
            attemptedMetricsResult(
                ResumeFromCheckpointStreamingTest.class.getName(),
                "allMessages",
                "EOFShallNotPassFn",
                4L)));
    assertThat(
        res.metrics().queryMetrics(metricsFilter).getCounters(),
        hasItem(
            attemptedMetricsResult(
                ResumeFromCheckpointStreamingTest.class.getName(),
                "processedMessages",
                "EOFShallNotPassFn",
                4L)));

    // --- between executions:

    // - clear state.
    clean();

    // - write a bit more.
    produce(
        ImmutableMap.of(
            "k5", new Instant(499),
            "EOF", new Instant(500) // to be dropped from [0, 500).
            ));

    // recovery should resume from last read offset, and read the second batch of input.
    res = runAgain(1);
    // assertions 2:
    assertThat(
        res.metrics().queryMetrics(metricsFilter).getCounters(),
        hasItem(
            attemptedMetricsResult(
                ResumeFromCheckpointStreamingTest.class.getName(),
                "processedMessages",
                "EOFShallNotPassFn",
                5L)));
    assertThat(
        res.metrics().queryMetrics(metricsFilter).getCounters(),
        hasItem(
            attemptedMetricsResult(
                ResumeFromCheckpointStreamingTest.class.getName(),
                "allMessages",
                "EOFShallNotPassFn",
                6L)));
    long successAssertions = 0;
    Iterable<MetricResult<Long>> counterResults =
        res.metrics()
            .queryMetrics(
                MetricsFilter.builder()
                    .addNameFilter(
                        MetricNameFilter.named(
                            PAssertWithoutFlatten.class, PAssert.SUCCESS_COUNTER))
                    .build())
            .getCounters();
    for (MetricResult<Long> counter : counterResults) {
      if (counter.getAttempted() > 0) {
        successAssertions++;
      }
    }
    assertThat(
        String.format("Expected %d successful assertions, but found %d.", 1L, successAssertions),
        successAssertions,
        is(1L));
    // validate assertion didn't fail.
    long failedAssertions = 0;
    Iterable<MetricResult<Long>> failCounterResults =
        res.metrics()
            .queryMetrics(
                MetricsFilter.builder()
                    .addNameFilter(
                        MetricNameFilter.named(
                            PAssertWithoutFlatten.class, PAssert.FAILURE_COUNTER))
                    .build())
            .getCounters();
    for (MetricResult<Long> counter : failCounterResults) {
      if (counter.getAttempted() > 0) {
        failedAssertions++;
      }
    }
    assertThat(
        String.format("Found %d failed assertions.", failedAssertions), failedAssertions, is(0L));
  }

  private SparkPipelineResult runAgain(int expectedAssertions) {
    // sleep before next run.
    Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
    return run(Optional.absent(), expectedAssertions);
  }

  private SparkPipelineResult run(Optional<Instant> stopWatermarkOption, int expectedAssertions) {
    KafkaIO.Read<String, Instant> read =
        KafkaIO.<String, Instant>read()
            .withBootstrapServers(EMBEDDED_KAFKA_CLUSTER.getBrokerList())
            .withTopics(Collections.singletonList(TOPIC))
            .withKeyDeserializer(StringDeserializer.class)
            .withValueDeserializer(InstantDeserializer.class)
            .withConsumerConfigUpdates(ImmutableMap.of("auto.offset.reset", "earliest"))
            .withTimestampFn(KV::getValue)
            .withWatermarkFn(
                kv -> {
                  // at EOF move WM to infinity.
                  String key = kv.getKey();
                  Instant instant = kv.getValue();
                  return "EOF".equals(key) ? BoundedWindow.TIMESTAMP_MAX_VALUE : instant;
                });

    TestSparkPipelineOptions options =
        PipelineOptionsFactory.create().as(TestSparkPipelineOptions.class);
    options.setSparkMaster("local[*]");
    options.setCheckpointDurationMillis(options.getBatchIntervalMillis());
    options.setExpectedAssertions(expectedAssertions);
    options.setRunner(TestSparkRunner.class);
    options.setEnableSparkMetricSinks(false);
    options.setForceStreaming(true);
    options.setCheckpointDir(temporaryFolder.getRoot().getPath());
    // timeout is per execution so it can be injected by the caller.
    if (stopWatermarkOption.isPresent()) {
      options.setStopPipelineWatermark(stopWatermarkOption.get().getMillis());
    }

    Pipeline p = Pipeline.create(options);

    PCollection<String> expectedCol =
        p.apply(Create.of(ImmutableList.of("side1", "side2")).withCoder(StringUtf8Coder.of()));
    PCollectionView<List<String>> view = expectedCol.apply(View.asList());

    PCollection<KV<String, Instant>> kafkaStream = p.apply(read.withoutMetadata());

    PCollection<Iterable<String>> grouped =
        kafkaStream
            .apply(Keys.create())
            .apply("EOFShallNotPassFn", ParDo.of(new EOFShallNotPassFn(view)).withSideInputs(view))
            .apply(
                Window.<String>into(FixedWindows.of(Duration.millis(500)))
                    .triggering(AfterWatermark.pastEndOfWindow())
                    .accumulatingFiredPanes()
                    .withAllowedLateness(Duration.ZERO))
            .apply(WithKeys.of(1))
            .apply(GroupByKey.create())
            .apply(Values.create());

    grouped.apply(new PAssertWithoutFlatten<>("k1", "k2", "k3", "k4", "k5"));

    return (SparkPipelineResult) p.run();
  }

  @After
  public void clean() {
    AggregatorsAccumulator.clear();
    MetricsAccumulator.clear();
    GlobalWatermarkHolder.clear();
    MicrobatchSource.clearCache();
  }

  @AfterClass
  public static void tearDown() {
    EMBEDDED_KAFKA_CLUSTER.shutdown();
    EMBEDDED_ZOOKEEPER.shutdown();
  }

  /** A pass-through fn that prevents EOF event from passing. */
  private static class EOFShallNotPassFn extends DoFn<String, String> {
    final PCollectionView<List<String>> view;
    private final Counter aggregator =
        Metrics.counter(ResumeFromCheckpointStreamingTest.class, "processedMessages");
    final Counter counter = Metrics.counter(ResumeFromCheckpointStreamingTest.class, "allMessages");

    private EOFShallNotPassFn(PCollectionView<List<String>> view) {
      this.view = view;
    }

    @ProcessElement
    public void process(ProcessContext c) {
      String element = c.element();
      // assert that side input is passed correctly before/after resuming from checkpoint.
      assertThat(c.sideInput(view), containsInAnyOrder("side1", "side2"));
      counter.inc();
      if (!"EOF".equals(element)) {
        aggregator.inc();
        c.output(c.element());
      }
    }
  }

  /**
   * A custom PAssert that avoids using {@link org.apache.beam.sdk.transforms.Flatten} until
   * BEAM-1444 is resolved.
   */
  private static class PAssertWithoutFlatten<T>
      extends PTransform<PCollection<Iterable<T>>, PDone> {
    private final T[] expected;

    @SafeVarargs
    private PAssertWithoutFlatten(T... expected) {
      this.expected = expected;
    }

    @Override
    public PDone expand(PCollection<Iterable<T>> input) {
      input.apply(ParDo.of(new AssertDoFn<>(expected)));
      return PDone.in(input.getPipeline());
    }

    private static class AssertDoFn<T> extends DoFn<Iterable<T>, Void> {
      private final Counter success =
          Metrics.counter(PAssertWithoutFlatten.class, PAssert.SUCCESS_COUNTER);
      private final Counter failure =
          Metrics.counter(PAssertWithoutFlatten.class, PAssert.FAILURE_COUNTER);
      private final T[] expected;

      AssertDoFn(T[] expected) {
        this.expected = expected;
      }

      @ProcessElement
      public void processElement(ProcessContext c) throws Exception {
        try {
          assertThat(c.element(), containsInAnyOrder(expected));
          success.inc();
        } catch (Throwable t) {
          failure.inc();
          throw t;
        }
      }
    }
  }
}


text:
<?php

/**
 * A Zend_Form subclass to set up a record editing form for the Omeka 2.0 admin
 * user interface
 *
 * @package Omeka\Form
 */

class Omeka_Form_Admin extends Omeka_Form
{
    protected $_editDisplayGroup;

    protected $_saveDisplayGroup;

    protected $_saveDisplayGroupActionDecorator;

    protected $_record;

    protected $_type;

    protected $_hasPublicPage = false;

    protected $_editGroupCssClass = 'seven columns alpha';

    protected $_saveGroupCssClass = 'three columns omega panel';

    public function init()
    {
        parent::init();

        if(empty($this->_type)) {
            throw new Zend_Form_Exception("A type (often the record type) must be given to use Omeka_Form_Admin");
        }
        //instead of extending Zend_Form_DisplayGroup, setting up here so css classes can be options directly
        //on instantiating the form. If those classes should never change, then this probably should go to
        //Omeka extensions of Zend_Form_DisplayGroup

        $this->_editDisplayGroup = new Zend_Form_DisplayGroup('edit-form', $this->getPluginLoader(self::DECORATOR));
        $this->_saveDisplayGroup = new Zend_Form_DisplayGroup('save', $this->getPluginLoader(self::DECORATOR));

        $this->addDisplayGroups(array($this->_editDisplayGroup, $this->_saveDisplayGroup));

        //create the decorators with CSS classes set up via options
        $editDecorator = new Zend_Form_Decorator_HtmlTag(array('tag'=>'section', 'class'=>$this->_editGroupCssClass));
        $saveDecorator = new Zend_Form_Decorator_HtmlTag(array('tag'=>'section', 'id'=>'save', 'class'=>$this->_saveGroupCssClass));

        $hookDecoratorOptions = array('type'=>$this->_type, 'hasPublicPage'=>$this->_hasPublicPage);
        $this->_saveDisplayGroupActionDecorator = new Omeka_Form_Decorator_SavePanelAction($hookDecoratorOptions);
        if($this->_record) {
            $this->_saveDisplayGroupActionDecorator->setOption('record', $this->_record);
            $hookDecoratorOptions['record'] = $this->_record;
        }
        $savePanelHookDecorator = new Omeka_Form_Decorator_SavePanelHook($hookDecoratorOptions);
        //Pro tip: order of adding decorators matters! if reversed, group elements would appear after the div!
        $this->_editDisplayGroup->setDecorators(array('FormElements', $editDecorator));
        $this->_saveDisplayGroup->setDecorators(array($this->_saveDisplayGroupActionDecorator, 'FormElements', $savePanelHookDecorator,  $saveDecorator));
    }

    /**
     * Add an element to the edit area
     *
     * @see Zend_Form::addElement
     * @param Zend_Form_Element|string $element
     * @param string|null $name
     * @param array|null $options
     */

    public function addElementToEditGroup($element, $name, $options = null)
    {
        return $this->addElementToDisplayGroup('edit', $element, $name, $options );
    }

    /**
     * Add an element to the save panel
     *
     * @see Zend_Form::addElement
     * @param Zend_Form_Element|string $element
     * @param string|null $name
     * @param array|null $options
     */

    public function addElementToSaveGroup($element, $name = null, $options = null)
    {
        return $this->addElementToDisplayGroup('save', $element, $name, $options );
    }

    /**
     * Generalizes creating and adding new elements to one of the display groups
     *
     * You can pass in either an Zend_Form_Element you have already created, or pass
     * parameters as you would to Zend_Form::addElement
     *
     * @param string $group Either 'save' or 'edit'
     * @param Zend_Form_Element $element The element to add to the display group
     * @param string $name
     * @param array $options
     * @throws Zend_Form_Exception
     * @return Omeka_Form_Admin
     */

    protected function addElementToDisplayGroup($group, $element, $name = null, $options = null)
    {

        if(is_string($element) && is_null($name)) {
            throw new Zend_Form_Exception('To add directly to a part of the admin edit page, you must give your element a name');
        }

        $this->addElement($element, $name, $options);

        $element = $this->getElement($name);

        switch($group) {
            case 'save':
                $this->_saveDisplayGroup->addElement($element);
                $element->setDecorators($this->getSaveGroupDefaultElementDecorators());
                break;

            case 'edit':
                $this->_editDisplayGroup->addElement($element);
                break;
        }
        return $this;
    }

    /**
     * Get the decorators for the save display group
     *
     * @return array The default decorators for the save display group
     */

    public function getSaveGroupDefaultElementDecorators()
    {
        return array(
                'ViewHelper',
                array('Description', array('tag' => 'p', 'class' => 'explanation')),
                'Errors',
                array(array('InputsTag' => 'HtmlTag'), array('tag' => 'div', 'class' => 'inputs')),
                array('Label', array('tag' => 'div', 'tagClass' => 'two columns alpha')),
                array(array('FieldTag' => 'HtmlTag'), array('tag' => 'div', 'class' => 'field'))
        );

    }

    /**
     * Set the class for the edit display group.
     *
     * You can alter the default css class for the edit group panel by passing in an
     * option for 'editGroupCssClass' when you create an instance of Omeka_Form_Admin.
     * This should be done very sparingly, as the default class is the best match to
     * existing admin theme look and feel
     *
     * @param string $cssClass
     */

    public function setEditGroupCssClass($cssClass)
    {
        $this->_editGroupCssClass = $cssClass;
    }

    /**
     * Set the class for the save display group.
     *
     * You can alter the default css class for the save group panel by passing in an
     * option for 'editGroupCssClass' when you create an instance of Omeka_Form_Admin.
     * This should be done very sparingly, as the default class is the best match to
     * existing admin theme look and feel
     *
     * @param string $cssClass
     */

    public function setSaveGroupCssClass($cssClass)
    {
        $this->_saveGroupCssClass = $cssClass;
    }

    /**
     * Set the record type of the object being edited (e.g., 'item')
     *
     * Pass in the recordType as part of the options array when you create an instance
     *
     * @param string $type
     */

    public function setType($type)
    {
        $this->_type = $type;
    }

    /**
     * Set the record (if one exists) for the object being edited
     *
     * Passing the record object as part of the options when you create the form
     * will automatically add 'Edit' and 'Delete' buttons to the save panel
     *
     * @param Omeka_Record_AbstractRecord $record
     */

    public function setRecord($record)
    {
        $this->_record = $record;
    }

    /**
     *
     * Set whether the save panel should display a link to the record's public page if it exists
     *
     * By default, a link to a record's public page is available if it exists. Pass false as the
     * value of hasPublicPage in the options array to suppress this behavior.
     *
     *
     * @param bool $value true
     */

    public function setHasPublicPage($value = false)
    {
        $this->_hasPublicPage = $value;
    }
}


text:
#include <stdafx.h>
#include "LeftAndRight.h"

CLeftAndRight::CLeftAndRight()
{
	m_right_up_with_left_down_done = false;
	m_left_up_with_right_down_done = false;
}

bool CLeftAndRight::LeftAndRightPressed(wxMouseEvent& event, bool &event_used)
{
	bool left_and_right_pressed = false;

	if(event.LeftUp()){
		if(m_right_up_with_left_down_done){
			m_right_up_with_left_down_done = false;
			left_and_right_pressed = true;
			event_used = true;
		}
		else if(event.RightIsDown()){
			m_left_up_with_right_down_done = true;
			event_used = true;
		}
	}
	else if(event.RightUp()){
		if(m_left_up_with_right_down_done){
			m_left_up_with_right_down_done = false;
			left_and_right_pressed = true;
			event_used = true;
		}
		else if(event.LeftIsDown()){
			m_right_up_with_left_down_done = true;
			event_used = true;
		}
	}

	return left_and_right_pressed;
}


text:
<resources>
    <!-- Application Title -->
    <string name="app_name">MA for Glass™</string>

    <!-- Activity Titles -->
    <string name="title_activity_main">Maintenance Assistant</string>
    <string name="title_activity_results">Results</string>
    <string name="title_pick_status">Select Status</string>
    <string name="title_view_more_info">View More</string>
    <string name="title_see_tasks">Tasks</string>
    <string name="title_activity_asset">Asset</string>
    <string name="title_activity_request">Request Work Order</string>
    <string name="title_activity_delay">Delay</string>

    <!-- API CREDENTIALS -->
    <string name="user_URL">URL here (with /api/ at the end)</string>
    <string name="app_key">Application Key Here</string>
    <string name="acs_key">Access Key Here</string>
    <string name="sec_key">Secret Key Here</string>
</resources>


text:
package com.dke.pursuitevasion.AI.CoorExplo;

import com.badlogic.gdx.math.Vector3;

import java.util.ArrayList;

/**
 * Created by Envy on 6/20/2017.
 */
public class Cell {
    public boolean frontier;
    public boolean ignore;
    public boolean explored;
    public double openness;
    public double cost;
    public double utility;
    public double distanceToClosestWall;
    public int x, y, visibleCounter;
    public Vector3 position;
    //HashMap visibleToPursuers = new HashMap();
    ArrayList<Integer> visibleToPursuers= new ArrayList<Integer>();

    public Cell(int X, int Y){
        x = X;
        y = Y;
        frontier = false;
        explored = false;
        ignore = false;
        openness = -1;
        cost = 0;
        utility = -1;
        visibleCounter = 0;
    }

}


text:
The example below shows you how to train a network in Torch and create logs which can be read in by
visualization tools in DeepBoof.  These visualization tools are intended to help you optimize your
network better and understand its behavior better.

# Requirements

First make sure you have Torch installed then add the luaposix package to your Torch setup.  This code
has only been tested in Linux and run through the command-line.

* [Install Torch 7](http://torch.ch/docs/getting-started.html#_)
* luarocks install luaposix

Optional For CUDA
* luarocks install cutorch
* luarocks install cunn

## Data Normalization

DeepBoof is used to normalize the raw input data and this must be done before any training can
be performed. The first command below will generate a description of the statistical properties
of the images in YUV color space.  The second command will first convert the image into
YUV color space then apply the normalization such that they have a mean of zero and standard
deviation of one.

```bash
gradle exampleRun -Pwhich=ExampleLearnNormalizationCifar10
gradle exampleRun -Pwhich=ExampleApplyNormalizeCifar10
```

Inside Deepboof/examples there will now be train_normalized_cifar10.t7 and train_normalized_cifar10.t7 files.

## Training Parameter Grid Search

Parameter search is used to determine that the best set of values to use when training.  This can be tricky
since there is no universally best value for parameters like the optimization step size.  What the code
below does is loads a range of values to search over from torch/grids and runs it on a subset of the input
data.  50 sample points is probably a good minimum number.  Select the one with the best training and use
its values "Single Run" example below.

To generate a randomized search of parameter space for best optimization parameters invoke:

```bash
th run_grid.lua -g spread_adam --search adam
```

Since the default network is very simple it should run fast even on a computer without Cuda installed.
If you have cuda installed you can invoke the line below instead and it will run even faster.

```bash
th run_grid.lua -g spread_adam --search adam --type cuda
```

Then let this run for an hour or two.  See in code comments for the details about what it's doing.

## Single Run

BLAH

## TODO LIST

* Use same data set cifar data as java examples
* Add preprocessing steps from VGG example?
*


text:
{% extends "layout.html" %}

{% block page_title %}
Search for a charge
{% endblock %}

{% block content %}

beta

Search results for

      <form action="#" method="GET">

          <fieldset>
            <legend class="visuallyhidden">Enter postcode or charge ID to find a charge</legend>

              Search again

              <input class="form-control search-field maintain-searched" id="maintain-map-search" name="maintain-map-search" type="text">
              <input class="search-button submit maintain-map-search-button" type="submit" name="maintain-map-search" value="">

          </fieldset>

      </form>

Local Land Charges in this area

There are 2 charges in this area

Charge ID
 HMLR-LLC-12871691

Registered on
 3 May 2017

          View
          Update

Charge ID
 HMLR-LLC-31261139

Registered on
 30 September 2012

          View
          Update

{% endblock %}


text:
//
//  MJCollectionViewFlowLayout.h
//  QQ群:286380794
//
//  Created by 郭明健 on 2016/3/7.
//  Copyright © 2016年 MJ Guo. All rights reserved.
//
//  https://github.com/GuoMingJian
//

//========用法============
/*
 1.#import "MJCollectionViewFlowLayout.h"
 2.实现协议 <MJCollectionViewDelegateFlowLayout>
 3.创建使用
 MJCollectionViewFlowLayout *layout = [[MJCollectionViewFlowLayout alloc] init];
 layout.minimumInteritemSpacing = 0.0f;  //水平间距
 layout.minimumLineSpacing = 0.0f;       //垂直间距
 layout.delegate = self;
 self.myCollectionView.collectionViewLayout = layout;
 */

#import <UIKit/UIKit.h>

@protocol  MJCollectionViewDelegateFlowLayout<UICollectionViewDelegateFlowLayout>

@end

@interface MJCollectionViewFlowLayout : UICollectionViewFlowLayout

@property (nonatomic,weak) id<MJCollectionViewDelegateFlowLayout> delegate;

@end


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('podcasts', '0033_podcast_ep_desc_template'),
    ]

    operations = [
        migrations.CreateModel(
            name='PodcastSlugMigration',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('migrate_from', models.SlugField()),
                ('podcast', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='podcasts.Podcast')),
            ],
        ),
    ]


text:
package com.radiojam.jamserver.servlets;

import com.radiojam.jamserver.song.SongNamePreparer;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * User: qde
 * Date: 16.05.13
 * Time: 20:52
 */

@SuppressWarnings("unused")
@CrossOrigin("${origin.url}")
@RestController
public class SongController {

    private final SongNamePreparer preparer;

    public SongController(SongNamePreparer preparer) {
        this.preparer = preparer;
    }

    @GetMapping("/song")
    public void doGet(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println(preparer.getCurrentSongJSON());
        }
    }

}