text:
package org.aludratest.testcase.data.impl.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.aludratest.config.AludraTestConfig;
import org.aludratest.dict.Data;
import org.aludratest.exception.AutomationException;
import org.aludratest.testcase.Ignored;
import org.aludratest.testcase.Offset;
import org.aludratest.testcase.data.Source;
import org.aludratest.testcase.data.TestCaseData;
import org.aludratest.testcase.data.TestDataProvider;
import org.aludratest.testcase.data.TestDataSource;
import org.aludratest.testcase.data.impl.xml.model.TestData;
import org.aludratest.testcase.data.impl.xml.model.TestDataConfiguration;
import org.aludratest.testcase.data.impl.xml.model.TestDataConfigurationSegment;
import org.aludratest.testcase.data.impl.xml.model.TestDataFieldMetadata;
import org.aludratest.testcase.data.impl.xml.model.TestDataFieldType;
import org.aludratest.testcase.data.impl.xml.model.TestDataFieldValue;
import org.aludratest.testcase.data.impl.xml.model.TestDataSegmentMetadata;
import org.apache.commons.io.IOUtils;
import org.codehaus.plexus.component.annotations.Requirement;
import org.databene.commons.BeanUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;

/** An XML based Test Data provider. XML files must have the AludraTest XML Testdata format; best use AludraTest VDE Plugin for
 * eclipse to create testdata files. The uri value of Source annotations must point to an XML file. This file is searched in these
 * two locations:
 *

 *
In a folder xlsRootPath/package/of/testclass/as/folder/MyTestClass/

 *
Relative to xlsRootPath
 *

 * xlsRootPath value is configured in aludratest.properties.
 *
 * @author falbrech */
public class XmlBasedTestDataProvider implements TestDataProvider {

    private final SimpleDateFormat ISO_DATE = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

    private final DecimalFormat JAVA_NUMBER = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance(Locale.US));

    @Requirement
    private AludraTestConfig aludraConfig;

    @Requirement(role = ScriptLibrary.class)
    private Map<String, ScriptLibrary> scriptLibraries = new HashMap<String, ScriptLibrary>();

    @Override
    public List<TestCaseData> getTestDataSets(Method method) {
        if (method.getParameterTypes().length == 0) {
            return Collections.singletonList(new TestCaseData("0", null, null));
        }

        // get @Source annotated parameters
        Annotation[][] annots = method.getParameterAnnotations();

        Offset offsetAnno = method.getAnnotation(Offset.class);
        int offset = (offsetAnno != null ? offsetAnno.value() : 0);

        boolean ignored = method.getAnnotation(Ignored.class) != null;
        String ignoredReason = null;
        if (ignored) {
            ignoredReason = method.getAnnotation(Ignored.class).value();
            if ("".equals(ignoredReason)) {
                ignoredReason = null;
            }
        }

        List<TestCaseData> result = new ArrayList<TestCaseData>();

        // cache for loaded file models
        Map<String, TestData> loadedFileModels = new HashMap<String, TestData>();

        // load param by param; transpose into test case data afterwards
        List<List<InternalSingleDataSource>> allData = new ArrayList<List<InternalSingleDataSource>>();
        for (int i = 0; i < annots.length; i++) {
            List<InternalSingleDataSource> paramData = getDataObjects(method, i, loadedFileModels);
            if (offset > 0) {
                if (offset < paramData.size()) {
                    paramData = paramData.subList(offset, paramData.size());
                }
                else {
                    paramData = Collections.emptyList();
                }
            }
            allData.add(paramData);
        }

        // transposition with the help of first loaded XML file
        Source firstSource = getRequiredSourceAnnotation(annots[0], "first parameter");
        TestData data = loadedFileModels.get(firstSource.uri());

        List<TestDataConfiguration> configs = data.getConfigurations();
        if (offset > 0) {
            int effectiveOffset = Math.min(offset, configs.size());
            configs = configs.subList(effectiveOffset, configs.size());
        }
        for (int i = 0; i < configs.size(); i++) {
            TestDataConfiguration config = configs.get(i);

            List<InternalSingleDataSource> dataForConfig = new ArrayList<InternalSingleDataSource>();
            // ensure that all data lists contain enough entries
            for (List<InternalSingleDataSource> ls : allData) {
                if (ls.size() <= i) {
                    result.add(new TestCaseData(getNextAutoId(result, false), new AutomationException("For method " + method
                            + ", not all referenced XML files contain the same amount of test configurations.")));
                    dataForConfig = null;
                    break;
                }
                else {
                    dataForConfig.add(ls.get(i));
                }
            }

            if (dataForConfig != null) {
                final List<InternalSingleDataSource> finalData = dataForConfig;
                TestDataSource source = new TestDataSource() {
                    @Override
                    public Data[] getData() {
                        Data[] dataArray = new Data[finalData.size()];
                        for (int i = 0; i < finalData.size(); i++) {
                            dataArray[i] = finalData.get(i).getObject();
                        }

                        return dataArray;
                    }
                };
                if (ignored) {
                    result.add(new TestCaseData(config.getName(), null, source, true, ignoredReason, config.getExternalTestId()));
                }
                else {
                    result.add(new TestCaseData(config.getName(), null, source, config.isIgnored(),
                            config.isIgnored() ? config.getIgnoredReason() : null, config.getExternalTestId()));
                }
            }
        }

        return result;
    }

    private List<InternalSingleDataSource> getDataObjects(Method method, int paramIndex, Map<String, TestData> loadedFileModels) {
        Annotation[][] annots = method.getParameterAnnotations();
        String paramName = method.getName() + " param #" + paramIndex;
        Source src = getRequiredSourceAnnotation(annots[paramIndex], paramName);

        // try to load the referenced file, or reuse from cache
        String uri = src.uri();
        if (uri == null || "".equals(uri)) {
            throw new AutomationException("@Source annotation does not specify required uri parameter");
        }
        if (src.segment() == null || "".equals(src.segment())) {
            throw new AutomationException("@Source annotation does not specify required segment parameter");
        }

        final TestData testData;
        if (loadedFileModels.containsKey(uri)) {
            testData = loadedFileModels.get(uri);
        }
        else {
            InputStream in = null;
            try {
                // real URI?
                in = tryFindXml(uri, method);
                testData = TestData.read(in);
                // some base validations
                if (testData.getMetadata() == null || testData.getMetadata().getSegments() == null
                        || testData.getConfigurations() == null) {
                    throw new AutomationException("Test data XML " + uri + " has an invalid format or is incomplete.");
                }
                loadedFileModels.put(uri, testData);
            }
            catch (Exception e) {
                throw new AutomationException("Could not read test data XML at " + uri, e);
            }
            finally {
                IOUtils.closeQuietly(in);
            }
        }

        List<InternalSingleDataSource> dataElements = new ArrayList<InternalSingleDataSource>();

        // get metadata for requested segment
        TestDataSegmentMetadata segmentMeta = null;
        for (TestDataSegmentMetadata segment : testData.getMetadata().getSegments()) {
            if (segment.getName().equals(src.segment())) {
                segmentMeta = segment;
                break;
            }
        }
        if (segmentMeta == null) {
            throw new AutomationException("Could not find segment " + src.segment() + " in XML file " + uri);
        }

        final TestDataSegmentMetadata finalSegmentMeta = segmentMeta;

        // for each configuration entry, find values
        for (final TestDataConfiguration config : testData.getConfigurations()) {
            if (containsSegment(config, segmentMeta.getName())) {
                dataElements.add(new InternalSingleDataSource() {
                    @Override
                    public Data getObject() {
                        return buildObject(testData, config, finalSegmentMeta.getName());
                    }
                });
            }
            else {
                dataElements.add(null);
            }
        }

        return dataElements;
    }

    private TestDataSegmentMetadata getSegmentMetadata(TestData testData, String segmentName) {
        for (TestDataSegmentMetadata segment : testData.getMetadata().getSegments()) {
            if (segmentName.equals(segment.getName())) {
                return segment;
            }
        }
        return null;
    }

    private Object getFieldValue(TestDataConfiguration configuration, String segmentName, TestDataFieldMetadata fieldMeta) {
        String fieldName = fieldMeta.getName();
        for (TestDataConfigurationSegment segment : configuration.getSegments()) {
            if (segmentName.equals(segment.getName())) {
                for (TestDataFieldValue field : segment.getFieldValues()) {
                    if (fieldName.equals(field.getName())) {
                        Object value = field.getFieldValueAsJavaType();
                        if (field.isScript() && (value instanceof String)) {
                            return new ScriptToEvaluate(value.toString(), fieldMeta.getFormatterPattern(),
                                    toLocale(fieldMeta.getFormatterLocale()));
                        }

                        // perform auto-conversion based on type
                        if (value instanceof String && !"".equals(value)) {
                            switch (fieldMeta.getType()) {
                                case BOOLEAN:
                                    value = Boolean.parseBoolean(value.toString());
                                    break;
                                case DATE:
                                    try {
                                        value = ISO_DATE.parse(value.toString());
                                    }
                                    catch (ParseException e) {
                                        // ignore; value is presented as-is
                                        return value;
                                    }
                                    break;
                                case NUMBER:
                                    try {
                                        value = JAVA_NUMBER.parseObject(value.toString());
                                    }
                                    catch (ParseException e) {
                                        // ignore; value is presented as-is
                                        return value;
                                    }
                                    break;
                                default:
                                    // nothing
                            }

                            return format(value, fieldMeta.getFormatterPattern(), toLocale(fieldMeta.getFormatterLocale()))
                                    .toString();
                        }
                        else if ("".equals(value)) {
                            return null;
                        }
                        return value;
                    }
                }
            }
        }
        return null;
    }

    private boolean containsSegment(TestDataConfiguration configuration, String segmentName) {
        for (TestDataConfigurationSegment segment : configuration.getSegments()) {
            if (segmentName.equals(segment.getName())) {
                return true;
            }
        }
        return false;
    }

    private Data buildObject(TestData testData, TestDataConfiguration configuration, String segmentName) {
        TestDataSegmentMetadata segmentMeta = getSegmentMetadata(testData, segmentName);
        if (segmentMeta == null) {
            throw new AutomationException("Segment " + segmentName + " is not defined in test data XML metadata.");
        }

        if (!containsSegment(configuration, segmentName)) {
            return null;
        }

        String dcn = segmentMeta.getDataClassName();

        try {
            @SuppressWarnings("unchecked")
            Class<? extends Data> clazz = (Class<? extends Data>) Class.forName(dcn);
            Data data = clazz.newInstance();

            // populate data
            Map<String, ScriptToEvaluate> scriptValues = new HashMap<String, ScriptToEvaluate>();
            Map<String, Object> plainValues = new HashMap<String, Object>();

            for (TestDataFieldMetadata field : segmentMeta.getFields()) {
                Object value;
                // if field is reference to another segment or segments, recurse into object creation
                if (field.getType() == TestDataFieldType.OBJECT) {
                    value = buildObject(testData, configuration, segmentMeta.getName() + "." + field.getName());
                }
                else if (field.getType() == TestDataFieldType.OBJECT_LIST) {
                    value = buildObjectList(testData, configuration, segmentMeta.getName() + "." + field.getName());
                }
                else {
                    value = getFieldValue(configuration, segmentName, field);
                }

                if (!(value instanceof ScriptToEvaluate)) {
                    // also put null in map to avoid "no such reference"
                    plainValues.put(field.getName(), value);
                }
                else {
                    scriptValues.put(field.getName(), (ScriptToEvaluate) value);
                }

                if (value != null && !(value instanceof ScriptToEvaluate)) {
                    BeanUtil.setPropertyValue(data, field.getName(), value);
                }
            }

            // now evaluate scripts. Offer already calculated fields as Context variables
            int lastErrorCount;
            int errorCount = 0;
            AutomationException lastException = null;
            do {
                lastErrorCount = errorCount;
                errorCount = 0;
                Iterator<Map.Entry<String, ScriptToEvaluate>> scriptIter = scriptValues.entrySet().iterator();
                while (scriptIter.hasNext()) {
                    Map.Entry<String, ScriptToEvaluate> entry = scriptIter.next();
                    try {
                        Object value = evaluate(entry.getValue().script, entry.getValue().formatPattern,
                                entry.getValue().formatLocale, plainValues);
                        plainValues.put(entry.getKey(), value);
                        if (value != null) {
                            BeanUtil.setPropertyValue(data, entry.getKey(), value);
                        }
                        scriptIter.remove();
                    }
                    catch (AutomationException e) {
                        lastException = e;
                        errorCount++;
                    }
                }
            }
            while (errorCount != lastErrorCount && !scriptValues.isEmpty());

            if (errorCount > 0 && lastException != null) {
                throw lastException;
            }

            return data;
        }
        catch (Exception e) {
            throw new AutomationException("Could not create data object for segment " + segmentMeta.getName(), e);
        }
    }

    private List<Data> buildObjectList(TestData testData, TestDataConfiguration configuration, String segmentName) {
        List<Data> result = new ArrayList<Data>();

        for (int i = 1; i < 1000; i++) {
            String segName = segmentName + "-" + i;
            if (!containsSegment(configuration, segName)) {
                break;
            }

            result.add(buildObject(testData, configuration, segName));
        }

        return result;
    }

    private Source getRequiredSourceAnnotation(Annotation[] annotations, String parameterName) {
        for (Annotation anno : annotations) {
            if (anno instanceof Source) {
                return (Source) anno;
            }
        }
        throw new AutomationException("Parameter does not have a @Source annotation: " + parameterName);
    }

    private InputStream tryFindXml(String uri, Method testMethod) throws IOException, AutomationException, URISyntaxException {
        if (uri.matches("[a-z]+://.*")) {
            URI realUri = new URI(uri);
            URL url = realUri.toURL();
            return url.openStream();
        }

        // first search try: full path, as used for Excels
        StringBuilder sbPath = new StringBuilder();
        sbPath.append(aludraConfig.getXlsRootPath());

        if (sbPath.toString().endsWith(File.separator)) {
            sbPath.delete(sbPath.length() - 1, sbPath.length());
        }
        sbPath.append(File.separator);
        sbPath.append(testMethod.getDeclaringClass().getName().replace(".", File.separator));
        sbPath.append(File.separator);
        sbPath.append(uri);
        File f = new File(sbPath.toString());
        if (f.isFile()) {
            return new FileInputStream(f);
        }

        // second try: directly under root path
        sbPath = new StringBuilder();
        sbPath.append(aludraConfig.getXlsRootPath());

        if (sbPath.toString().endsWith(File.separator)) {
            sbPath.delete(sbPath.length() - 1, sbPath.length());
        }
        sbPath.append(File.separator);
        sbPath.append(uri);
        f = new File(sbPath.toString());
        if (f.isFile()) {
            return new FileInputStream(f);
        }

        throw new AutomationException("Could not find test data XML file " + uri);
    }

    private String getNextAutoId(List<TestCaseData> dataSets, boolean error) {
        String prefix = error ? "error-" : "";
        int nextAutoId = dataSets.size();
        boolean found;
        do {
            found = false;
            for (TestCaseData tcd : dataSets) {
                if (tcd.getId().equals(prefix + nextAutoId)) {
                    found = true;
                    break;
                }
            }
            if (found) {
                nextAutoId++;
            }
        }
        while (found);
        return prefix + nextAutoId;
    }

    /** Evaluates the given data script, applying the given format pattern and locale, if specified.
     *
     * @param script Script to evaluate, e.g. addDaysToNow(5)
     * @param formatPattern Format pattern to apply. Can be a format accepted by SimpleDateFormat or
     *            DecimalFormat, depending on type of expression. If not specified, a type-specific default format is
     *            used. If the expression evaluates to a String, this parameter is ignored.
     * @param locale Locale to apply to the format pattern. If not specified, Locale.US is used (NOT the
     *            platform default, to ensure platform-independent operation).
     * @param contextVariables Map with objects which should be offered in the script context as variables. Can be
     *            null.
     * @return the result of the script */
    public String evaluate(String script, String formatPattern, Locale locale, Map<String, Object> contextVariables) {
        Context context = Context.enter();

        try {
            Scriptable scope = context.initStandardObjects();

            // find all script libraries and add their scripts
            for (ScriptLibrary lib : scriptLibraries.values()) {
                lib.addFunctionsToContext(context, scope);
            }

            // put context variables
            if (contextVariables != null) {
                for (Map.Entry<String, Object> entry : contextVariables.entrySet()) {
                    scope.put(entry.getKey(), scope, entry.getValue() == null ? null : Context.toObject(entry.getValue(), scope));
                }
            }

            try {
                Object result = context.evaluateString(scope, script, "<cmd>", 1, null);
                if (result instanceof Undefined) {
                    return null;
                }
                result = toJavaObject(result);

                // apply time travel
                if (result instanceof Date && aludraConfig.getScriptSecondsOffset() != 0) {
                    result = new Date(((Date) result).getTime() + aludraConfig.getScriptSecondsOffset() * 1000l);
                }

                // apply patterns, if required
                result = format(result, formatPattern, locale);

                return result.toString();
            }
            catch (RhinoException e) {
                throw new AutomationException("Cannot evaluate test data script '" + script + "'", e);
            }
        }
        finally {
            Context.exit();
        }
    }

    private Object format(Object object, String formatPattern, Locale locale) {
        if (locale == null) {
            locale = Locale.US;
        }

        if (object instanceof Date) {
            if (formatPattern == null) {
                formatPattern = "yyyy-MM-dd";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(formatPattern, locale);
            return sdf.format(object);
        }
        if (object instanceof Number) {
            if (formatPattern == null) {
                formatPattern = "#.#";
            }
            DecimalFormat df = new DecimalFormat(formatPattern, DecimalFormatSymbols.getInstance(locale));
            return df.format(object);
        }

        return object;
    }

    private Object toJavaObject(Object jsObject) {
        if (!(jsObject instanceof ScriptableObject)) {
            // already Java
            return jsObject;
        }
        // analyze object class name to determine target type
        if (jsObject.getClass().getName().endsWith("Date")) {
            return Context.jsToJava(jsObject, Date.class);
        }
        if (jsObject.getClass().getName().endsWith("Number")) {
            return Context.jsToJava(jsObject, Double.class);
        }
        return Context.toString(jsObject);
    }

    private static Locale toLocale(String s) {
        if (s == null || "".equals(s)) {
            return null;
        }

        // language only?
        if (s.matches("[a-z]{2}")) {
            return new Locale(s);
        }

        // language and country?
        if (s.matches("[a-z]{2}_[A-Z]{2}")) {
            String[] parts = s.split("_");
            return new Locale(parts[0], parts[1]);
        }

        // variant?
        if (s.matches("[a-z]{2}_[A-Z]{2}_[^_]+")) {
            String[] parts = s.split("_");
            return new Locale(parts[0], parts[1], parts[2]);
        }

        // invalid locale string
        throw new IllegalArgumentException("Invalid Locale value found in XML: " + s);
    }

    private static class ScriptToEvaluate {

        private String script;

        private String formatPattern;

        private Locale formatLocale;

        private ScriptToEvaluate(String script, String formatPattern, Locale formatLocale) {
            this.script = script;
            this.formatPattern = formatPattern;
            this.formatLocale = formatLocale;
        }

    }

    private static interface InternalSingleDataSource {

        public Data getObject();

    }

}


text:
const gulp = require('gulp');
const shell = require('gulp-shell');
const fs = require('fs-extra');
const winston = require('winston');
const readline = require('readline');
const spawn = require('child_process').spawn;
const pluralize = require('pluralize');
const config = require('./src/config');
const utilities = require('./src/utilities');

let winstonConfig = utilities.setUpWinstonLogger('logs/gulpErrors.log');

winston.loggers.add('gulpError', {
  file: winstonConfig,
});
const gulpErrors = winston.loggers.get('gulpError');

winstonConfig = utilities.setUpWinstonLogger('logs/latestTests.log');

winston.loggers.add('latestTests', {
  file: winstonConfig,
});
const latestTests = winston.loggers.get('latestTests');

gulp.task('env-dev', function () {
  return process.env.NODE_ENV = 'development';
});

gulp.task('env-test', function () {
  return process.env.NODE_ENV = 'testing';
});

gulp.task('env-staging', function () {
  return process.env.NODE_ENV = 'staging';
});

gulp.task('env-prod', function () {
  return process.env.NODE_ENV = 'production';
});

gulp.task('env-force', function () {
  return process.env.FORCE = 'YES';
});

gulp.task('build', shell.task('npm run build'));

gulp.task('server-serve', shell.task('npm run serve'));

gulp.task('server-start-no-nodemon', shell.task('npm run start-no-nodemon'));

gulp.task('server-http-test', shell.task('npm run http-test'));

gulp.task('server-http-just-aa-test', shell.task('npm run http-just-aa-test'));

gulp.task('server-http-just-access-test', shell.task('npm run http-just-access-test'));

gulp.task('unit-test', shell.task('npm run unit-test'));

gulp.task('test-autoAssociations', shell.task('npm run test-autoAssociations'));

gulp.task('test-permissions', shell.task('npm run test-permissions'));

gulp.task('test-groups', shell.task('npm run test-groups'));

gulp.task('test-failing', shell.task('npm run test-failing'));

gulp.task('generate-changelog', shell.task('github_changelog_generator'));

gulp.task('build-dup-report', shell.task('jscpd'));

gulp.task('serve', ['build', 'server-serve']);

gulp.task('travis-test', ['test-permissions', 'test-autoAssociations']);

gulp.task('server-test-all-ignore-config', ['server-http-test', 'unit-test']);

gulp.task('pre-commit-build', ['build-dup-report', 'generate-changelog']);

gulp.task('build-all', ['build', 'pre-commit-build']);

// main test task for not built code
gulp.task('test-server', ['env-force', 'env-test', 'server-start-no-nodemon'], function () {
  startOfTests('test');
});

gulp.task('repeat-test-server', ['env-force', 'env-test', 'server-start-no-nodemon'], function () {
  runHttpTestsOrEnd('test');
});

// main test task for built code
gulp.task('test-staging-server', ['env-force', 'env-staging', 'serve'], function () {
  startOfTests('staging');
});

gulp.task('repeat-test-staging-server', ['env-force', 'env-staging', 'serve'], function () {
  runHttpTestsOrEnd('staging');
});

gulp.task('reset-test-config', function () {
  fs.readFile('./test/testConfig.json', 'utf8', (testConfigErr, testConfigData) => {
    const testConfig = JSON.parse(testConfigData);
    resetTestConfig(testConfig);
  });
});

gulp.task('retire', function () {
  // Spawn Retire.js as a child process
  // You can optionally add option parameters to the second argument (array)
  const child = spawn('retire', [], { cwd: process.cwd() });

  child.stdout.setEncoding('utf8');
  child.stdout.on('data', function (data) {
    winston.info(data);
  });

  child.stderr.setEncoding('utf8');
  child.stderr.on('data', function (data) {
    gulpErrors.error(data);
  });
});

gulp.task('new-resource', function () {
  rlInput('', buildResourceFolder, false);
});

gulp.task('start', function() {
  preStart(['start']);
});

gulp.task('start-no-nodemon', function() {
  preStart(['run', 'start-no-nodemon']);
});

/** @function
 * @name preStart
 * @param {Array} npmScript
 */
const preStart = function (npmScript) {
  mainConfigTest().then(function (result) {
    if (result.length === 0) {
      const child = spawn('npm', npmScript, {cwd: process.cwd()});

      child.stdout.setEncoding('utf8');
      child.stdout.on('data', function (data) {
        console.log(data);
      });

      child.stderr.setEncoding('utf8');
      child.stderr.on('data', function (data) {
        gulpErrors.error(data);
      });
    }
  });
};

/** @function
 * @name addToIgnoreList
 * @param {Array} activeList
 * @return {Array}
 * @description Helper program for mainConfigTest. Returns list of config variables to ignore
 */
const addToIgnoreList = function (activeList) {
  const ignore = [];
  activeList.forEach(function (activeCheck) {
    const actualCheckVariable = config[activeCheck.activeVariable];
    if (activeCheck.activeType.toLowerCase() === 'string') {
      if ((activeCheck.activeEquals === true) && (activeCheck.activeValue !== actualCheckVariable)) {
        ignore.push.apply(ignore, activeCheck.configVariables);
      } else if ((activeCheck.activeEquals === false) && (activeCheck.activeValue === actualCheckVariable)) {
        ignore.push.apply(ignore, activeCheck.configVariables);
      }
    } else if (activeCheck.activeType.toLowerCase() === 'array') {
      if (activeCheck.activeEquals === true) {
        if ((actualCheckVariable.length === 0) || (actualCheckVariable.indexOf(activeCheck.activeValue) < 0)) {
          ignore.push.apply(ignore, activeCheck.configVariables);
        }
      } else if ((activeCheck.activeEquals === false) && (actualCheckVariable.indexOf(activeCheck.activeValue) >= 0)) {
        ignore.push.apply(ignore, activeCheck.configVariables);
      }
    }
  });
  return ignore;
};

/** @function
 * @name configTestMessage
 * @param {object} configVariables
 * @param {Array} ignore
 * @return {string}
 * @description Helper program for mainConfigTest. Returns error message
 */
const configTestMessage = function (configVariables, ignore) {
  let returnMessage = '';
  configVariables.forEach(function (configVariableObj) {
    if (ignore.indexOf(configVariableObj.variable) === -1) {
      const variableSplit = configVariableObj.variable.split('.');
      let actualPlaceholderText = config;
      if (variableSplit.length > 0) {
        variableSplit.forEach(function(varEle) {
          actualPlaceholderText = actualPlaceholderText[varEle];
        });
      } else {
        actualPlaceholderText = actualPlaceholderText[configVariableObj.variable];
      }
      if (configVariableObj.placeholderText === actualPlaceholderText) {
        if (returnMessage.length === 0) {
          returnMessage += '\n';
        }
        if (configVariableObj.customMessage.length > 0) {
          returnMessage += configVariableObj.customMessage;
        } else {
          returnMessage += `${configVariableObj.variable} is still using the placeholder input!`;
        }
        returnMessage += '\n';
      }
    }
  });
  if (returnMessage.length > 0) {
    winston.error(returnMessage);
  }
  return returnMessage;
};

/** @function
 * @name mainConfigTest
 * @return {Promise}
 * @description Checks to see if default values were replaced for required config variables
 */
const mainConfigTest = function () {
  return new Promise(function (resolve) {
    fs.readFile('test/mainConfigTest.json', 'utf8', function (mainConfigTestErr, mainConfigTestData) {
      if (mainConfigTestErr) {
        winston.error(`Attempt to read mainConfigTest.js. ${mainConfigTestErr}`);
      }
      const mainConfigTestObj = JSON.parse(mainConfigTestData);

      resolve(configTestMessage(mainConfigTestObj.configVariables, addToIgnoreList(mainConfigTestObj.activeList)));
    });
  });
};

/** @function
 * @name partialRight
 * @param {function} fn
 * @return {function}
 * @description see: http://benalman.com/news/2012/09/partial-application-in-javascript/
 */
const partialRight = function (fn /*, args...*/) {
  // A reference to the Array#slice method.
  const slice = Array.prototype.slice;
  // Convert arguments object to an array, removing the first argument.
  const args = slice.call(arguments, 1);
  return function() {
  // Invoke the originally-specified function, passing in all just-
  // specified arguments, followed by any originally-specified arguments.
    return fn.apply(this, slice.call(arguments, 0).concat(args));
  };
};

/** @function
 * @name buildModelResourceFile
 * @param {string} userInput
 * @param {string} cleanedResourceName
 * @param {string} fieldNameOrTypeOrEnd
 */
const buildModelResourceFile = function (userInput, cleanedResourceName, fieldNameOrTypeOrEnd) {
  const modelFile = getCleanedResourcePath(cleanedResourceName, 'model.js');
  if (fieldNameOrTypeOrEnd.search(/Field Name/g) !== -1) {
    buildFieldName(userInput, cleanedResourceName, modelFile);
  } else if (fieldNameOrTypeOrEnd.search(/Field Type/g) !== -1) {
    buildFieldType(userInput, cleanedResourceName, modelFile);
  } else if (fieldNameOrTypeOrEnd.search(/Add Another Field/g) !== -1) {
    buildAnotherFieldOrEnd(userInput, cleanedResourceName, modelFile);
  } else {
    gulpErrors.info('Unhandled question in buildModelResourceFile function');
  }
};

/** @function
 * @name buildAnotherFieldOrEnd
 * @param {string} userInput
 * @param {string} resourceName
 * @param {string} modelFile
 */
const buildAnotherFieldOrEnd = function (userInput, resourceName, modelFile) {
  const yesAnswers = ['y', 'yes', 'surewhynot'];
  const noAnswers = ['n', 'no', 'q', 'quit'];
  const userInputLowerCase = userInput.toLowerCase().trim();
  if ((userInput.trim().length === 0) || ((yesAnswers.indexOf(userInputLowerCase) < 0) && (noAnswers.indexOf(userInputLowerCase) < 0))) {
    askNextQuestionModel(resourceName, 'Valid answer is required.\nAdd Another Field? (y/n): ', 'Valid answer is required.\nAdd Another Field? (y/n): ', false);
  } else if (noAnswers.indexOf(userInputLowerCase) !== -1) {
    fs.readFile(modelFile, 'utf8', function (err, data) {
      if (err) gulpErrors.info(err);
      const newLine = data.replace(/'<NEXT_NAME>': sequelize.NEXT_TYPE,/g, '');
      fs.writeFile(modelFile, newLine, 'utf8', function (err) {
        if (err) gulpErrors.info(err);
        rlInput('', function () {}, true);
      });
    });
  } else {
    fs.readFile(modelFile, 'utf8', function (err, data) {
      if (err) gulpErrors.info(err);
      const newLine = data.replace(/'<NEXT_NAME>': sequelize.NEXT_TYPE,/g, '\n      \'<field_name>\': sequelize.FIELD_TYPE,');
      fs.writeFile(modelFile, newLine, 'utf8', function (err) {
        if (err) gulpErrors.info(err);
        askNextQuestionModel(resourceName, 'Field Name: ', 'Field Name: ', false);
      });
    });
  }
};

/** @function
 * @name buildFieldType
 * @param {string} userInput
 * @param {string} resourceName
 * @param {string} modelFile
 */
const buildFieldType = function (userInput, resourceName, modelFile) {
  const validFieldTypes = ['STRING', 'CHAR', 'TEXT', 'INTEGER', 'BIGINT', 'FLOAT', 'REAL', 'DOUBLE', 'DECIMAL', 'BOOLEAN', 'TIME', 'DATE', 'DATEONLY', 'HSTORE', 'JSON', 'JSONB', 'NOW', 'BLOB', 'RANGE', 'UUID', 'UUIDV1', 'UUIDV4', 'VIRTUAL', 'ENUM', 'ARRAY', 'GEOMETRY', 'GEOGRAPHY'];
  const validFieldTypesString = validFieldTypes.join(', ');
  const userInputUpperCase = userInput.toUpperCase().trim();
  const userInputUpperCaseNoBrackets = userInputUpperCase.replace(/ *\([^)]*\) */g, '');
  if ((userInput.trim().length === 0) || (validFieldTypes.indexOf(userInputUpperCaseNoBrackets) < 0)) {
    askNextQuestionModel(resourceName, `Valid Field Type is required. (${validFieldTypesString})\nField Type: `, 'Field Type: ', false);
  } else {
    fs.readFile(modelFile, 'utf8', function (err, data) {
      if (err) gulpErrors.info(err);
      const fieldFilled = data.replace(/FIELD_TYPE/g, userInput);
      fs.writeFile(modelFile, fieldFilled, 'utf8', function (err) {
        if (err) gulpErrors.info(err);
        askNextQuestionModel(resourceName, 'Add Another Field? (y/n): ', 'Add Another Field? (y/n): ', false);
      });
    });
  }
};

/** @function
 * @name buildFieldName
 * @param {string} userInput
 * @param {string} resourceName
 * @param {string} modelFile
 */
const buildFieldName = function (userInput, resourceName, modelFile) {
  if (userInput.trim().length === 0) {
    askNextQuestionModel(resourceName, 'Field Name is required\nField Name: ', 'Field Type: ', false);
  } else {
    fs.readFile(modelFile, 'utf8', function (err, data) {
      if (err) gulpErrors.info(err);
      const fieldFilled = data.replace(/'<field_name>'/g, userInput);
      fs.writeFile(modelFile, fieldFilled, 'utf8', function (err) {
        if (err) gulpErrors.info(err);
        askNextQuestionModel(resourceName, 'Field Type: ', 'Field Type: ', false);
      });
    });
  }
};

/** @function
 * @name rlInput
 * @param {string} prompt
 * @param {function} callback
 * @param {boolean} end
 */
const rlInput = function (prompt, callback, end = false) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  if ((prompt === '') && (end === false)) {
    setTimeout(process.stdout.write.bind(process.stdout), 500, 'Resource Name: ');
  }
  if (end === true) {
    process.exit();
  } else {
    rl.question(prompt, function (x) {
      callback(x);
      rl.close();
    });
  }
};

/** @function
 * @name askNextQuestionModel
 * @param {string} resourceName
 * @param {string} fieldNameOrTypeOrEnd
 * @param {string} fieldNameOrTypeOrEndNext
 * @param {boolean} end
 */
const askNextQuestionModel = function (resourceName, fieldNameOrTypeOrEnd, fieldNameOrTypeOrEndNext, end) {
  const buildModelResourceFilePartial = partialRight(buildModelResourceFile, resourceName, fieldNameOrTypeOrEndNext);
  rlInput(fieldNameOrTypeOrEnd, buildModelResourceFilePartial, end);
};

/** @function
 * @name getCleanedResourceName
 * @param {string} resourceName
 * @return {string}
 */
const getCleanedResourceName = function (resourceName) {
  const resourceNameCleaned = resourceName.trim();
  return resourceNameCleaned.charAt(0).toUpperCase() + resourceNameCleaned.slice(1);
};

/** @function
 * @name getCleanedResourcePath
 * @param {string} cleanedResourceName
 * @param {string} fileName
 * @return {string}
 */
const getCleanedResourcePath = function (cleanedResourceName, fileName) {
  return `src/resources/${cleanedResourceName}/${fileName}`;
};

/** @function
 * @name buildResourceFile
 * @param {string} resourceName
 * @param {string} fileName
 */
const buildResourceFile = function (resourceName, fileName) {
  return new Promise((resolve, reject) => {
    const copiedPath = getCleanedResourcePath(resourceName, fileName);
    fs.copy(`src/resourcesBuilder/template/${fileName}`, copiedPath, err => {
      if (err) gulpErrors.info(err);
      if (fileName === 'index.js') {
        fs.readFile(copiedPath, 'utf8', function (err, data) {
          if (err) gulpErrors.info(err);
          const pluralResource = pluralize.plural(resourceName).toLowerCase();
          let fieldFilled = data.replace(/<your_resource_plural>/g, pluralResource);
          fieldFilled = fieldFilled.replace(/<your_resource>/g, resourceName);
          fs.writeFile(copiedPath, fieldFilled, 'utf8', function (err) {
            if (err) gulpErrors.error(err);
            resolve(resourceName);
          });
        });
      } else {
        resolve(resourceName);
      }
    });
  });
};

/** @function
 * @name buildResourceFolder
 * @param {string} resourceName
 */
const buildResourceFolder = function (resourceName) {
  if (resourceName.trim().length === 0) {
    rlInput('Resource Name is Required\nResource Name: ', buildResourceFolder, false);
  } else {
    let resourceNameCleaned = getCleanedResourceName(resourceName);
    if (pluralize.plural(resourceNameCleaned) === resourceNameCleaned) {
      resourceNameCleaned = pluralize.singular(resourceNameCleaned);
    }
    const dir = `src/resources/${resourceNameCleaned}`;
    fs.ensureDir(dir, err => {
      if (err) gulpErrors.error(err);
      return buildNonModelResourceFiles(resourceNameCleaned);
    });
  }
};

/** @function
 * @name buildNonModelResourceFiles
 * @param {string} resourceName
 */
const buildNonModelResourceFiles = function (resourceName) {
  return new Promise((resolve, reject) => {
    fs.readdir('src/resourcesBuilder/template', function (err, files) {
      if (err) gulpErrors.error(err);
      Promise.all(files.map(function (file) {
        if (file.slice(-3) === '.js') {
          return buildResourceFile(resourceName, file);
        }
      })).then(function (promiseAllData) {
        fs.readFile('src/resources/index.js', 'utf8', function (err, data) {
          if (err) gulpErrors.error(err);
          const resourcesIndex = data.toString().split('\n');
          resourcesIndex.unshift(`import ${promiseAllData[0]} from './${promiseAllData[0]}';`);
          resourcesIndex.forEach(function (line, index) {
            if (line.includes('export default') === true) {
              resourcesIndex[index] = `${line.slice(0, line.length - 2)}, ${promiseAllData[0]}${line.slice(line.length - 2)}`;
              const resourcesIndexConcat = resourcesIndex.join('\n');
              fs.writeFile('src/resources/index.js', resourcesIndexConcat, 'utf8', function (err) {
                if (err) gulpErrors.error(err);
                resolve(data[0]);
                askNextQuestionModel(promiseAllData[0], 'Field Name: ', 'Field Name: ', false);
              });
            }
          });
        });
      }, function (error) {
        gulpErrors.info(error);
      });
    });
  });
};

/** @function
 * @name resetTestConfig
 * @param {object} testConfig - testConfig.json
 * @description Resets testConfig.json to its starting state
 */
const resetTestConfig = function (testConfig) {
  testConfig.testNumber = 0;
  testConfig.individualHttpTest = false;
  testConfig.testsCasesHaveBeenGenerated = false;
  if (testConfig.generationConfig && testConfig.generationConfig.removePreviousGeneratedTestCases === true) {
    testConfig.testCases = testConfig.testCases.filter(function(testCase) {
      if (testCase.generatedByTestsCasesJs !== true) {
        return testCase;
      }
    });
  } else {
    gulpErrors.error('testConfig.generationConfig is falsy or removePreviousGeneratedTestCases is not true');
  }
  fs.writeFile('./test/testConfig.json', JSON.stringify(testConfig, null, 2), function (err) {
    if (err) return gulpErrors.error(err);
  });
};

/** @function
 * @name startOfTests
 * @param {string} env - test or staging
 * @description Clears and moves test results. Starts tests.
 */
const startOfTests = function (env) {
  const envCleaned = env.toLocaleLowerCase().trim();
  fs.truncate('./logs/previousTestResults.log', 0, function () {
    fs.rename('./logs/testResults.log', './logs/previousTestResults.log', function (err) {
      if (err) return gulpErrors.error(err);
      fs.truncate('./logs/testResults.log', 0, function () {
        runHttpTestsOrEnd(envCleaned);
      });
    });
  });
};

/** @function
 * @name endOfTests
 * @description Sets the test status for the currently tests and set the environment to development
 */
const endOfTests = function () {
  fs.readFile('./logs/testResults.log', 'utf8', (testResultsErr, testResultsData) => {
    if (testResultsErr) return gulpErrors.error(testResultsErr);
    let testResultOverview = '';
    if (testResultsData.toString('utf8').search(/AssertionError/g) !== -1) {
      testResultOverview = `Not all tests passed on ${new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')} (UTC)`;
    } else {
      testResultOverview = `Passed all tests on ${new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')} (UTC)`;
    }
    latestTests.info(testResultOverview);
    process.env.NODE_ENV = 'development';
  });
};

/** @function
 * @name runHttpTests
 * @param {string} env
 * @description Runs http tests until all the test cases in testConfig.json have been run
 */
const runHttpTests = function (env) {
  fs.readFile('./test/testConfig.json', 'utf8', (testConfigErr, testConfigData) => {
    const testConfig = JSON.parse(testConfigData);
    const numOfTestCasesHttp = testConfig.testCases.length;
    if (numOfTestCasesHttp > testConfig.testNumber) {
      testConfig.testNumber = testConfig.testNumber + 1;
      testConfig.individualHttpTest = true;
      fs.writeFile('./test/testConfig.json', JSON.stringify(testConfig, null, 2), function (err) {
        if (err) return gulpErrors.error(err);
        if (env === 'test') {
          gulp.start('repeat-test-server');
        } else if (env === 'staging') {
          gulp.start('repeat-test-staging-server');
        } else {
          gulpErrors.error('environment is not test or staging!');
        }
      });
    } else {
      resetTestConfig(testConfig);
      endOfTests();
    }
  });
};

/** @function
 * @name runHttpTestsOrEnd
 * @param {string} environment
 * @description Runs http tests if they have been enabled in testConfig.json
 */
const runHttpTestsOrEnd = function (environment) {
  fs.readFile('./test/testConfig.json', 'utf8', (testConfigErr, testConfigData) => {
    const testConfig = JSON.parse(testConfigData);
    if (testConfig.doHttpTests === true) {
      runHttpTests(environment);
    } else {
      endOfTests();
    }
  });
};

redpajama_set_name: RedPajamaGithub


text:
/**
*
* Mtrend2
*
*/

import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import Responsive from 'react-responsive';

class Mtrend2 extends React.PureComponent {

  handleNav = (location) => {
    this.context.router.push(location);
  }
  render() {
    const mAfTrendCont={
      width:"100%",
      height:"600px",
      display:"flex",
      justifyContent:"center",
      background:"rgba(3,255,3,.05)",

    }
    const mAfTrendContMax={
      width:"100%",
      height:"100%",
      background:"rgba(3,255,3,0)",
      display:"flex",
      flexDirection:"column",

    }
    const mAfTrendContTitle={
      height:"30%",
      width:"100%",
      background:"rgba(3,255,3,.2)!important",
      textAlign:"center",
      fontSize:"5em",
      fontWeight:"bold",
      fontVariant:"small-caps",
      fontFamily:"Lobster",
      color:"rgba(220,255,220,1)",
      textShadow:"1px 1px 5px green",
      borderTop:"solid green 1px",

    }
    const  mAfTrendContContentTitle={
      height:"10%",
      width:"100%",
      display:"flex",
      flexDirection:"row",
      textAlign:"center",
      fontSize:"2em",
      fontWeight:"bold",
      fontVariant:"small-caps",
      fontFamily:"Lato",
      color:"rgba(220,255,220,1)",
      textShadow:"1px 1px 5px green",
      borderBottom:"solid green 1px",

    }
    const  mAfTrendContContentTitleB={
      height:"100%",
      width:"50%",
      background:"rgba(3,255,3,.3)",
      color:"rgba(220,255,220,1)",
      textShadow:"1px 1px 5px green",
    }
    const  mAfTrendContContent={
      height:"70%",
      width:"100%",
      background:"rgba(3,255,3,.05)",
      display:"flex",
      flexDirection:"row",
      justifyContent:"space-around",
    }
    const img={
      width:"100%",
      height:"auto",
      backgroundImage:"url:http://www.pitara.com/wordpress/wp-content/uploads/2001/10/clef-vine.jpg",
      padding:"auto",
      position:"relative",
      bottom:"800px"
    }

    const img2={
      width:"100%",
      height:"auto",
      backgroundImage:"url:http://www.pitara.com/wordpress/wp-content/uploads/2001/10/clef-vine.jpg",
      padding:"auto",
      position:"relative",
      bottom:"500px"
    }

    const imgBlock2={
      height:"auto",
      width:"100%",
      background:"rgba(3,255,3,0)",
      zIndex:"90000",
      overflow:"hidden",

    }

    const imgText={

      width:"100%",
      height:"30%",
      backgroundColor:"rgba(0,0,0,0)",
      textAlign:"left",
      fontSize:"5em",
      fontWeight:"none",
      fontVariant:"small-caps",
      fontFamily:"Lobster",
      color:"rgba(210,255,210,1)",
      textShadow:"1px 1px 5px black",
      padding:"7%",
      textAlign:"center",
      position:"relative",
      zIndex:"99998"

    }

    return (

      <Responsive minDeviceWidth={1400}>

          <FlatButton style={mAfTrendContTitle} backgroundColor="rgba(3,255,3,.2)" hoverColor="rgba(3,255,3,.05)" rippleColor="rgba(0,225,0,.7)" onTouchTap={()=> this.handleNav("/donate")}>We Need You</FlatButton>

            <FlatButton style={mAfTrendContContentTitleB} backgroundColor="rgba(3,255,3,.4)" hoverColor="rgba(150,225,150,.2)" rippleColor="rgba(0,225,0,.7)" onTouchTap={()=> this.handleNav("/donate")}>Donate</FlatButton>
            <FlatButton style={mAfTrendContContentTitleB} backgroundColor="rgba(3,255,3,.4)" hoverColor="rgba(150,225,150,.2)" rippleColor="rgba(0,225,0,.7)" onTouchTap={()=> this.handleNav("/signup")}>Lend A Hand</FlatButton>

Donate

      </Responsive>

      <Responsive maxDeviceWidth={1399}>

            <FlatButton style={mAfTrendContTitle} backgroundColor="rgba(3,255,3,.2)" hoverColor="rgba(3,255,3,.05)" rippleColor="rgba(0,225,0,.7)" onTouchTap={()=> this.handleNav("/donate")}>We Need You</FlatButton>

              <FlatButton style={mAfTrendContContentTitleB} backgroundColor="rgba(3,255,3,.4)" hoverColor="rgba(150,225,150,.2)" rippleColor="rgba(0,225,0,.7)" onTouchTap={()=> this.handleNav("/donate")}>Donate</FlatButton>
              <FlatButton style={mAfTrendContContentTitleB} backgroundColor="rgba(3,255,3,.4)" hoverColor="rgba(150,225,150,.2)" rippleColor="rgba(0,225,0,.7)" onTouchTap={()=> this.handleNav("/signup")}>Lend A Hand</FlatButton>

Donate

      </Responsive>

    );
  }
}
Mtrend2.contextTypes = {
  router: React.PropTypes.object
}

export default Mtrend2;


text:
from behave import *
import json
from app import server

@when(u'I visit the "home page"')
def step_impl(context):
    context.resp = context.app.get('/')

@then(u'I should see "{message}"')
def step_impl(context, message):
    assert message in context.resp.data

@then(u'I should not see "{message}"')
def step_impl(context, message):
    assert message not in context.resp.data

@given(u'the following orders')
def step_impl(context):
    server.data_reset()
    for row in context.table:
        server.data_load({"customer_name": row['customer_name'], "amount_paid": row['amount_paid']})

@when(u'I visit "{url}"')
def step_impl(context, url):
    context.resp = context.app.get(url)
    assert context.resp.status_code == 200

@when(u'I attempt to query for "{url}" and search by customer name "{customer_name}"')
def step_impl(context, url, customer_name):
    context.resp = context.app.get(url + '?customer_name=' + customer_name)
    assert context.resp.status_code == 200

@when(u'I delete "{url}" with id "{id}"')
def step_impl(context, url, id):
    target_url = url + '/' + id
    context.resp = context.app.delete(target_url)
    assert context.resp.status_code == 204
    assert context.resp.data is ""

@when(u'I retrieve "{url}" with id "{id}"')
def step_impl(context, url, id):
    target_url = url + '/' + id
    context.resp = context.app.get(target_url)
    assert context.resp.status_code == 200

@when(u'I change "{key}" to "{value}"')
def step_impl(context, key, value):
    data = json.loads(context.resp.data)
    data[key] = value
    context.resp.data = json.dumps(data)

@when(u'I update "{url}" with id "{id}"')
def step_impl(context, url, id):
    target_url = url + '/' + id
    context.resp = context.app.put(target_url, data=context.resp.data, content_type='application/json')
    assert context.resp.status_code == 200

@when(u'I use "{url}" the id "{id}" of that order so the customer can re-order their previous order')
def step_impl(context, url, id):
    target_url = url + '/' + id + '/duplicate'
    context.resp = context.app.put(target_url, data=context.resp.data, content_type='application/json')
    assert context.resp.status_code == 201

@then(u'I should see an order on "{url}" with the same amount_paid and customer name as the original order')
def step_impl(context, url):
    context.resp = context.app.get(url, data=context.resp.data, content_type='application/json')
    data = json.loads(context.resp.data)
    found = False

    for entry in data:
        for compare_entry in data:
            if entry['id'] == compare_entry['id']:
                continue
            if entry['customer_name'] == compare_entry['customer_name'] and entry['amount_paid'] == compare_entry['amount_paid']:
                found = True

    assert found == True

# @then(u'I should see a list of orders')
# def step_impl(context):
#     assert context.resp.status_code == 200
#     assert len(context.resp.data) > 0


text:
import DS from 'ember-data';

export default DS.Model.extend({
    // relationships
    user: DS.belongsTo('user'),

    // TODO: add images
    // attributes
    to: DS.attr('string'),
    from: DS.attr('string'),
    title: DS.attr('string'),
    description: DS.attr('string'),
    body: DS.attr('string')
  });


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhabdospora domingensis Gonz. Frag. & Cif.

### Remarks
null


text:
<!DOCTYPE html>

<title>Time_TZDate_setUTCMilliseconds_boundaryUpperLimit</title>


text:
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/integration/corrections.h>

using namespace boost::python;

namespace dials { namespace algorithms { namespace boost_python {

  void export_corrections() {
    def("lp_correction",
        &lp_correction,
        (arg("s0"), arg("pn"), arg("pf"), arg("m2"), arg("s1")));

    def("lp_correction",
        &stills_lp_correction,
        (arg("s0"), arg("pn"), arg("pf"), arg("s1")));

    def("qe_correction", &qe_correction, (arg("mu"), arg("t0"), arg("s1"), arg("n")));

    class_<Corrections>("Corrections", no_init)
      .def(init<const BeamBase&, const Goniometer&, const Detector&>())
      .def(init<const BeamBase&, const Detector&>())
      .def("lp", &Corrections::lp, (arg("s1")))
      .def("qe", &Corrections::qe, (arg("s1"), arg("panel")));

    class_<CorrectionsMulti>("CorrectionsMulti")
      .def("append", &CorrectionsMulti::push_back)
      .def("__len__", &CorrectionsMulti::size)
      .def("lp", &CorrectionsMulti::lp)
      .def("qe", &CorrectionsMulti::qe);
  }

}}}  // namespace dials::algorithms::boost_python


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Specification.cs" company="Catel development team">
//   Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Catel.Data.Specifications
{
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using Expressions;

    /// <summary>
    /// Generic specification class that serves as base for customized specifications.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    public class Specification<TEntity> : ISpecification<TEntity>
    {
        #region Fields
        private readonly Lazy<Func<TEntity, bool>> _compiledPredicate;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="Specification{TEntity}" /> class.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="predicate"/> is <c>null</c>.</exception>
        public Specification(Expression<Func<TEntity, bool>> predicate)
        {
            Argument.IsNotNull("predicate", predicate);

            Predicate = predicate;
            _compiledPredicate = new Lazy<Func<TEntity, bool>>(() => Predicate.Compile());
        }
        #endregion

        #region Operators
        /// <summary>
        /// Performs an implicit conversion from <see cref="Specification{TEntity}" /> to <see cref="Func{TEntity, Boolean}" />.
        /// </summary>
        /// <param name="specification">The specification.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator Func<TEntity, bool>(Specification<TEntity> specification)
        {
            return specification._compiledPredicate.Value;
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets the predicate used for this specification.
        /// </summary>
        /// <value>The predicate.</value>
        public Expression<Func<TEntity, bool>> Predicate { get; private set; }
        #endregion

        #region ISpecification<TEntity> Members
        /// <summary>
        /// Returns a single entity that match the current specification.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>Entity that matches the specification.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="query"/> is <c>null</c>.</exception>
        public TEntity SatisfyingEntityFrom(IQueryable<TEntity> query)
        {
            Argument.IsNotNull("query", query);

            return query.Where(Predicate).SingleOrDefault();
        }

        /// <summary>
        /// Returns a queryable of entities that match the current specification.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>IQueryable of entities that match the specification.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="query"/> is <c>null</c>.</exception>
        public IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query)
        {
            Argument.IsNotNull("query", query);

            return query.Where(Predicate);
        }
        #endregion

        #region Methods
        /// <summary>
        /// Creates a new specification based on the current one combined with the specified specification.
        /// </summary>
        /// <param name="specification">The specification.</param>
        /// <returns>New specification with the current specification combined with the specified specification.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="specification"/> is <c>null</c>.</exception>
        public Specification<TEntity> And(Specification<TEntity> specification)
        {
            Argument.IsNotNull("specification", specification);

            return new Specification<TEntity>(Predicate.And(specification.Predicate));
        }

        /// <summary>
        /// Creates a new specification based on the current one combined with the specified predicate.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        /// <returns>New specification with the current specification combined with the specified predicate.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="predicate"/> is <c>null</c>.</exception>
        public Specification<TEntity> And(Expression<Func<TEntity, bool>> predicate)
        {
            Argument.IsNotNull("predicate", predicate);

            return new Specification<TEntity>(Predicate.And(predicate));
        }

        /// <summary>
        /// Creates a new specification based on the current one combined with the specified specification.
        /// </summary>
        /// <param name="specification">The specification.</param>
        /// <returns>New specification with the current specification combined with the specified specification.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="specification"/> is <c>null</c>.</exception>
        public Specification<TEntity> Or(Specification<TEntity> specification)
        {
            Argument.IsNotNull("specification", specification);

            return new Specification<TEntity>(Predicate.Or(specification.Predicate));
        }

        /// <summary>
        /// Creates a new specification based on the current one combined with the specified predicate.
        /// </summary>
        /// <param name="predicate">The predicate.</param>
        /// <returns>New specification with the current specification combined with the specified predicate.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="predicate"/> is <c>null</c>.</exception>
        public Specification<TEntity> Or(Expression<Func<TEntity, bool>> predicate)
        {
            Argument.IsNotNull("predicate", predicate);

            return new Specification<TEntity>(Predicate.Or(predicate));
        }
        #endregion
    }
}


text:
<?xml version="1.0"?>

<cache-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://xmlns.oracle.com/coherence/coherence-cache-config"
              xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-cache-config coherence-cache-config.xsd">

    <defaults>
        <serializer>
            <instance>
                <class-name>com.tangosol.io.pof.ConfigurablePofContext</class-name>
                <init-params>
                    <init-param>
                        <param-type>String</param-type>
                        <param-value>coherence/pof-server-config.xml</param-value>
                    </init-param>
                </init-params>
            </instance>
        </serializer>
    </defaults>

    <caching-scheme-mapping>
        <cache-mapping>
              <cache-name>dist-*</cache-name>
              <scheme-name>xdm-distributed-scheme</scheme-name>
              <!--init-params>
                  <init-param>
                      <param-name>cachestore-bean-id</param-name>
                      <param-value>exRulesHistoryCacheStore</param-value>
                  </init-param>
                  <init-param>
                      <param-name>cachestore-timeout</param-name>
                      <param-value>300s</param-value>
                  </init-param>
                  <init-param>
                      <param-name>read-only</param-name>
                      <param-value>true</param-value>
                  </init-param>
                  <init-param>
                      <param-name>back-size-limit</param-name>
                      <param-value>100m</param-value>
                  </init-param>
                  <init-param>
                      <param-name>back-expiry</param-name>
                      <param-value>10m</param-value>
                  </init-param>
              </init-params-->
        </cache-mapping>

        <cache-mapping>
              <cache-name>repl-*</cache-name>
              <scheme-name>xdm-replicated-scheme</scheme-name>
        </cache-mapping>

        <cache-mapping>
              <cache-name>dict-*</cache-name>
              <scheme-name>xdm-replicated-scheme</scheme-name>
        </cache-mapping>

        <cache-mapping>
              <cache-name>xdm-*</cache-name>
              <scheme-name>xdm-transient-scheme</scheme-name>
        </cache-mapping>

        <cache-mapping>
            <cache-name>coherence.common.sequencegenerators</cache-name>
            <scheme-name>distributed-scheme-for-sequence-generators</scheme-name>
        </cache-mapping>

    </caching-scheme-mapping>

    <caching-schemes>

        <local-scheme>
            <scheme-name>xdm-local-scheme</scheme-name>
            <eviction-policy>HYBRID</eviction-policy>
            <high-units>{back-size-limit 0}</high-units>
            <unit-calculator>BINARY</unit-calculator>
            <expiry-delay>{back-expiry 0}</expiry-delay>
            <!--flush-delay>1m</flush-delay -->
            <cachestore-scheme></cachestore-scheme>
        </local-scheme>

        <read-write-backing-map-scheme>
            <scheme-name>xdm-read-write-scheme</scheme-name>
            <internal-cache-scheme>
            	<local-scheme>
                	<scheme-ref>xdm-local-scheme</scheme-ref>
                </local-scheme>
            </internal-cache-scheme>
            <cachestore-scheme>
            	<class-scheme>
                	<class-name>spring-bean:{cachestore-bean-id}</class-name>
                </class-scheme>
            </cachestore-scheme>
            <read-only>{read-only false}</read-only>
            <write-delay>5s</write-delay>
            <write-batch-factor>0.5</write-batch-factor>
            <write-requeue-threshold>100</write-requeue-threshold>
            <cachestore-timeout>{cachestore-timeout 120s}</cachestore-timeout>
        </read-write-backing-map-scheme>

        <!-- Base Replicated Cache scheme -->
        <replicated-scheme>
            <scheme-name>xdm-replicated-scheme</scheme-name>
            <service-name>ReplicatedXDMDataCache</service-name>
            <lease-granularity>member</lease-granularity>
	    	<member-listener>
			<class-factory-name>com.bagri.xdm.process.coherence.factory.SpringAwareCacheFactory</class-factory-name>
			<method-name>instantiateSpringBean</method-name>
			<init-params>
			    	<init-param>
					<param-type>java.lang.String</param-type>
					<param-value>replPopulationListener</param-value>
    			    	</init-param>
			</init-params>
    	    </member-listener>
            <backing-map-scheme>
                <local-scheme>
                    <eviction-policy>HYBRID</eviction-policy>
                    <high-units>{back-size-limit 0}</high-units>
                </local-scheme>
            </backing-map-scheme>
            <autostart>true</autostart>
        </replicated-scheme>

        <!-- Scheme for any distributed cache with no population. -->
        <distributed-scheme>
            <scheme-name>xdm-base-distributed-scheme</scheme-name>
            <!--service-name>DistributedXDMDataCache</service-name-->
            <thread-count system-property="xdm.cache.threads.distributedScheme">200</thread-count>
            <backup-count>1</backup-count>
            <request-timeout>1500s</request-timeout>
            <guardian-timeout>1200s</guardian-timeout>

            <backing-map-scheme>
                <read-write-backing-map-scheme>
            		<scheme-ref>xdm-read-write-scheme</scheme-ref>
                </read-write-backing-map-scheme>
            </backing-map-scheme>
            <!--autostart>true</autostart-->
        </distributed-scheme>

        <!-- Scheme for any pre-populated distributed cache. -->
        <distributed-scheme>
            <scheme-name>xdm-distributed-scheme</scheme-name>
            <scheme-ref>xdm-base-distributed-scheme</scheme-ref>
            <service-name>DistributedXDMDataCache</service-name>
            <member-listener>
                <class-factory-name>com.bagri.xdm.process.coherence.factory.SpringAwareCacheFactory</class-factory-name>
                <method-name>instantiateSpringBean</method-name>
                <init-params>
                    <init-param>
                        <param-type>java.lang.String</param-type>
                        <param-value>distPopulationListener</param-value>
                    </init-param>
                </init-params>
            </member-listener>
            <autostart>true</autostart>
        </distributed-scheme>

        <distributed-scheme>
            <scheme-name>xdm-transient-scheme</scheme-name>
            <scheme-ref>xdm-distributed-scheme</scheme-ref>
            <backing-map-scheme>
            	<local-scheme>
               	    <scheme-ref>xdm-local-scheme</scheme-ref>
                </local-scheme>
            </backing-map-scheme>
            <autostart>true</autostart>
        </distributed-scheme>

        <distributed-scheme>
            <scheme-name>distributed-scheme-for-sequence-generators</scheme-name>
            <service-name>DistributedCacheForSequenceGenerators</service-name>
		<!--member-listener>
			<class-factory-name>com.db.cpg.ccs.cache.factory.SpringAwareCacheFactory</class-factory-name>
			<method-name>instantiateSpringBean</method-name>
			<init-params>
				<init-param>
					<param-type>java.lang.String</param-type>
					<param-value>sqPopulationListener</param-value>
				</init-param>
			</init-params>
		</member-listener-->
            <backing-map-scheme>
            	<local-scheme>
               	    <scheme-ref>xdm-local-scheme</scheme-ref>
                </local-scheme>

                <!--read-write-backing-map-scheme>
                    <internal-cache-scheme>
                        <local-scheme/>
                    </internal-cache-scheme>
                    <cachestore-scheme>
                    	<class-scheme>
                        	<class-name>spring-bean:sqCacheStore</class-name>
                        </class-scheme>
                    </cachestore-scheme>
                </read-write-backing-map-scheme-->
            </backing-map-scheme>
            <autostart>true</autostart>
        </distributed-scheme>

        <invocation-scheme>
            <scheme-name>xdm-invocation-scheme</scheme-name>
            <service-name>InvocationService</service-name>
            <thread-count system-property="xdm.cache.threads.invocationScheme">150</thread-count>
            <guardian-timeout>3600000</guardian-timeout>
            <!--task-hung-threshold>60000</task-hung-threshold> <task-timeout>70000</task-timeout -->
            <autostart system-property="tangosol.coherence.invocation.autostart">true</autostart>
        </invocation-scheme>

        <invocation-scheme>
            <scheme-name>xdm-population-scheme</scheme-name>
            <service-name>PopulationService</service-name>
            <thread-count system-property="xdm.cache.threads.populationScheme">70</thread-count>
            <guardian-timeout>3600000</guardian-timeout>
            <!--task-hung-threshold>60000</task-hung-threshold> <task-timeout>70000</task-timeout -->
            <autostart system-property="tangosol.coherence.invocation.autostart">true</autostart>
        </invocation-scheme>

    </caching-schemes>

</cache-config>


text:
function RVGTLine(margin, rowHeight) {
	this.elements = new Array;
	this.margin = margin;
	this.rowHeight = rowHeight;
	this.maxHeight = 0;
}

RVGTLine.prototype = {
	width: 0,
	elementsWidth: 0,
	firstThumbIndex: 0,

	add: function($elt, absIndex) {
		if (this.elements.length === 0)
			this.firstThumbIndex = absIndex;
		var w,h;

		if (! (w=$elt.data("w")) ) {
			if ( (w=$elt[0].getAttribute("width")) && (w=parseInt(w)) ) {
				h=parseInt($elt[0].getAttribute("height"));
			}
			else {
				w=$elt.width();
				h=$elt.height();
			}
			if (h > this.rowHeight) {
				w = Math.round(w * this.rowHeight/h);
				h = this.rowHeight;
			}
			$elt.data("w", w)
				.data("h", h);
		}
		else
			h=$elt.data("h");

		var eltObj = {
			$elt: $elt,
			w: w,
			h: h
		};
		this.elements.push(eltObj);

		if (eltObj.h > this.maxHeight)
			this.maxHeight = eltObj.h;

		this.width += this.margin + eltObj.w;
		this.elementsWidth += eltObj.w;
	},

	clear: function() {
		if (!this.elements.length) return;
		this.width = this.elementsWidth = 0;
		this.maxHeight = 0;
		this.elements.length = 0;
	}
}

function RVGThumbs(options) {
	this.opts = options;

	this.$thumbs = $('#thumbnails');
	if (this.$thumbs.length==0) return;
	this.$thumbs.css('text-align', 'left');

	this.opts.extraRowHeight = 0;
	if (window.devicePixelRatio > 1) {
		var dpr = window.devicePixelRatio;
		this.opts.resizeThreshold = 1.01;
		this.opts.resizeFactor = 0.95;
		this.opts.extraRowHeight = 6; /*loose sharpness but only for small screens when we could "almost" fit with full sharpness*/
		this.opts.rowHeight = Math.round(this.opts.rowHeight / dpr ) + this.opts.extraRowHeight;
	}
	else {
		this.opts.resizeThreshold = 1.12; /*if row is less than 12% larger than available width, distribute extra width through cropping*/
		this.opts.resizeFactor = 0.8;/* when row is more than 12% larger than available width, distribute extra width 80% through resizing and 20% through cropping*/
	}
	this.process();

	var that = this;
	$(window).on('resize', function() {
		if (Math.abs(that.$thumbs.width() - that.prevContainerWidth)>1)
			that.process();
	})
		.on('RVTS_loaded', function(evt, down) {
			that.process( down && that.$thumbs.width() == that.prevContainerWidth ? that.prevLastLineFirstThumbIndex : 0);
		} );

	if (!$.isReady) {
		$(document).ready( function() {
			if ( that.$thumbs.width() < that.prevContainerWidth )
				that.process();
			} );
	}
}

RVGThumbs.prototype = {
	prevContainerWidth:0,
	prevLastLineFirstThumbIndex: 0,

	process: function(startIndex) {
		startIndex = startIndex ? startIndex : 0;
		var containerWidth  = this.$thumbs.width()
			, maxExtraMarginPerThumb = 1;
		this.prevContainerWidth = containerWidth;

		var $elts = $('li>a>img', this.$thumbs)
			, line  = new RVGTLine(this.opts.hMargin, this.opts.rowHeight);

		for (var i=startIndex; i<$elts.length; i++) {
			var $elt = $( $elts[i] );

			line.add($elt, i);
			if (line.width >= containerWidth - maxExtraMarginPerThumb * line.elements.length) {
				this.processLine(line, containerWidth);
				line.clear();
			}
		};

		if(line.elements.length)
			this.processLine(line, containerWidth, true);
		this.prevLastLineFirstThumbIndex = line.firstThumbIndex;
	},

	processLine: function(line, containerWidth, lastLine) {
		var toRecover, eltW, eltH
			, rowHeight = line.maxHeight ? line.maxHeight : line.elements[0].h;

		if (line.width / containerWidth > this.opts.resizeThreshold) {
			var ratio = line.elementsWidth / (line.elementsWidth + containerWidth - line.width);
			var adjustedRowHeight = rowHeight / (1 + (ratio-1) * this.opts.resizeFactor );
			adjustedRowHeight = 6 * Math.round( adjustedRowHeight/6 );
			if (adjustedRowHeight < rowHeight / ratio ) {
				adjustedRowHeight = Math.ceil( rowHeight / ratio );
				var missing = this.opts.rowHeight - this.opts.extraRowHeight - adjustedRowHeight;
				if (missing>0 && missing<6)
					adjustedRowHeight += missing;
			}
			if (adjustedRowHeight < rowHeight)
				rowHeight = adjustedRowHeight;
		}
		else if (lastLine)
			rowHeight = Math.min( rowHeight, this.opts.rowHeight - this.opts.extraRowHeight);

		toRecover = line.width - containerWidth;
		if (lastLine)
			toRecover = 0;

		for(var i=0; i<line.elements.length; i++) {
			var eltObj = line.elements[i]
				, eltW=eltObj.w
				, eltH=eltObj.h
				, eltToRecover;

			if (i==line.elements.length-1)
				eltToRecover = toRecover;
			else
				eltToRecover = Math.round(toRecover * eltW / line.elementsWidth);

			toRecover -= eltToRecover;
			line.elementsWidth -= eltW;

			if (eltH > rowHeight ) {
				eltW = Math.round( eltW * rowHeight/eltObj.h );
				eltH = rowHeight;
				eltToRecover -= eltObj.w - eltW;
				if (lastLine)
					eltToRecover = 0;
			}

			this.reposition(eltObj.$elt, eltW, eltH, eltW-eltToRecover, rowHeight);
		}
	},

	reposition: function($img, imgW, imgH, liW, liH) {
		/* JQuery .attr and .css functions add too much overhead ...*/
		var elt = $img[0];
		elt.setAttribute("width", imgW+"");
		elt.setAttribute("height", imgH+"");

		elt = elt.parentNode;//a
		elt.style.left = Math.round((liW-imgW)/2)+"px";
		elt.style.top = Math.round((liH-imgH)/2)+"px";

		elt = elt.parentNode;//li
		elt.style.width = liW+"px";
		elt.style.height = liH+"px";

	}

}


text:
require 'test_helper'

module Explorer
  class ListingsControllerTest < ActionController::TestCase
    setup do
      @routes = Engine.routes
    end

    test "should get index" do
      get :index
      assert_response :success
    end

    test "should get show" do
      get :show
      assert_response :success
    end

    test "should get new" do
      get :new
      assert_response :success
    end

    test "should get edit" do
      get :edit
      assert_response :success
    end

  end
end


text:
using namespace std;

namespace EGF {
using namespace Audio;
using namespace FreeType;
using namespace Graphics2D;

ResourceManager::ResourceManager():
    resourceLoader_(0)
{}

string ResourceManager::getFileData(const string& fileName) throw(invalid_argument, runtime_error) {

    std::lock_guard<std::mutex> guard(resourceLoaderAccess_);

    ASSERT( // åñëè íåò çàãðóç÷èêà ðåñóðñîâ
        (resourceLoader_ != 0),
        runtime_error(
            (boost::format("Can't load resource \"%1%\"")
                % fileName
            ).str()
        )
    );

    return resourceLoader_->readFile(fileName);

}

void ResourceManager::setResourceLoader(ResourceLoader* resourceLoader) throw(invalid_argument) {

    ASSERT(
        (resourceLoader != 0),
        invalid_argument("resourceLoader")
    );

    std::lock_guard<std::mutex> lockGuard(resourceLoaderAccess_);

    resourceLoader_ = resourceLoader;

}

template<> std::map< std::string, boost::shared_ptr<Font> >&
ResourceManager::getResourcesMap<Font>() {

    return fonts_;

}

template<> std::map< std::string, boost::shared_ptr<Texture> >&
ResourceManager::getResourcesMap<Texture>() {

    return textures_;

}

template<> std::map< std::string, boost::shared_ptr<Sound>  >&
ResourceManager::getResourcesMap<Sound>() {

    return sounds_;

}

template<>
boost::shared_ptr<Font> ResourceManager::loadResource<Font>(const std::string& name) throw(std::invalid_argument, std::runtime_error) {

    return resourceLoader_->loadFont(name);

}

template<>
boost::shared_ptr<Texture> ResourceManager::loadResource<Texture>(const std::string& name) throw(std::invalid_argument, std::runtime_error) {

    return resourceLoader_->loadTexture(name);

}

template<>
boost::shared_ptr<Sound> ResourceManager::loadResource<Sound>(const std::string& name) throw(std::invalid_argument, std::runtime_error) {

    return resourceLoader_->loadSound(name);

}

template<>
std::mutex& ResourceManager::getResourcesAccessMutex<Font>() {

    return fontsAccess_;

}

template<>
std::mutex& ResourceManager::getResourcesAccessMutex<Texture>() {

    return texturesAccess_;

}

template<>
std::mutex& ResourceManager::getResourcesAccessMutex<Sound>() {

    return soundsAccess_;

}

}


text:
// TypeScript Version: 2.0

/**
* Returns an object value.
*
* @returns new value
*/
type Nullary = () => any;

/**
* Returns an object value.
*
* @param value - object value corresponding to `key`
* @returns new value
*/
type Unary = ( key: string ) => any;

/**
* Returns an object value.
*
* @param value - object value corresponding to `key`
* @param key - object key
* @returns new value
*/
type Binary = ( value: any, key: string ) => any;

/**
* Returns an object value.
*
* @param value - object value corresponding to `key`
* @param key - object key
* @param obj - the input object
* @returns new value
*/
type Ternary = ( value: any, key: string, obj: any ) => any;

/**
* Returns an object value.
*
* @param value - object value corresponding to `key`
* @param key - object key
* @param obj - the input object
* @returns new value
*/
type Transform = Nullary | Unary | Binary | Ternary;

/**
* Maps values from one object to a new object having the same keys.
*
* ## Notes
*
* -   The transform function is provided three arguments:
*
*     -   `value`: object value corresponding to `key`
*     -   `key`: object key
*     -   `obj`: the input object
*
* -   The function only maps values from own properties. Hence, the function does not map inherited properties.
*
* -   The function shallow copies key values.
*
* -   Iteration order is **not** guaranteed.
*
* @param obj - source object
* @param transform - transform function
* @returns new object
*
* @example
* function transform( value, key ) {
*     return key + value;
* }
*
* var obj1 = {
*     'a': 1,
*     'b': 2
* };
*
* var obj2 = mapValues( obj1, transform );
* // returns { 'a': 'a1', 'b': 'b2' }
*/
declare function mapValues( obj: any, transform: Transform ): any;

// EXPORTS //

export = mapValues;


text:
require 'twitter/bootswatch/rails/fontawesome/version'

module Twitter
  module Bootswatch
    module Rails
      module Fontawesome
        require 'twitter/bootswatch/rails/fontawesome/engine' if defined?(::Rails)
      end
    end
  end
end

require 'less-rails'
require 'twitter/bootswatch/rails/fontawesome/engine' if defined?(::Rails)


text:
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, FormattedMessage } from 'react-intl';
import { createValidator } from '../../core/validation';

const createMinLengthValidation = length => value => {
  if (value.length >= length) {
    return { touched: false };
  }
  return { touched: true, errorName: 'min', args: length };
};
const createMaxLengthValidation = length => value => {
  if (value.length <= length) {
    return { touched: false };
  }
  return { touched: true, errorName: 'max', args: length };
};

const messages = defineMessages({
  empty: {
    id: 'form.error-empty',
    defaultMessage: "You can't leave this empty",
    description: 'Help for empty fields',
  },
  wrongSelect: {
    id: 'form.error-select',
    defaultMessage: 'You selection is not correct. Click on a suggestion',
    description:
      'Help for selection, when input does not match with a suggestion',
  },
  min: {
    id: 'form.error-min',
    defaultMessage: 'Enter atleast {value} chars or numbers',
    description: 'Min',
  },
  invalidEmail: {
    id: 'form.error-invalidEmail',
    defaultMessage: 'Your email address seems to be invalid',
    description: 'Help for email',
  },
  emailTaken: {
    id: 'form.error-emailTaken',
    defaultMessage: 'Email address already in use',
    description: 'Help for not unique email',
  },
  shortPassword: {
    id: 'form.error-shortPassword',
    defaultMessage:
      'Short passwords are easy to guess. Try one with at least 6 characters ',
    description: 'Help for short passwords',
  },
  wrongPassword: {
    id: 'settings.error.passwordOld',
    defaultMessage: 'Wrong password',
    description: 'Wrong password entered',
  },
  passwordMismatch: {
    id: 'form.error-passwordMismatch',
    defaultMessage: "These passwords don't match. Try again?",
    description: 'Help for mismatching passwords',
  },
  dateTime: {
    id: 'form.error-past',
    defaultMessage: 'Time already passed',
    description: 'Help for wrong time settings',
  },
});

const genInitialState = (fields, values) =>
  fields.reduce(
    (acc, curr) => {
      acc[curr] = values[curr] || '';
      acc.errors[curr] = { touched: false };
      return acc;
    },
    { errors: {} },
  );

const genValidateFn = ({ fn, args = {} }) => {
  const allFns = [];
  if (fn) {
    allFns.push(fn);
  }
  if (args.min) {
    allFns.push(createMinLengthValidation(args.min));
  }
  if (args.max) {
    allFns.push(createMaxLengthValidation(args.max));
  }
  return (value, state, options, fieldName) => {
    /* breaks after it found an error */
    let error;

    if (value) {
      for (let i = 0; i < allFns.length; i += 1) {
        error = allFns[i](value, state, options, fieldName);
        if (error.touched) {
          break;
        }
      }
    } else if (args.required) {
      error = { touched: true, errorName: 'empty' };
    }

    return error || { touched: false };
  };
};

const getChangedFields = (inputFields, state, props) =>
  inputFields.reduce((agg, field) => {
    if (field in state) {
      if (field in props) {
        if (state[field] !== props[field]) {
          agg[field] = state[field]; // eslint-disable-line
        }
        // get only fields with values
      } else if (state[field]) {
        agg[field] = state[field]; // eslint-disable-line
      }
      // only in state
    }
    return agg;
  }, {});

class FormValidation extends React.Component {
  static propTypes = {
    validations: PropTypes.arrayOf(
      PropTypes.shape({
        fn: PropTypes.func,
        valuesResolver: PropTypes.func,
        args: PropTypes.shape({}),
      }),
    ).isRequired,
    data: PropTypes.shape({}),
    submit: PropTypes.func.isRequired,
    children: PropTypes.func.isRequired,
    names: PropTypes.shape({}),
    lazy: PropTypes.bool,
    eager: PropTypes.bool,
    onBlur: PropTypes.func,
    options: PropTypes.shape({}),
  };

  static defaultProps = {
    data: null,
    names: null,
    lazy: null,
    eager: null,
    onBlur: null,
    options: null,
  };

  constructor(props) {
    super(props);
    this.formFields = Object.keys(props.validations);
    this.state = {
      ...genInitialState(this.formFields, {
        ...(props.data && props.data),
        ...(props.names && { ...props.names }),
      }),
    };
    const validationMappings = Object.keys(props.validations).reduce(
      (acc, fieldName) => {
        let key;
        if (props.validations[fieldName].fn) {
          key = props.validations[fieldName].fn.name || `${fieldName}fn`;
        } else {
          key = fieldName;
        }
        acc[key] = genValidateFn(props.validations[fieldName]);
        return acc;
      },
      {},
    );

    const allValues = Object.keys(props.validations).reduce(
      (acc, fieldName) => {
        let key;
        if (props.validations[fieldName].fn) {
          key = props.validations[fieldName].fn.name || `${fieldName}fn`;
        } else {
          key = fieldName;
        }
        acc[fieldName] = {
          fn: key,
          ...(props.validations[fieldName].valuesResolver && {
            valuesResolver: props.validations[fieldName].valuesResolver,
          }),
        };
        return acc;
      },
      {},
    );

    this.Validator = createValidator(
      allValues,
      validationMappings,
      this,
      obj => obj.state,
    );

    this.handleValueChanges = this.handleValueChanges.bind(this);
    this.visibleErrors = this.visibleErrors.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.validate = this.validate.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
    this.enforceValidation = this.enforceValidation.bind(this);
  }

  componentWillReceiveProps({ data, options }) {
    const { data: oldData, options: oldOptions } = this.props;
    let newState = {};
    if ((data && data !== oldData) || (options && options !== oldOptions)) {
      newState = {
        ...genInitialState(this.formFields, {
          ...this.state,
          ...(data && data),
          ...(data && data.names && { ...data.names }),
        }),
      };
      if (options && options !== oldOptions) {
        newState = { ...newState, ...options };
      }
      this.setState(newState);
    }
  }

  onSubmit(e, options) {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    const { errors } = this.state;
    const { lazy, data, submit } = this.props;
    let fields = this.formFields;
    if (options && options.excludeFields && options.excludeFields.length) {
      fields = fields.filter(field => !options.excludeFields.includes(field));
    }
    const validationResult = this.validate(fields);
    const newState = {
      errors: { ...errors, ...validationResult.errors },
    };
    if (validationResult.failed === 0 || lazy) {
      /* this.setState(newState, () => {
        const newValues = getChangedFields(
          this.formFields,
          this.state,
          data || {},
        );
        if (submit) {
          submit(newValues, this.state, options);
        }
      }); */
      this.setState(newState);

      if (submit) {
        const nextState = { ...this.state, ...newState };
        const newValues = getChangedFields(
          this.formFields,
          nextState,
          data || {},
        );
        submit(newValues, nextState, options);
      }
      return true;
    }
    return this.setState(newState);
  }

  handleBlur(e) {
    const field = e.target.name;
    const fields = [];
    // eslint-disable-next-line react/destructuring-assignment
    if (this.state[field]) {
      fields.push(field);
      const { onBlur } = this.props;
      if (onBlur) {
        onBlur(field, this.state, fields);
      }
      const validationResult = this.validate(fields);
      this.setState(prevState => ({
        errors: {
          ...prevState.errors,
          ...validationResult.errors,
        },
      }));
    }
  }

  validate(fields) {
    return this.Validator(fields);
  }

  // TODO refactor
  enforceValidation(fields = this.formFields, options) {
    const validate = () => {
      const validationResult = this.validate(fields);
      const { data } = this.props;
      const { errors } = this.state;
      this.setState(prevState => ({
        errors: { ...prevState.errors, ...validationResult.errors },
      }));
      const newState = { errors: { ...errors, ...validationResult.errors } };
      const nextState = { ...this.state, ...newState };

      const newValues = getChangedFields(fields, nextState, data || {});
      return { isValid: validationResult.failed === 0, values: newValues };
    };
    if (options) {
      this.setState({ ...options }, validate);
      return false; // TODO not sure how to handle response
    }
    return validate();
  }

  visibleErrors(errorNames) {
    return errorNames.reduce((acc, curr) => {
      const err = `${curr}Error`;
      const fieldStatus = this.state.errors[curr]; // eslint-disable-line react/destructuring-assignment
      if (fieldStatus.touched) {
        acc[err] = (
          <FormattedMessage
            {...messages[fieldStatus.errorName]}
            values={{ value: fieldStatus.args }}
          />
        );
      }
      return acc;
    }, {});
  }

  handleValueChanges(e) {
    let value;
    if (e.target.type === 'checkbox') {
      value = !this.state[e.target.name]; // eslint-disable-line react/destructuring-assignment
    } else {
      value = e.target.value; //eslint-disable-line
    }
    const { errors } = this.state;
    const { eager } = this.props;
    const field = e.target.name;
    if (eager) {
      if (errors[field].touched) {
        this.setState(prevState => ({
          errors: {
            ...prevState.errors,
            [field]: { ...prevState.errors[field], touched: false },
          },
        }));
      }
    }
    this.setState({ [field]: value });
  }

  renderChildren() {
    const { data, children } = this.props;
    const { allValid } = this.state;
    const fields = getChangedFields(this.formFields, this.state, data || {});

    const inputChanged = Object.keys(fields).length > 0;
    return children({
      validate: this.handleValidate,
      errorMessages: this.visibleErrors(this.formFields),
      allValid,
      values: this.state,
      handleValueChanges: this.handleValueChanges,
      onSubmit: this.onSubmit,
      onBlur: this.handleBlur,
      inputChanged,
    });
  }

  render() {
    return this.renderChildren();
  }
}

export default FormValidation;


text:
<?xml version="1.0"?>
<!--

-->
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_layout.xsd">
    <reference name="any_handle_name" />
    <any_node>
        <reference name="singlechunk" />
    </any_node>
</layout>