text:
package nokogiri;

import static nokogiri.internals.NokogiriHelpers.getNokogiriClass;
import static nokogiri.internals.NokogiriHelpers.stringOrBlank;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.StringReader;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import nokogiri.internals.NokogiriXsltErrorListener;

import org.apache.xalan.transformer.TransformerImpl;
import org.apache.xml.serializer.SerializationHandler;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.w3c.dom.Document;

/**
 * Class for Nokogiri::XSLT::Stylesheet
 *
 * @author sergio
 * @author Yoko Harada <yokolet@gmail.com>
 */
@JRubyClass(name="Nokogiri::XSLT::Stylesheet")
public class XsltStylesheet extends RubyObject {
    private static Map<String, Object> registry = new HashMap<String, Object>();
    private TransformerFactory factory = null;
    private Templates sheet = null;
    private IRubyObject stylesheet = null;
    private boolean htmlish = false;

    public static Map<String, Object> getRegistry() {
        return registry;
    }

    public XsltStylesheet(Ruby ruby, RubyClass rubyClass) {
        super(ruby, rubyClass);
    }

    /**
     * Create and return a copy of this object.
     *
     * @return a clone of this object
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    private void addParametersToTransformer(ThreadContext context, Transformer transf, IRubyObject parameters) {
        Ruby runtime = context.getRuntime();

        if (parameters instanceof RubyHash) {
            setHashParameters(transf, (RubyHash)parameters);
        } else if (parameters instanceof RubyArray) {
            setArrayParameters(transf, runtime, (RubyArray)parameters);
        } else {
            throw runtime.newTypeError("parameters should be given either Array or Hash");
        }
    }

    private void setHashParameters(Transformer transformer, RubyHash hash) {
        Set<String> keys = hash.keySet();
        for (String key : keys) {
            String value = (String)hash.get(key);
            transformer.setParameter(key, unparseValue(value));
        }
    }

    private void setArrayParameters(Transformer transformer, Ruby runtime, RubyArray params) {
        int limit = params.getLength();
        if(limit % 2 == 1) limit--;

        for(int i = 0; i < limit; i+=2) {
            String name = params.aref(runtime.newFixnum(i)).asJavaString();
            String value = params.aref(runtime.newFixnum(i+1)).asJavaString();
            transformer.setParameter(name, unparseValue(value));
        }
    }

    private Pattern p = Pattern.compile("'.{1,}'");

    private String unparseValue(String orig) {
        Matcher m = p.matcher(orig);
        if ((orig.startsWith("\"") && orig.endsWith("\"")) || m.matches()) {
            orig = orig.substring(1, orig.length()-1);
        }

        return orig;
    }

    @JRubyMethod(meta = true, rest = true)
    public static IRubyObject parse_stylesheet_doc(ThreadContext context, IRubyObject klazz, IRubyObject[] args) {

        Ruby runtime = context.getRuntime();

        ensureFirstArgIsDocument(runtime, args[0]);

        XmlDocument xmlDoc = (XmlDocument) args[0];
        ensureDocumentHasNoError(context, xmlDoc);

        Document doc = ((XmlDocument) xmlDoc.dup_implementation(context, true)).getDocument();

        XsltStylesheet xslt =
            (XsltStylesheet) NokogiriService.XSLT_STYLESHEET_ALLOCATOR.allocate(runtime, (RubyClass)klazz);

        try {
            xslt.init(args[1], doc);
        } catch (TransformerConfigurationException ex) {
            throw runtime.newRuntimeError("could not parse xslt stylesheet");
        }

        return xslt;
    }

    private void init(IRubyObject stylesheet, Document document) throws TransformerConfigurationException {
        this.stylesheet = stylesheet;  // either RubyString or RubyFile
        if (factory == null) factory = TransformerFactory.newInstance();
        NokogiriXsltErrorListener elistener = new NokogiriXsltErrorListener();
        factory.setErrorListener(elistener);
        sheet = factory.newTemplates(new DOMSource(document));
    }

    private static void ensureFirstArgIsDocument(Ruby runtime, IRubyObject arg) {
        if (arg instanceof XmlDocument) {
            return;
        } else {
            throw runtime.newArgumentError("doc must be a Nokogiri::XML::Document instance");
        }
    }

    private static void ensureDocumentHasNoError(ThreadContext context, XmlDocument xmlDoc) {
        Ruby runtime = context.getRuntime();
        RubyArray errors_of_xmlDoc = (RubyArray) xmlDoc.getInstanceVariable("@errors");
        if (!errors_of_xmlDoc.isEmpty()) {
            throw runtime.newRuntimeError(errors_of_xmlDoc.first().asString().asJavaString());
        }
    }

    @JRubyMethod
    public IRubyObject serialize(ThreadContext context, IRubyObject doc) throws IOException, TransformerException {
    	XmlDocument xmlDoc = (XmlDocument) doc;
    	TransformerImpl transformer = (TransformerImpl) this.sheet.newTransformer();
    	ByteArrayOutputStream writer = new ByteArrayOutputStream();
    	StreamResult streamResult = new StreamResult(writer);
    	SerializationHandler serializationHandler = transformer.createSerializationHandler(streamResult);
    	serializationHandler.serialize(xmlDoc.getNode());
    	return context.getRuntime().newString(writer.toString());
    }

    @JRubyMethod(rest = true, required=1, optional=2)
    public IRubyObject transform(ThreadContext context, IRubyObject[] args) {
        Ruby runtime = context.getRuntime();

        argumentTypeCheck(runtime, args[0]);

        NokogiriXsltErrorListener elistener = new NokogiriXsltErrorListener();
        DOMSource domSource = new DOMSource(((XmlDocument) args[0]).getDocument());
        DOMResult result = null;
        String stringResult = null;
        try{
            result = tryXsltTransformation(context, args, domSource, elistener); // DOMResult
            if (result.getNode().getFirstChild() == null) {
                stringResult = retryXsltTransformation(context, args, domSource, elistener); // StreamResult
            }
        } catch(TransformerConfigurationException ex) {
            throw runtime.newRuntimeError(ex.getMessage());
        } catch(TransformerException ex) {
            throw runtime.newRuntimeError(ex.getMessage());
        } catch (IOException ex) {
            throw runtime.newRuntimeError(ex.getMessage());
        }

        switch (elistener.getErrorType()) {
            case ERROR:
            case FATAL:
                throw runtime.newRuntimeError(elistener.getErrorMessage());
            case WARNING:
            default:
                // no-op
        }

        if (stringResult == null) {
            return createDocumentFromDomResult(context, runtime, result);
        } else {
            return createDocumentFromString(context, runtime, stringResult);
        }
    }

    private DOMResult tryXsltTransformation(ThreadContext context, IRubyObject[] args, DOMSource domSource, NokogiriXsltErrorListener elistener) throws TransformerException {
        Transformer transf = sheet.newTransformer();
        transf.reset();
        transf.setErrorListener(elistener);
        if (args.length > 1) {
            addParametersToTransformer(context, transf, args[1]);
        }

        DOMResult result = new DOMResult();
        transf.transform(domSource, result);
        return result;
    }

    private String retryXsltTransformation(ThreadContext context,
                                           IRubyObject[] args,
                                           DOMSource domSource,
                                           NokogiriXsltErrorListener elistener)
            throws TransformerException, IOException {
        Templates templates = getTemplatesFromStreamSource();
        Transformer transf = templates.newTransformer();
        transf.setErrorListener(elistener);
        if (args.length > 1) {
            addParametersToTransformer(context, transf, args[1]);
        }
        PipedWriter pwriter = new PipedWriter();
        PipedReader preader = new PipedReader();
        pwriter.connect(preader);
        StreamResult result = new StreamResult(pwriter);
        transf.transform(domSource, result);
        char[] cbuf = new char[1024];
        int len = preader.read(cbuf, 0, 1024);
        StringBuilder builder = new StringBuilder();
        builder.append(CharBuffer.wrap(cbuf, 0, len));
        htmlish = isHtml(builder.toString()); // judge from the first chunk

        while (len == 1024) {
            len = preader.read(cbuf, 0, 1024);
            if (len > 0) {
                builder.append(CharBuffer.wrap(cbuf, 0, len));
            }
        }

        preader.close();
        pwriter.close();

        return builder.toString();
    }

    private IRubyObject createDocumentFromDomResult(ThreadContext context, Ruby runtime, DOMResult domResult) {
        if ("html".equals(domResult.getNode().getFirstChild().getNodeName())) {
            HtmlDocument htmlDocument = (HtmlDocument) getNokogiriClass(runtime, "Nokogiri::HTML::Document").allocate();
            htmlDocument.setDocumentNode(context, (Document) domResult.getNode());
            return htmlDocument;
        } else {
            XmlDocument xmlDocument = (XmlDocument) NokogiriService.XML_DOCUMENT_ALLOCATOR.allocate(runtime, getNokogiriClass(runtime, "Nokogiri::XML::Document"));
            xmlDocument.setDocumentNode(context, (Document) domResult.getNode());
            return xmlDocument;
        }
    }

    private Templates getTemplatesFromStreamSource() throws TransformerConfigurationException {
        if (stylesheet instanceof RubyString) {
            StringReader reader = new StringReader((String)stylesheet.toJava(String.class));
            StreamSource xsltStreamSource = new StreamSource(reader);
            return factory.newTemplates(xsltStreamSource);
        }
        return null;
    }

    private static Pattern html_tag =
        Pattern.compile("<(%s)*html", Pattern.CASE_INSENSITIVE);

    private boolean isHtml(String chunk) {
        Matcher m = XsltStylesheet.html_tag.matcher(chunk);
        if (m.find()) return true;
        else return false;
    }

    private IRubyObject createDocumentFromString(ThreadContext context, Ruby runtime, String stringResult) {
        IRubyObject[] args = new IRubyObject[4];
        args[0] = stringOrBlank(runtime, stringResult);
        args[1] = runtime.getNil();  // url
        args[2] = runtime.getNil();  // encoding
        RubyClass parse_options = (RubyClass)runtime.getClassFromPath("Nokogiri::XML::ParseOptions");
        if (htmlish) {
            args[3] = parse_options.getConstant("DEFAULT_HTML");
            RubyClass htmlDocumentClass = getNokogiriClass(runtime, "Nokogiri::HTML::Document");
            return RuntimeHelpers.invoke(context, htmlDocumentClass, "parse", args);
        } else {
            args[3] = parse_options.getConstant("DEFAULT_XML");
            RubyClass xmlDocumentClass = getNokogiriClass(runtime, "Nokogiri::XML::Document");
            XmlDocument xmlDocument = (XmlDocument) RuntimeHelpers.invoke(context, xmlDocumentClass, "parse", args);
            if (((Document)xmlDocument.getNode()).getDocumentElement() == null) {
                RubyArray errors = (RubyArray) xmlDocument.getInstanceVariable("@errors");
                RuntimeHelpers.invoke(context, errors, "<<", args[0]);
            }
            return xmlDocument;
        }
    }

    private void argumentTypeCheck(Ruby runtime, IRubyObject arg) {
        if (arg instanceof XmlDocument) {
            return;
        } else {
            throw runtime.newArgumentError("argument must be a Nokogiri::XML::Document");
        }
    }

    @JRubyMethod(name = {"registr", "register"}, meta = true)
    public static IRubyObject register(ThreadContext context, IRubyObject cls, IRubyObject uri, IRubyObject receiver) {
        throw context.getRuntime().newNotImplementedError("Nokogiri::XSLT.register method is not implemented");
        /* When API conflict is solved, this method should be below:
        // ThreadContext is used while executing xslt extension function
        registry.put("context", context);
        registry.put("receiver", receiver);
        return context.getRuntime().getNil();
        */
    }
}


text:
package org.apache.hadoop.mapred;

import java.io.IOException;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapred.JobClient.RawSplit;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.TaskID;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
import org.apache.hadoop.metrics.MetricsContext;
import org.apache.hadoop.metrics.MetricsUtil;
import org.apache.hadoop.net.Node;
import org.apache.hadoop.tools.rumen.JobStory;
import org.apache.hadoop.tools.rumen.Pre21JobHistoryConstants;
import org.apache.hadoop.tools.rumen.ReduceTaskAttemptInfo;
import org.apache.hadoop.tools.rumen.TaskAttemptInfo;

public class SimulatorJobInProgress extends JobInProgress {
  static final Log LOG = LogFactory.getLog(SimulatorJobInProgress.class);

  // JobStory that contains all information that should be read from the
  // cache
  private final JobStory jobStory;

  RawSplit[] splits;

  @SuppressWarnings("deprecation")
  public SimulatorJobInProgress(JobID jobid, JobTracker jobtracker,
      JobConf default_conf, JobStory jobStory) {
    super(jobid, jobStory.getJobConf(), jobtracker);
    // jobSetupCleanupNeeded set to false in parent cstr, though
    // default is true

    restartCount = 0;
    jobSetupCleanupNeeded = false;

    this.memoryPerMap = conf.getMemoryForMapTask();
    this.memoryPerReduce = conf.getMemoryForReduceTask();
    this.maxTaskFailuresPerTracker = conf.getMaxTaskFailuresPerTracker();

    this.jobId = jobid;
    String url = "http://" + jobtracker.getJobTrackerMachine() + ":"
        + jobtracker.getInfoPort() + "/jobdetails.jsp?jobid=" + jobid;
    this.jobtracker = jobtracker;
    this.conf = jobStory.getJobConf();
    this.priority = conf.getJobPriority();
    Path jobDir = jobtracker.getSystemDirectoryForJob(jobid);
    this.jobFile = new Path(jobDir, "job.xml");
    this.status = new JobStatus(jobid, 0.0f, 0.0f, 0.0f, 0.0f, JobStatus.PREP,
            priority, conf.getUser());
    this.profile = new JobProfile(jobStory.getUser(), jobid, this.jobFile
        .toString(), url, jobStory.getName(), conf.getQueueName());
    this.startTime = JobTracker.getClock().getTime();
    status.setStartTime(startTime);
    this.resourceEstimator = new ResourceEstimator(this);

    this.numMapTasks = jobStory.getNumberMaps();
    this.numReduceTasks = jobStory.getNumberReduces();
    this.taskCompletionEvents = new ArrayList<TaskCompletionEvent>(numMapTasks
        + numReduceTasks + 10);

    this.mapFailuresPercent = conf.getMaxMapTaskFailuresPercent();
    this.reduceFailuresPercent = conf.getMaxReduceTaskFailuresPercent();
    MetricsContext metricsContext = MetricsUtil.getContext("mapred");
    this.jobMetrics = MetricsUtil.createRecord(metricsContext, "job");
    this.jobMetrics.setTag("user", conf.getUser());
    this.jobMetrics.setTag("sessionId", conf.getSessionId());
    this.jobMetrics.setTag("jobName", conf.getJobName());
    this.jobMetrics.setTag("jobId", jobid.toString());

    this.maxLevel = jobtracker.getNumTaskCacheLevels();
    this.anyCacheLevel = this.maxLevel + 1;
    this.nonLocalMaps = new LinkedList<TaskInProgress>();
    this.nonLocalRunningMaps = new LinkedHashSet<TaskInProgress>();
    this.runningMapCache = new IdentityHashMap<Node, Set<TaskInProgress>>();
    this.nonRunningReduces = new LinkedList<TaskInProgress>();
    this.runningReduces = new LinkedHashSet<TaskInProgress>();
    this.slowTaskThreshold = Math.max(0.0f, conf.getFloat(
        "mapred.speculative.execution.slowTaskThreshold", 1.0f));
    this.speculativeCap = conf.getFloat(
        "mapred.speculative.execution.speculativeCap", 0.1f);
    this.slowNodeThreshold = conf.getFloat(
        "mapred.speculative.execution.slowNodeThreshold", 1.0f);

    this.jobStory = jobStory;
//    this.jobHistory = this.jobtracker.getJobHistory();
  }

  // for initTasks, update information from JobStory object
  @Override
  public synchronized void initTasks() throws IOException {
    boolean loggingEnabled = LOG.isDebugEnabled();
    if (loggingEnabled) {
      LOG.debug("(initTasks@SJIP) Starting Initialization for " + jobId);
    }
    numMapTasks = jobStory.getNumberMaps();
    numReduceTasks = jobStory.getNumberReduces();

    JobHistory.JobInfo.logSubmitted(getJobID(), conf, jobFile.toString(),
                                    this.startTime, hasRestarted());
    if (loggingEnabled) {
      LOG.debug("(initTasks@SJIP) Logged to job history for " + jobId);
    }

//    checkTaskLimits();

    if (loggingEnabled) {
      LOG.debug("(initTasks@SJIP) Checked task limits for " + jobId);
    }

    final String jobFile = "default";
    splits = getRawSplits(jobStory.getInputSplits());
    if (loggingEnabled) {
      LOG.debug("(initTasks@SJIP) Created splits for job = " + jobId
          + " number of splits = " + splits.length);
    }

//    createMapTasks(jobFile, splits);

    numMapTasks = splits.length;
    maps = new TaskInProgress[numMapTasks];
    for (int i=0; i < numMapTasks; ++i) {
      inputLength += splits[i].getDataLength();
      maps[i] = new TaskInProgress(jobId, jobFile,
                                   splits[i],
                                   jobtracker, conf, this, i, numSlotsPerMap);
    }
    if (numMapTasks > 0) {
      nonRunningMapCache = createCache(splits, maxLevel);
      if (loggingEnabled) {
        LOG.debug("initTasks:numMaps=" + numMapTasks
            + " Size of nonRunningMapCache=" + nonRunningMapCache.size()
            + " for " + jobId);
      }
    }

    // set the launch time
    this.launchTime = JobTracker.getClock().getTime();

//    createReduceTasks(jobFile);

    //
    // Create reduce tasks
    //
    this.reduces = new TaskInProgress[numReduceTasks];
    for (int i = 0; i < numReduceTasks; i++) {
      reduces[i] = new TaskInProgress(jobId, jobFile,
                                      numMapTasks, i,
                                      jobtracker, conf, this, numSlotsPerReduce);
      nonRunningReduces.add(reduces[i]);
    }

    // Calculate the minimum number of maps to be complete before
    // we should start scheduling reduces
    completedMapsForReduceSlowstart = (int) Math.ceil((conf.getFloat(
        "mapred.reduce.slowstart." + "completed.maps",
        DEFAULT_COMPLETED_MAPS_PERCENT_FOR_REDUCE_SLOWSTART) * numMapTasks));

    tasksInited.set(true);
    if (loggingEnabled) {
      LOG.debug("Initializing job, nowstatus = "
          + JobStatus.getJobRunState(getStatus().getRunState()));
    }
    setupComplete();

    if (loggingEnabled) {
      LOG.debug("Initializing job, inited-status = "
          + JobStatus.getJobRunState(getStatus().getRunState()));
    }
  }

  RawSplit[] getRawSplits(InputSplit[] splits) throws IOException {
    if (splits == null || splits.length != numMapTasks) {
      throw new IllegalArgumentException("Input split size mismatch: expected="
          + numMapTasks + ", actual=" + ((splits == null) ? -1 : splits.length));
    }

    RawSplit rawSplits[] = new RawSplit[splits.length];
    for (int i = 0; i < splits.length; i++) {
      try {
        rawSplits[i] = new RawSplit();
        rawSplits[i].setClassName(splits[i].getClass().getName());
        rawSplits[i].setDataLength(splits[i].getLength());
        rawSplits[i].setLocations(splits[i].getLocations());
      } catch (InterruptedException ie) {
        throw new IOException(ie);
      }
    }

    return rawSplits;
  }

  /**
   * Given the map taskAttemptID, returns the TaskAttemptInfo. Deconstructs the
   * map's taskAttemptID and looks up the jobStory with the parts taskType, id
   * of task, id of task attempt.
   *
   * @param taskTracker
   *          tasktracker
   * @param taskAttemptID
   *          task-attempt
   * @return TaskAttemptInfo for the map task-attempt
   */
  @SuppressWarnings("deprecation")
  private synchronized TaskAttemptInfo getMapTaskAttemptInfo(
      TaskTracker taskTracker, TaskAttemptID taskAttemptID) {
    assert (taskAttemptID.isMap());

    JobID jobid = (JobID) taskAttemptID.getJobID();
    assert (jobid == getJobID());

    // Get splits for the TaskAttempt
    RawSplit split = splits[taskAttemptID.getTaskID().getId()];
    int locality = getClosestLocality(taskTracker, split);

    TaskID taskId = taskAttemptID.getTaskID();
    if (!taskId.isMap()) {
      assert false : "Task " + taskId + " is not MAP :";
    }

    TaskAttemptInfo taskAttemptInfo = jobStory.getMapTaskAttemptInfoAdjusted(
        taskId.getId(), taskAttemptID.getId(), locality);

    if (LOG.isDebugEnabled()) {
      LOG.debug("get an attempt: "
          + taskAttemptID.toString()
          + ", state="
          + taskAttemptInfo.getRunState()
          + ", runtime="
          + ((taskId.isMap()) ? taskAttemptInfo.getRuntime()
              : ((ReduceTaskAttemptInfo) taskAttemptInfo).getReduceRuntime()));
    }
    return taskAttemptInfo;
  }

  private int getClosestLocality(TaskTracker taskTracker, RawSplit split) {
    int locality = 2;

    Node taskTrackerNode = jobtracker
        .getNode(taskTracker.getStatus().getHost());
    if (taskTrackerNode == null) {
      throw new IllegalArgumentException(
          "Cannot determine network topology node for TaskTracker "
              + taskTracker.getTrackerName());
    }
    for (String location : split.getLocations()) {
      Node dataNode = jobtracker.getNode(location);
      if (dataNode == null) {
        throw new IllegalArgumentException(
            "Cannot determine network topology node for split location "
                + location);
      }
      locality = Math.min(locality, jobtracker.clusterMap.getDistance(
          taskTrackerNode, dataNode));
    }
    return locality;
  }

  @SuppressWarnings("deprecation")
  public TaskAttemptInfo getTaskAttemptInfo(TaskTracker taskTracker,
      TaskAttemptID taskAttemptId) {
    JobID jobid = (JobID) taskAttemptId.getJobID();
    assert (jobid == getJobID());

    return (taskAttemptId.isMap()) ? getMapTaskAttemptInfo(
        taskTracker, taskAttemptId)
        : getReduceTaskAttemptInfo(taskTracker, taskAttemptId);
  }

  /**
   * Given the reduce taskAttemptID, returns the TaskAttemptInfo. Deconstructs
   * the reduce taskAttemptID and looks up the jobStory with the parts taskType,
   * id of task, id of task attempt.
   *
   * @param taskTracker
   *          tasktracker
   * @param taskAttemptID
   *          task-attempt
   * @return TaskAttemptInfo for the reduce task-attempt
   */
  private TaskAttemptInfo getReduceTaskAttemptInfo(TaskTracker taskTracker,
      TaskAttemptID taskAttemptID) {
    assert (!taskAttemptID.isMap());
    TaskID taskId = taskAttemptID.getTaskID();
    TaskType taskType;
    if (taskAttemptID.isMap()) {
      taskType = TaskType.MAP;
    } else {
      taskType = TaskType.REDUCE;
    }

    TaskAttemptInfo taskAttemptInfo = jobStory.getTaskAttemptInfo(taskType,
        taskId.getId(), taskAttemptID.getId());
    if (LOG.isDebugEnabled()) {
      LOG.debug("get an attempt: "
          + taskAttemptID.toString()
          + ", state="
          + taskAttemptInfo.getRunState()
          + ", runtime="
          + ((taskAttemptID.isMap()) ? taskAttemptInfo.getRuntime()
              : ((ReduceTaskAttemptInfo) taskAttemptInfo).getReduceRuntime()));
    }
    return taskAttemptInfo;
  }
}

redpajama_set_name: RedPajamaGithub


text:
status=0
mkdir test_root

if ./cleantree test_root
then
    status=1
fi

rmdir test_root
exit $status


text:
package com.xtremelabs.robolectric.shadows;

import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.util.Strings;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultRequestDirector;
import org.apache.http.protocol.HttpContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.net.URI;

import static com.xtremelabs.robolectric.Robolectric.shadowOf;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;

@RunWith(WithTestDefaultsRunner.class)
public class DefaultRequestDirectorTest {
    private DefaultRequestDirector requestDirector;
    private ConnectionKeepAliveStrategy connectionKeepAliveStrategy;

    @Before
    public void setUp_EnsureStaticStateIsReset() {
        FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
        assertTrue(fakeHttpLayer.pendingHttpResponses.isEmpty());
        assertTrue(fakeHttpLayer.httpRequestInfos.isEmpty());
        assertTrue(fakeHttpLayer.httpResponseRules.isEmpty());
        assertNull(fakeHttpLayer.defaultHttpResponse);

        connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
            @Override public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
                return 0;
            }
        };
        requestDirector = new DefaultRequestDirector(null, null, null, connectionKeepAliveStrategy, null, null, null, null, null, null, null, null);
    }

    @After
    public void tearDown_EnsureStaticStateIsReset() throws Exception {
        Robolectric.addPendingHttpResponse(200, "a happy response body");
    }

    @Test
    public void shouldGetHttpResponseFromExecute() throws Exception {
        Robolectric.addPendingHttpResponse(new TestHttpResponse(200, "a happy response body"));
        HttpResponse response = requestDirector.execute(null, new HttpGet("http://example.com"), null);

        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
    }

    @Test
    public void shouldPreferPendingResponses() throws Exception {
        Robolectric.addPendingHttpResponse(new TestHttpResponse(200, "a happy response body"));

        Robolectric.addHttpResponseRule(HttpGet.METHOD_NAME, "http://some.uri",
                new TestHttpResponse(200, "a cheery response body"));

        HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
    }

    @Test
    public void shouldReturnRequestsByRule() throws Exception {
        Robolectric.addHttpResponseRule(HttpGet.METHOD_NAME, "http://some.uri",
                new TestHttpResponse(200, "a cheery response body"));

        HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a cheery response body"));
    }

    @Test
    public void shouldReturnRequestsByRule_MatchingMethod() throws Exception {
        Robolectric.setDefaultHttpResponse(new TestHttpResponse(404, "no such page"));
        Robolectric.addHttpResponseRule(HttpPost.METHOD_NAME, "http://some.uri",
                new TestHttpResponse(200, "a cheery response body"));

        HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
    }

    @Test
    public void shouldReturnRequestsByRule_AnyMethod() throws Exception {
        Robolectric.addHttpResponseRule("http://some.uri", new TestHttpResponse(200, "a cheery response body"));

        HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
        assertNotNull(getResponse);
        assertThat(getResponse.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(getResponse.getEntity().getContent()), equalTo("a cheery response body"));

        HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
        assertNotNull(postResponse);
        assertThat(postResponse.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(postResponse.getEntity().getContent()), equalTo("a cheery response body"));
    }

    @Test
    public void shouldReturnRequestsByRule_WithTextResponse() throws Exception {
        Robolectric.addHttpResponseRule("http://some.uri", "a cheery response body");

        HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a cheery response body"));
    }

    @Test
    public void shouldReturnRequestsByRule_WithCustomRequestMatcher() throws Exception {
        Robolectric.setDefaultHttpResponse(new TestHttpResponse(404, "no such page"));

        Robolectric.addHttpResponseRule(new FakeHttpLayer.RequestMatcher() {
            @Override public boolean matches(HttpRequest request) {
                return request.getRequestLine().getUri().equals("http://matching.uri");
            }
        }, new TestHttpResponse(200, "a cheery response body"));

        HttpResponse response = requestDirector.execute(null, new HttpGet("http://matching.uri"), null);
        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a cheery response body"));

        response = requestDirector.execute(null, new HttpGet("http://non-matching.uri"), null);
        assertNotNull(response);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("no such page"));
    }

    @Test
    public void shouldGetHttpResponseFromExecuteSimpleApi() throws Exception {
        Robolectric.addPendingHttpResponse(200, "a happy response body");
        HttpResponse response = requestDirector.execute(null, new HttpGet("http://example.com"), null);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
    }

    @Test
    public void shouldHandleMultipleInvocations() throws Exception {
        Robolectric.addPendingHttpResponse(200, "a happy response body");
        Robolectric.addPendingHttpResponse(201, "another happy response body");

        HttpResponse response1 = requestDirector.execute(null, new HttpGet("http://example.com"), null);
        HttpResponse response2 = requestDirector.execute(null, new HttpGet("www.example.com"), null);

        assertThat(response1.getStatusLine().getStatusCode(), equalTo(200));
        assertThat(Strings.fromStream(response1.getEntity().getContent()), equalTo("a happy response body"));

        assertThat(response2.getStatusLine().getStatusCode(), equalTo(201));
        assertThat(Strings.fromStream(response2.getEntity().getContent()), equalTo("another happy response body"));
    }

    @Test
    public void shouldHandleMultipleInvocationsOfExecute() throws Exception {
        Robolectric.addPendingHttpResponse(200, "a happy response body");
        Robolectric.addPendingHttpResponse(201, "another happy response body");

        requestDirector.execute(null, new HttpGet("http://example.com"), null);
        requestDirector.execute(null, new HttpGet("www.example.com"), null);

        HttpUriRequest request1 = (HttpUriRequest) Robolectric.getSentHttpRequest(0);
        assertThat(request1.getMethod(), equalTo(HttpGet.METHOD_NAME));
        assertThat(request1.getURI(), equalTo(URI.create("http://example.com")));

        HttpUriRequest request2 = (HttpUriRequest) Robolectric.getSentHttpRequest(1);
        assertThat(request2.getMethod(), equalTo(HttpGet.METHOD_NAME));
        assertThat(request2.getURI(), equalTo(URI.create("www.example.com")));
    }

    @Test
    public void shouldRejectUnexpectedCallsToExecute() throws Exception {
        try {
            requestDirector.execute(null, new HttpGet("http://example.com"), null);
            fail();
        } catch (RuntimeException expected) {
            assertThat(expected.getMessage(), equalTo("Unexpected call to execute, no pending responses are available. See Robolectric.addPendingResponse()."));
        }
    }

    @Test
    public void shouldRecordExtendedRequestData() throws Exception {
        Robolectric.addPendingHttpResponse(200, "a happy response body");
        HttpGet httpGet = new HttpGet("http://example.com");
        requestDirector.execute(null, httpGet, null);

        assertSame(Robolectric.getSentHttpRequestInfo(0).getHttpRequest(), httpGet);
        ConnectionKeepAliveStrategy strategy = shadowOf((DefaultRequestDirector) Robolectric.getSentHttpRequestInfo(0).getRequestDirector()).getConnectionKeepAliveStrategy();
        assertSame(strategy, connectionKeepAliveStrategy);
    }
}


text:
package com.wesabe.api.accounts.presenters.tests;

import static com.wesabe.api.tests.util.CurrencyHelper.*;
import static com.wesabe.api.tests.util.MoneyHelper.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.util.Locale;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;

import com.wesabe.api.accounts.analytics.SumOfMoney;
import com.wesabe.api.accounts.presenters.MoneyPresenter;
import com.wesabe.api.accounts.presenters.SumOfMoneyPresenter;
import com.wesabe.xmlson.XmlsonObject;

@RunWith(Enclosed.class)
public class SumOfMoneyPresenterTest {
	public static class The_Representation_Of_A_Sum_Of_Money {
		private MoneyPresenter moneyPresenter;
		private SumOfMoney sum;
		private SumOfMoneyPresenter presenter;

		@Before
		public void setup() throws Exception {
			this.moneyPresenter = new MoneyPresenter();
			this.presenter = new SumOfMoneyPresenter(moneyPresenter);

			this.sum = new SumOfMoney(money("32.54", USD), 20);
		}

		@Test
		public void itItHasTheGivenName() throws Exception {
			final XmlsonObject representation = presenter.present("dingo", sum, Locale.JAPAN);

			assertThat(representation.getName(), is("dingo"));
		}

		@Test
		public void itItHasTheSumsCount() throws Exception {
			final XmlsonObject representation = presenter.present("dingo", sum, Locale.JAPAN);

			assertThat(representation.getInteger("count"), is(20));
		}

		@Test
		public void itItHasTheSumAsAFloat() throws Exception {
			final XmlsonObject representation = presenter.present("dingo", sum, Locale.JAPAN);

			assertThat(representation.getString("value"), is("32.54"));
		}

		@Test
		public void itItHasTheSumAsAMonetaryAmount() throws Exception {
			final XmlsonObject representation = presenter.present("dingo", sum, Locale.JAPAN);

			assertThat(representation.getString("display"), is("US$32.54"));
		}
	}
}


text:
layout: post
title: Reshape the Matrix
date: 2017-04-30
tags:
- Leetcode
categories:
- Matrix
author: Jason
---
**In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.**

```python
class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        if r * c != len(nums) * len(nums[0]):
            return nums
        #use () instead of [] to get a generator
        num_list = (x for y in nums for x in y)
        #put column number in a list first
        return [[num_list.next() for i in range(c)] for j in range(r)]
```


text:
@ParametersAreNonnullByDefault
package com.github.snd297.yp.hibernateequals.persistence;

import javax.annotation.ParametersAreNonnullByDefault;


text:
// github.com/RodneyShag

import java.io.*;
import java.util.*;

public class Solution {
    //  Time Complexity: O(n) using a HashMap
    // Space Complexity: O(n)
    static boolean isAnagram(String a, String b) {
        if (a == null || b == null || a.length() != b.length()) {
            return false;
        }
        a = a.toLowerCase();
        b = b.toLowerCase();
        HashMap<Character, Integer> map = new HashMap();

        /* Fill HashMap with 1st String */
        for (int i = 0; i < a.length(); i++) {
            char ch = a.charAt(i);
            map.merge(ch, 1, Integer::sum);
        }

        /* Compare 2nd String to 1st String's HashMap */
        for (int i = 0; i < b.length(); i++) {
            char ch = b.charAt(i);
            if (map.containsKey(ch) && map.get(ch) > 0) {
                map.put(ch, map.get(ch) - 1);
            } else {
                return false;
            }
        }
        return true;
    }

  public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String a = scan.next();
        String b = scan.next();
        scan.close();
        boolean ret = isAnagram(a, b);
        System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
    }
}


text:
package org.apache.sis.metadata.iso.spatial;

import java.util.List;
import java.util.Collection;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.opengis.metadata.spatial.GCP;
import org.opengis.metadata.spatial.Georectified;
import org.opengis.metadata.spatial.PixelOrientation;
import org.opengis.geometry.primitive.Point;
import org.opengis.util.InternationalString;
import org.apache.sis.internal.jaxb.Context;
import org.apache.sis.util.resources.Messages;
import org.apache.sis.xml.Namespaces;

/**
 * Grid whose cells are regularly spaced in a geographic or projected coordinate reference system.
 * Any cell in the grid can be geolocated given its grid coordinate and the grid origin, cell spacing,
 * and orientation indication of whether or not geographic.
 *
 *
Relationship between properties

 * Providing the {@linkplain #getCheckPointDescription() check point description} implies that
 * {@linkplain #isCheckPointAvailable() check point availability} is {@code true}. The setter
 * methods will ensure that this condition is not violated.
 *
 *
Limitations

 *

 *
Instances of this class are not synchronized for multi-threading.
 *       Synchronization, if needed, is caller's responsibility.

 *
Serialized objects of this class are not guaranteed to be compatible with future Apache SIS releases.
 *       Serialization support is appropriate for short term storage or RMI between applications running the
 *       same version of Apache SIS. For long term storage, use {@link org.apache.sis.xml.XML} instead.

 *

 *
 * @author  Martin Desruisseaux (IRD, Geomatys)
 * @author  Touraïvane (IRD)
 * @author  Cédric Briançon (Geomatys)
 * @since   0.3
 * @version 0.3
 * @module
 */
@XmlType(name = "MD_Georectified_Type", propOrder = {
    "checkPointAvailable",
    "checkPointDescription",
    "cornerPoints",
    "centerPoint",
    "pointInPixel",
    "transformationDimensionDescription",
    "transformationDimensionMapping",
    "checkPoints"
})
@XmlRootElement(name = "MD_Georectified")
@XmlSeeAlso(org.apache.sis.internal.jaxb.gmi.MI_Georectified.class)
public class DefaultGeorectified extends DefaultGridSpatialRepresentation implements Georectified {
    /**
     * Serial number for inter-operability with different versions.
     */
    private static final long serialVersionUID = -2924562334097446037L;

    /**
     * Mask for the {@code checkPointAvailable} boolean value.
     *
     * @see #booleans
     */
    private static final byte CHECK_POINT_MASK = TRANSFORMATION_MASK << 1;

    /**
     * Description of geographic position points used to test the accuracy of the
     * georeferenced grid data.
     */
    private InternationalString checkPointDescription;

    /**
     * Earth location in the coordinate system defined by the Spatial Reference System
     * and the grid coordinate of the cells at opposite ends of grid coverage along two
     * diagonals in the grid spatial dimensions. There are four corner points in a
     * georectified grid; at least two corner points along one diagonal are required.
     */
    private List<Point> cornerPoints;

    /**
     * Earth location in the coordinate system defined by the Spatial Reference System
     * and the grid coordinate of the cell halfway between opposite ends of the grid in the
     * spatial dimensions.
     */
    private Point centerPoint;

    /**
     * Point in a pixel corresponding to the Earth location of the pixel.
     */
    private PixelOrientation pointInPixel;

    /**
     * Description of the information about which grid dimensions are the spatial dimensions.
     */
    private InternationalString transformationDimensionDescription;

    /**
     * Information about which grid dimensions are the spatial dimensions.
     */
    private Collection<InternationalString> transformationDimensionMapping;

    /**
     * Geographic references used to validate georectification of the data.
     */
    private Collection<GCP> checkPoints;

    /**
     * Constructs an initially empty georectified object.
     */
    public DefaultGeorectified() {
    }

    /**
     * Constructs a new instance initialized with the values from the specified metadata object.
     * This is a shallow copy constructor, since the other metadata contained in the
     * given object are not recursively copied.
     *
     * @param object The metadata to copy values from, or {@code null} if none.
     *
     * @see #castOrCopy(Georectified)
     */
    public DefaultGeorectified(final Georectified object) {
        super(object);
        if (object != null) {
            checkPointDescription              = object.getCheckPointDescription();
            cornerPoints                       = copyList(object.getCornerPoints(), Point.class);
            centerPoint                        = object.getCenterPoint();
            pointInPixel                       = object.getPointInPixel();
            transformationDimensionDescription = object.getTransformationDimensionDescription();
            transformationDimensionMapping     = copyCollection(object.getTransformationDimensionMapping(), InternationalString.class);
            checkPoints                        = copyCollection(object.getCheckPoints(), GCP.class);

            // checkPointAvailability is required to be 'true' if there is a description.
            if (checkPointDescription != null || object.isCheckPointAvailable()) {
                booleans |= CHECK_POINT_MASK;
            }
        }
    }

    /**
     * Returns a SIS metadata implementation with the values of the given arbitrary implementation.
     * This method performs the first applicable action in the following choices:
     *
     *

     *
If the given object is {@code null}, then this method returns {@code null}.

     *
Otherwise if the given object is already an instance of
     *       {@code DefaultGeorectified}, then it is returned unchanged.

     *
Otherwise a new {@code DefaultGeorectified} instance is created using the
     *       {@linkplain #DefaultGeorectified(Georectified) copy constructor}
     *       and returned. Note that this is a shallow copy operation, since the other
     *       metadata contained in the given object are not recursively copied.

     *

     *
     * @param  object The object to get as a SIS implementation, or {@code null} if none.
     * @return A SIS implementation containing the values of the given object (may be the
     *         given object itself), or {@code null} if the argument was null.
     */
    public static DefaultGeorectified castOrCopy(final Georectified object) {
        if (object == null || object instanceof DefaultGeorectified) {
            return (DefaultGeorectified) object;
        }
        return new DefaultGeorectified(object);
    }

    /**
     * Returns an indication of whether or not geographic position points are available to test the
     * accuracy of the georeferenced grid data.
     *
     * @return Whether or not geographic position points are available to test accuracy.
     */
    @Override
    @XmlElement(name = "checkPointAvailability", required = true)
    public boolean isCheckPointAvailable() {
        return (booleans & CHECK_POINT_MASK) != 0;
    }

    /**
     * Sets an indication of whether or not geographic position points are available to test the
     * accuracy of the georeferenced grid data.
     *
     *
Effect on other properties

     * If and only if the given {@code newValue} is {@code false}, then this method automatically hides
     * the {@linkplain #setCheckPointDescription check point description} property. The description can
     * be shown again by reverting {@code checkPointAvailability} to {@code true}.
     *
     * @param newValue {@code true} if check points are available.
     */
    public void setCheckPointAvailable(final boolean newValue) {
        checkWritePermission();
        if (newValue) {
            booleans |= CHECK_POINT_MASK;
        } else {
            if (checkPointDescription != null && (booleans & CHECK_POINT_MASK) != 0) {
                Context.warningOccured(Context.current(), DefaultGeorectified.class, "setCheckPointAvailable",
                        Messages.class, Messages.Keys.PropertyHiddenBy_2, "checkPointDescription", "checkPointAvailability");
            }
            booleans &= ~CHECK_POINT_MASK;
        }
    }

    /**
     * Returns a description of geographic position points used to test the accuracy of the
     * georeferenced grid data. This value is non-null only if {@link #isCheckPointAvailable()}
     * returns {@code true}.
     *
     * @return Description of geographic position points used to test accuracy, or {@code null}.
     */
    @Override
    @XmlElement(name = "checkPointDescription")
    public InternationalString getCheckPointDescription() {
        return (booleans & CHECK_POINT_MASK) != 0 ? checkPointDescription : null;
    }

    /**
     * Sets the description of geographic position points used to test the accuracy of the
     * georeferenced grid data.
     *
     *
Effect on other properties

     * If and only if the given {@code newValue} is non-null, then this method automatically sets
     * the {@linkplain #setCheckPointAvailable check point availability} property to {@code true}.
     *
     * @param newValue The new check point description.
     */
    public void setCheckPointDescription(final InternationalString newValue) {
        checkWritePermission();
        checkPointDescription = newValue;
        if (newValue != null) {
            booleans |= CHECK_POINT_MASK;
        }
    }

    /**
     * Returns the Earth location in the coordinate system defined by the Spatial Reference System
     * and the grid coordinate of the cells at opposite ends of grid coverage along two diagonals.
     *
     * @return The corner points.
     */
    @Override
    @XmlElement(name = "cornerPoints", required = true)
    public List<Point> getCornerPoints() {
        return cornerPoints = nonNullList(cornerPoints, Point.class);
    }

    /**
     * Sets the corner points.
     *
     * The {@linkplain List#size() list size} should be 2 or 4.
     * The list should contain at least two corner points along one diagonal.
     * or may contains the 4 corner points of the georectified grid.
     *
     *
The first corner point shall correspond to the origin of the grid.

     *
     * @param newValues The new corner points.
     */
    public void setCornerPoints(final List<? extends Point> newValues) {
        cornerPoints = writeList(newValues, cornerPoints, Point.class);
    }

    /**
     * Returns the Earth location in the coordinate system defined by the Spatial Reference System
     * and the grid coordinate of the cell halfway between opposite ends of the grid in the
     * spatial dimensions.
     *
     * @return The center point, or {@code null}.
     */
    @Override
    @XmlElement(name = "centerPoint")
    public Point getCenterPoint() {
        return centerPoint;
    }

    /**
     * Sets the center point.
     *
     * @param newValue The new center point.
     */
    public void setCenterPoint(final Point newValue) {
        checkWritePermission();
        centerPoint = newValue;
    }

    /**
     * Returns the point in a pixel corresponding to the Earth location of the pixel.
     *
     * @return Earth location of the pixel, or {@code null}.
     */
    @Override
    @XmlElement(name = "pointInPixel", required = true)
    public PixelOrientation getPointInPixel() {
        return pointInPixel;
    }

    /**
     * Sets the point in a pixel corresponding to the Earth location of the pixel.
     *
     * @param newValue The new point in a pixel.
     */
    public void setPointInPixel(final PixelOrientation newValue) {
        checkWritePermission();
        pointInPixel = newValue;
    }

    /**
     * Returns a general description of the transformation.
     *
     * @return General description of the transformation, or {@code null}.
     */
    @Override
    @XmlElement(name = "transformationDimensionDescription")
    public InternationalString getTransformationDimensionDescription() {
        return transformationDimensionDescription;
    }

    /**
     * Sets a general description of the transformation.
     *
     * @param newValue The new general description.
     */
    public void setTransformationDimensionDescription(final InternationalString newValue) {
        checkWritePermission();
        transformationDimensionDescription = newValue;
    }

    /**
     * Returns information about which grid dimensions are the spatial dimensions.
     *
     * @return Information about which grid dimensions are the spatial dimensions, or {@code null}.
     */
    @Override
    @XmlElement(name = "transformationDimensionMapping")
    public Collection<InternationalString> getTransformationDimensionMapping() {
        return transformationDimensionMapping = nonNullCollection(transformationDimensionMapping, InternationalString.class);
    }

    /**
     * Sets information about which grid dimensions are the spatial dimensions.
     * The given list should contain at most 2 elements.
     *
     * @param newValues The new transformation mapping.
     */
    public void setTransformationDimensionMapping(final Collection<? extends InternationalString> newValues) {
        transformationDimensionMapping = writeCollection(newValues, transformationDimensionMapping, InternationalString.class);
    }

    /**
     * Returns the geographic references used to validate georectification of the data.
     *
     * @return Geographic references used to validate georectification.
     */
    @Override
    @XmlElement(name = "checkPoint", namespace = Namespaces.GMI)
    public Collection<GCP> getCheckPoints() {
        return checkPoints = nonNullCollection(checkPoints, GCP.class);
    }

    /**
     * Sets the geographic references used to validate georectification of the data.
     *
     * @param newValues The new check points values.
     */
    public void setCheckPoints(final Collection<? extends GCP> newValues) {
        checkPoints = writeCollection(newValues, checkPoints, GCP.class);
    }
}


text:
/*
 * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.IoT.Model
{
    ///
    /// Container for the parameters to the DeletePolicy operation.
    /// Deletes the specified policy.
    ///
    ///
    /// <para>
    /// A policy cannot be deleted if:
    /// </para>
    ///
    /// <para>
    ///  - it has non-default versions
    /// </para>
    ///
    /// <para>
    ///  - it is attached to any certificate
    /// </para>
    ///
    /// <para>
    /// To delete a policy:
    /// </para>
    ///
    /// <para>
    ///  - First delete all the non-default versions of the policy using the DeletePolicyVersion
    /// API.
    /// </para>
    ///
    /// <para>
    ///  - Detach it from any certificate using the DetachPrincipalPolicy API.
    /// </para>
    ///
    /// <para>
    /// When a policy is deleted, its default version is deleted with it.
    /// </para>
    ///
    public partial class DeletePolicyRequest : AmazonIoTRequest
    {
        private string _policyName;

        ///
        /// Gets and sets the property PolicyName.
        /// <para>
        /// The name of the policy to delete.
        /// </para>
        ///
        public string PolicyName
        {
            get { return this._policyName; }
            set { this._policyName = value; }
        }

        // Check to see if PolicyName property is set
        internal bool IsSetPolicyName()
        {
            return this._policyName != null;
        }

    }
}


text:
require File.expand_path('../test_helper.rb', __FILE__)

class MetricProxyTest < Test::Unit::TestCase
  def setup
    @scout = Scout::Account.new('account', 'username', 'password')
  end

  def test_metrics
    @scout.stub_get('clients/13431.xml', 'client.xml')
    server = Scout::Server.first(13431)
    @scout.stub_get('descriptors.xml?name=&ids=&plugin_ids=&server_ids=13431&group_ids=', 'descriptors.xml')
    metrics = server.metrics
    assert_equal 30, metrics.size
    assert metrics.first.is_a?(Scout::Metric)
  end

end


text:
<?php

return array(

    /**
     * Command Prefix
     *
     * Optional command to prefix the cron line with. Useful if you use tools such as run-one to ensure
     * long running cron tasks aren't duplicated.
     */
    'command_prefix' => '',

    /**
     * Log cron output to file
     *
     * Specifies if the generated cron command should log to a file in ./app/storage/logs or not.
     */
    'log_to_file' => true,

    /**
     * Custom Commands
     *
     * Sometimes you need to run custom cron commands which are not linked through artisan commands.
     * Since CronSync removes any lines containing the base_path(), you will need to define them below.
     *
     * IMPORTANT: This command needs base_path() in it, or it will be duplicated on repeated cronsync runs.
     *
     * Each entry is in the form: ['schedule', 'command'],
     */
    'custom_commands' => array(

        //['* * * * *', '/var/www/html/command'],

    ),
);


text:
title: ReactiveUI v8.6.3 released
category:
  - Release Notes
author: Glenn Watson
---

Release 8.6.3 of ReactiveUI is available!

## What's Changed

* feature: Stamp the code repository details in projects (#1720) @glennawatson
* feature: automatically draft release notes (#1721) @reactiveuibot


text:
Contribute
==========

So you've got an awesome idea to throw into Flyway. Great! Please keep the following in mind:

* **Use http://stackoverflow.com/questions/tagged/flyway for indirect Flyway questions that are not bugs.**
* **Contributions will not be accepted without tests or necessary documentation updates.**
* Make sure to read https://flywaydb.org/documentation/contribute/ first


text:
package org.apache.ignite.internal.processors.query.h2;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 */
public class GridSubqueryJoinOptimizerSelfTest extends GridCommonAbstractTest {
    /** */
    private static final Comparator<List<?>> ROW_COMPARATOR = new RowComparator();

    /** */
    private static final String CACHE_NAME = "cache";

    /** */
    private static IgniteEx ignite;

    /** */
    private static IgniteCache<Integer, Integer> cache;

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        ignite = (IgniteEx)startGridsMultiThreaded(2);
        cache = ignite.getOrCreateCache(new CacheConfiguration<>(CACHE_NAME));

        prepare();
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        super.afterTestsStopped();

        stopAllGrids();
    }

    /**
     * Very simple case: all tables have an alias, all columns referred
     * through tables' alias.
     */
    @Test
    public void testSelectExpression1() {
        String outerSqlTemplate = "select e.name, (%s) from emp e order by 1";
        String subSql = "select d.name from dep d where d.id = e.dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables has no aliases, but they are different.
     */
    @Test
    public void testSelectExpression2() {
        String outerSqlTemplate = "select name, (%s) dname from emp e order by 1";
        String subSql = "select name from dep where id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables are the same, inner table has an alias.
     */
    @Test
    public void testSelectExpression3() {
        String outerSqlTemplate = "select name, (%s) ename from emp order by 1";
        String subSql = "select name from emp e where e.id = emp.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables are the same, outer table has an alias.
     */
    @Test
    public void testSelectExpression4() {
        String outerSqlTemplate = "select name, (%s) ename from emp e order by 1";
        String subSql = "select name from emp where e.id = id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables are the same, the outer table has an alias, the inner has an additional filter.
     */
    @Test
    public void testSelectExpression5() {
        String outerSqlTemplate = "select name, (%s) ename from emp e order by 1";
        String subSql = "select name from emp where e.id = id and name = 'emp1'";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case like {@link #testSelectExpression1()}, but PK of the inner table is compound.
     */
    @Test
    public void testSelectExpressionCompoundPk() {
        String outerSqlTemplate = "select e.name, (%s) from emp e order by 1";
        String subSql = "select d.name from dep2 d where d.id = e.dep_id and d.id2 = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case where several subqueries used as several indeoendent columns.
     */
    @Test
    public void testSelectExpressionMultiple1() {
        String outerSqlTemplate = "select (%s), (%s), (%s) from emp e1 order by 2, 3";

        String subSql1 = "select 42";
        String subSql2 = "select e2.name from emp e2 where e2.id = e1.id";
        String subSql3 = "select d.name from dep d where d.id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql1, subSql2, subSql3);

        check(resSql, 2);
    }

    /**
     * Case where several subqueries used within a function.
     */
    @Test
    public void testSelectExpressionMultiple2() {
        String outerSqlTemplate = "select name, (%s) as lbl from emp e1 order by 1";
        String subSql = "(select 'prefix ' as pref_val) " +
            "|| (select name from dep2 dn where dn.id = dep_id and dn.id2 = dep_id)";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Simple case to ensure subqueries correctly pulled out from table list.
     */
    @Test
    public void testTableList1() {
        String outerSqlTemplate = "select e.name, d.name from emp e, (%s) d where e.dep_id = d.id order by 1, 2";
        String subSql = "select dd.name, dd.id from dep dd where dd.id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure subqueries correctly pulled out from table list, but tables the same.
     */
    @Test
    public void testTableList2() {
        String outerSqlTemplate = "select d1.name, d2.name from dep d1, (%s) d2 where d1.id = d2.id order by 1, 2";
        String subSql = "select d.name, d.id from dep d where d.id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * The same as {@link #testTableList2()}, but inner table has no alias.
     */
    @Test
    public void testTableList3() {
        String outerSqlTemplate = "select d1.name, d2.name from dep d1, (%s) d2 where d1.id = d2.id order by 1, 2";
        String subSql = "select name, id from dep where id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * The same as {@link #testTableList2()}, but both tables have no aliases.
     */
    @Test
    public void testTableList4() {
        String outerSqlTemplate = "select name from dep, (%s) d where dep.id = d.id order by 1";
        String subSql = "select id from dep where id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure subqueries correctly pulled out from table list, but inner table has no filters.
     */
    @Test
    public void testTableList5() {
        String outerSqlTemplate = "select name from dep, (%s) d where dep.id = (MOD(d.id, 7) + 1) order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure simple hierarchical subqueries properly pulled out from table list.
     */
    @Test
    public void testTableList6() {
        String outerSqlTemplate = "select name from (%s) d where d.id < 100 order by 1";
        String subSql = "select * from (select id, name from dep)";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared inner join with explicit join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList7() {
        String outerSqlTemplate = "select e.name from emp e inner join (%s) d on e.id = d.id where d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared inner join with implicit join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList8() {
        String outerSqlTemplate = "select e.name from emp e inner join (%s) d where e.id = d.id and d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared left join with explicit join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList9() {
        String outerSqlTemplate = "select e.name from emp e left join (%s) d on e.id = d.id where d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared left join without join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList10() {
        String outerSqlTemplate = "select e.name from emp e left join (%s) d where e.id = d.id and d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * The same as {@link #testTableList2()}, but both tables have no aliases.
     */
    @Test
    public void testTableListMultiple() {
        String outerSqlTemplate = "select name from dep, (%s) d, (%s) e where dep.id = d.id order by 1";
        String subSql1 = "select id from dep where id < 100";
        String subSql2 = "select id from emp where id < 100";

        String resSql = String.format(outerSqlTemplate, subSql1, subSql2);

        check(resSql, 1);
    }

    /**
     * Simple case where all tables have an alias, all columns referred
     * through tables' alias.
     */
    @Test
    public void testExistsClause1() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep d where d.id = e.dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has no alias.
     */
    @Test
    public void testExistsClause2() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep where id = e.dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but outer table has no alias.
     */
    @Test
    public void testExistsClause3() {
        String outerSqlTemplate = "select id, name from emp where exists (%s) order by 1";
        String subSql = "select 1 from dep d where d.id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but both tables have no aliases.
     */
    @Test
    public void testExistsClause4() {
        String outerSqlTemplate = "select id, name from emp where exists (%s) order by 1";
        String subSql = "select 1 from dep where id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but tables are the same.
     */
    @Test
    public void testExistsClause5() {
        String outerSqlTemplate = "select id, name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from emp where id = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has coumpound PK.
     */
    @Test
    public void testExistsClauseCompoundPk() {
        String outerSqlTemplate = "select id, name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 where id = e.id and id2 = 12";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case with multiple EXISTS clauses.
     */
    @Test
    public void testExistsClauseMultiple() {
        String outerSqlTemplate = "select id, name from dep2 d where exists (%s) and exists (%s) order by 1";
        String subSql1 = "select 1 from emp where d.id = dep_id and id = 3";
        String subSql2 = "select 1 from emp where d.id2 = dep_id and id = 3";

        String resSql = String.format(outerSqlTemplate, subSql1, subSql2);

        check(resSql, 1);
    }

    /**
     * Simple case where all tables have an alias, all columns referred
     * through tables' alias.
     */
    @Test
    public void testInClause1() {
        String outerSqlTemplate = "select e.id, e.name from emp e where e.dep_id in (%s) order by 1";
        String subSql = "select d.id from dep d";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has no alias.
     */
    @Test
    public void testInClause2() {
        String outerSqlTemplate = "select e.id, e.name from emp e where e.dep_id in (%s) order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but outer table has no alias.
     */
    @Test
    public void testInClause3() {
        String outerSqlTemplate = "select id, name from emp where dep_id in (%s) order by 1";
        String subSql = "select d.id from dep d";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but both tables have no aliases.
     */
    @Test
    public void testInClause4() {
        String outerSqlTemplate = "select id, name from emp where dep_id in (%s) order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but tables are the same.
     */
    @Test
    public void testInClause5() {
        String outerSqlTemplate = "select id, name from emp e where id in (%s) order by 1";
        String subSql = "select id from emp";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure that array on the left of the IN clause is handled properly.
     */
    @Test
    public void testInClause6() {
        String outerSqlTemplate = "select id, name from emp e where (id, name) in (%s) order by 1";
        String subSql = "select (id, name) from emp";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure that expression on the left of the IN clause is handled properly.
     */
    @Test
    public void testInClause7() {
        String outerSqlTemplate = "select id, name from emp e where (2 + abs(id)) in (%s) order by 1";
        String subSql = "select id from emp";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has coumpound PK.
     */
    @Test
    public void testInClauseCompoundPk() {
        String outerSqlTemplate = "select id, name from emp e where id in (%s) order by 1";
        String subSql = "select id from dep2 where id2 = 12";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case with multiple IN clauses.
     */
    @Test
    public void testInClauseMultiple() {
        String outerSqlTemplate = "select id, name from dep2 d where id in (%s) and id2 in (%s) order by 1";
        String subSql = "select id from emp";

        String resSql = String.format(outerSqlTemplate, subSql, subSql);

        check(resSql, 1);
    }

    /**
     * Test should verify cases with UNION ALL.
     */
    @Test
    public void testOptimizationAppliedToUnion() {
        String sql = "" +
            "select emp.name, d.id from emp, (select * from dep) d " +
            "union all " +
            "select (select name from dep2 where id = 1 and id2 = 1) as dep_name, d.id " +
            "from dep d where exists (select 1 from dep where id = d.id)";

        check(sql, 1);
    }

    /**
     * Test should verify all cases where subquery should not be rewrited.
     */
    @Test
    public void testOptimizationShouldNotBeApplied1() {
        String sql = "" +
            // follow should not be rewrited beacuse of aggregates
            "select (select max(id) from emp) f1," +
            "       (select sum(id) from emp) f2," +
            "       (select distinct id from emp where id = 1) f3," +
            "       (select distinct(id) from emp where id = 1) f4," +
            "       (select id from emp where id = 1 group by id) f5," +
            "       (select id from emp where id = 1 group by 1) f6," +
            "       (select id from emp limit 1) f7," +
            "       (select id from emp where id = 2 offset 2) f8," +
            // and this one because dep2 has compound pk (id, id2),
            // so predicate over 'id' could not guarantee uniqueness
            "       (select id from dep2 where id = 2) f9" +
            " from dep";

        check(sql, 10);
    }

    /**
     * Test should verify that optimization won't be applied when columns of the compound index
     * connect by OR.
     */
    @Test
    public void testOptimizationShouldNotBeApplied2() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 d2 where d2.id = e.id or d2.id2 = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Case to ensure subquery with join won't be pulled out from table list.
     */
    @Test
    public void testOptimizationShouldNotBeApplied3() {
        String outerSqlTemplate = "select e.name from emp e, (%s) d order by 1 limit 10";
        String subSql = "select d1.id, d2.name from dep d1, dep d2";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2 + 1/* explain reports one additional SELECT in comments */);
    }

    /**
     * Case to ensure subquery with join won't be pulled out from EXISTS.
     */
    @Test
    public void testOptimizationShouldNotBeApplied4() {
        String outerSqlTemplate = "select e.name from emp e where exists (%s) order by 1 limit 10";
        String subSql = "select 1 from dep d1, dep d2 where d1.id = d2.id and d1.id = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Test should verify that optimization won't be applied when columns of the compound index
     * connect by OR (ver 2).
     */
    @Test
    public void testOptimizationShouldNotBeApplied5() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 d2 where 1 = 1 and (d2.id = e.id or d2.id2 = e.id)";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Test should verify that optimization won't be applied when columns of the compound index
     * connect by OR (ver 3).
     */
    @Test
    public void testOptimizationShouldNotBeApplied6() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 d2 where 1 = 1 and (d2.id = e.id and (d2.id2 = 1 or d2.id2 = 2))";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * @param sql Sql.
     * @param expSelectClauses Expected select clauses.
     */
    private void check(String sql, int expSelectClauses) {
        optimizationEnabled(false);

        List<List<?>> exp = cache.query(new SqlFieldsQuery(sql)).getAll();

        exp.sort(ROW_COMPARATOR);

        optimizationEnabled(true);

        List<List<?>> act = cache.query(new SqlFieldsQuery(sql).setEnforceJoinOrder(true)).getAll();

        act.sort(ROW_COMPARATOR);

        Assert.assertEquals("Result set mismatch", exp, act);

        String plan = cache.query(new SqlFieldsQuery("explain " + sql)).getAll().get(0).get(0).toString();

        System.out.println(plan);

        int actCnt = countEntries(plan, "SELECT");

        Assert.assertEquals(String.format("SELECT-clause count mismatch: exp=%d, act=%d, plan=[%s]",
            expSelectClauses, actCnt, plan), expSelectClauses, actCnt);
    }

    /**
     * Creates all neccessary tables and inserts data.
     */
    private void prepare() {
        Random rnd = new Random();

        cache.query(new SqlFieldsQuery("CREATE TABLE dep (id LONG PRIMARY KEY, name VARCHAR, dep_name VARCHAR)"));
        cache.query(new SqlFieldsQuery("CREATE TABLE dep2 (id LONG, id2 LONG, name VARCHAR, PRIMARY KEY(id, id2))"));
        cache.query(new SqlFieldsQuery("CREATE TABLE emp (id LONG PRIMARY KEY, name VARCHAR, dep_id LONG)"));

        for (int i = 0; i < 20; i++) {
            cache.query(new SqlFieldsQuery("insert into dep (id, name, dep_name) values(?, ?, ?)")
                .setArgs(i, "dep" + i, "dep" + i));

            cache.query(new SqlFieldsQuery("insert into dep2 (id, id2, name) values(?, ?, ?)")
                .setArgs(i, i, "dep" + i));

            cache.query(new SqlFieldsQuery("insert into emp (id, name, dep_id) values(?, ?, ?)")
                .setArgs(i, "emp" + i, i < 10 ? rnd.nextInt(10) : null));
        }
    }

    /**
     * Count of entries of substring in string.
     *
     * @param where Where to search.
     * @param what What to search.
     * @return Count of entries or -1 if non is found.
     */
    private int countEntries(String where, String what) {
        return where.split(what).length - 1;
    }

    /** */
    private void optimizationEnabled(boolean enabled) {
        System.setProperty(IgniteSystemProperties.IGNITE_ENABLE_SUBQUERY_REWRITE_OPTIMIZATION, String.valueOf(enabled));

        GridTestUtils.setFieldValue(GridSubqueryJoinOptimizer.class, "optimizationEnabled", null);
    }

    /** */
    @SuppressWarnings("ComparatorNotSerializable")
    private static class RowComparator implements Comparator<List<?>> {
        /** {@inheritDoc} */
        @Override public int compare(List<?> o1, List<?> o2) {
            if (o1 == null && o2 == null)
                return 0;

            if (o1 == null)
                return 1;

            if (o2 == null)
                return -1;

            Iterator<?> i1 = o1.iterator(), i2 = o2.iterator();
            while (i1.hasNext() && i2.hasNext()) {
                Object e1 = i1.next(), e2 = i2.next();

                if (e1 == null && e2 == null)
                    continue;

                if (e1 == null)
                    return 1;

                if (e2 == null)
                    return -1;

                checkComparable(e1);
                checkComparable(e2);

                int res = ((Comparable<Object>)e1).compareTo(e2);
                if (res != 0)
                    return res;
            }

            return Integer.signum(o1.size() - o2.size());
        }

        /** */
        private void checkComparable(Object o) {
            if (!(o instanceof Comparable))
                throw new RuntimeException(o.getClass().getSimpleName() + " is not comparable");
        }
    }
}


text:
import jwt from 'jsonwebtoken'
import config from '../environment'
import sha256 from 'sha256'
import userModel from '../models/user'

const SERVICE_MESSAGES = {
    NO_TOKEN_PROVIDED: 'No auth token provided',
    FAILED_AUTHENTICATE_TOKEN: 'Failed authenticate token',
    WRONG_CREDENTIALS: 'Wrong username or password'
};

function verifyToken(req, res, next) {
    let token = req.headers['x-token'];

    if(!token) {
        return res.status(401)
            .send(_response(false, SERVICE_MESSAGES.NO_TOKEN_PROVIDED));
    }

    jwt.verify(token, config.app.secret, (err, decoded) => {
        if(err) {
            return res.status(401)
                .send(_response(false, SERVICE_MESSAGES.FAILED_AUTHENTICATE_TOKEN));
        }
        next();
    });
}

function authenticate(req, res) {
    let user = {
        username: req.body.username,
        password: req.body.password
    };

    return userModel.findOne({login: user.username}).exec() // TODO move
        .then((dbUser) => {
            if(!dbUser) {
                throw new Error(SERVICE_MESSAGES.WRONG_CREDENTIALS);
            }

            let password = sha256(user.password);
            if(password !== dbUser.password) {
                throw new Error(SERVICE_MESSAGES.WRONG_CREDENTIALS);
            }

            let token = jwt.sign(user, config.app.secret, {expiresIn: "1h"});
            let response = _response(true, "");
            Object.assign(response, {token: token});

            return res.status(200)
                .send(response);
        })
        .catch((err) => {
            return res.status(401)
                .send(_response(false, err.message));
        });
}

function _response(success, message) {
    return {
        success: success,
        message: message
    };
}

export default  {
    verifyToken,
    authenticate
};


text:
#ifndef SVGFESpecularLightingElement_h
#define SVGFESpecularLightingElement_h

#include "core/SVGNames.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGAnimatedNumberOptionalNumber.h"
#include "core/svg/SVGFELightElement.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
#include "platform/graphics/filters/FESpecularLighting.h"
#include "platform/heap/Handle.h"

namespace blink {

class SVGFESpecularLightingElement final : public SVGFilterPrimitiveStandardAttributes {
    DEFINE_WRAPPERTYPEINFO();
public:
    DECLARE_NODE_FACTORY(SVGFESpecularLightingElement);
    void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);

    SVGAnimatedNumber* specularConstant() { return m_specularConstant.get(); }
    SVGAnimatedNumber* specularExponent() { return m_specularExponent.get(); }
    SVGAnimatedNumber* surfaceScale() { return m_surfaceScale.get(); }
    SVGAnimatedNumber* kernelUnitLengthX() { return m_kernelUnitLength->firstNumber(); }
    SVGAnimatedNumber* kernelUnitLengthY() { return m_kernelUnitLength->secondNumber(); }
    SVGAnimatedString* in1() { return m_in1.get(); }

    DECLARE_VIRTUAL_TRACE();

private:
    explicit SVGFESpecularLightingElement(Document&);

    bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&) override;
    void svgAttributeChanged(const QualifiedName&) override;
    FilterEffect* build(SVGFilterBuilder*, Filter*) override;

    Member<SVGAnimatedNumber> m_specularConstant;
    Member<SVGAnimatedNumber> m_specularExponent;
    Member<SVGAnimatedNumber> m_surfaceScale;
    Member<SVGAnimatedNumberOptionalNumber> m_kernelUnitLength;
    Member<SVGAnimatedString> m_in1;
};

} // namespace blink

#endif // SVGFESpecularLightingElement_h


text:
package de.danoeh.antennapod.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import org.apache.commons.lang3.StringUtils;

import de.danoeh.antennapod.core.BuildConfig;
import de.danoeh.antennapod.core.storage.DBTasks;
import de.danoeh.antennapod.core.storage.DownloadRequester;
import de.danoeh.antennapod.core.util.NetworkUtils;

public class ConnectivityActionReceiver extends BroadcastReceiver {
	private static final String TAG = "ConnectivityActionReceiver";

	@Override
	public void onReceive(final Context context, Intent intent) {
		if (StringUtils.equals(intent.getAction(), ConnectivityManager.CONNECTIVITY_ACTION)) {
			if (BuildConfig.DEBUG)
				Log.d(TAG, "Received intent");

			if (NetworkUtils.autodownloadNetworkAvailable(context)) {
				if (BuildConfig.DEBUG)
					Log.d(TAG,
							"auto-dl network available, starting auto-download");
					DBTasks.autodownloadUndownloadedItems(context);
			} else { // if new network is Wi-Fi, finish ongoing downloads,
						// otherwise cancel all downloads
				ConnectivityManager cm = (ConnectivityManager) context
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo ni = cm.getActiveNetworkInfo();
				if (ni == null || ni.getType() != ConnectivityManager.TYPE_WIFI) {
					if (BuildConfig.DEBUG)
						Log.i(TAG,
								"Device is no longer connected to Wi-Fi. Cancelling ongoing downloads");
					DownloadRequester.getInstance().cancelAllDownloads(context);
				}

			}
		}
	}
}


text:
namespace mojo {
namespace shell {

ChildProcessHost::ChildProcessHost(Context* context, ChildProcess::Type type)
    : process_launch_task_runner_(context->task_runners()->blocking_pool()),
      type_(type),
      child_process_handle_(base::kNullProcessHandle) {
}

ChildProcessHost::~ChildProcessHost() {
  if (child_process_handle_ != base::kNullProcessHandle) {
    LOG(WARNING) << "Destroying ChildProcessHost with unjoined child";
    base::CloseProcessHandle(child_process_handle_);
    child_process_handle_ = base::kNullProcessHandle;
  }
}

void ChildProcessHost::Start(DidStartCallback callback) {
  DCHECK_EQ(child_process_handle_, base::kNullProcessHandle);
  CHECK(base::PostTaskAndReplyWithResult(
      process_launch_task_runner_,
      FROM_HERE,
      base::Bind(&ChildProcessHost::DoLaunch, base::Unretained(this)),
      callback));
}

int ChildProcessHost::Join() {
  DCHECK_NE(child_process_handle_, base::kNullProcessHandle);
  int rv = -1;
  LOG_IF(ERROR, !base::WaitForExitCode(child_process_handle_, &rv))
      << "Failed to wait for child process";
  base::CloseProcessHandle(child_process_handle_);
  child_process_handle_ = base::kNullProcessHandle;
  return rv;
}

bool ChildProcessHost::DoLaunch() {
  static const char* kForwardSwitches[] = {
    switches::kTraceToConsole,
    switches::kV,
    switches::kVModule,
  };

  const CommandLine* parent_command_line = CommandLine::ForCurrentProcess();
  CommandLine child_command_line(parent_command_line->GetProgram());
  child_command_line.CopySwitchesFrom(*parent_command_line, kForwardSwitches,
                                      arraysize(kForwardSwitches));
  child_command_line.AppendSwitchASCII(
      switches::kChildProcessType, base::IntToString(static_cast<int>(type_)));

  embedder::PlatformChannelPair platform_channel_pair;
  embedder::HandlePassingInformation handle_passing_info;
  platform_channel_pair.PrepareToPassClientHandleToChildProcess(
      &child_command_line, &handle_passing_info);

  base::LaunchOptions options;
#if defined(OS_WIN)
  options.start_hidden = true;
  options.handles_to_inherit = &handle_passing_info;
#elif defined(OS_POSIX)
  options.fds_to_remap = &handle_passing_info;
#endif

  if (!base::LaunchProcess(child_command_line, options, &child_process_handle_))
    return false;

  platform_channel_pair.ChildProcessLaunched();
  platform_channel_ = platform_channel_pair.PassServerHandle();
  CHECK(platform_channel_.is_valid());
  return true;
}

}  // namespace shell
}  // namespace mojo


text:
export * from './email';
export * from './github';
export * from './pixiv';
export * from './menu';


text:
package leetCode;

/*
 * Link : https://leetcode.com/problems/pascals-triangle-ii/
 */

public class _125ValidPalindrome {
	public static boolean isPalindrome(String s) {
		s=s.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
		StringBuilder sb=new StringBuilder(s);
		String reverseString=sb.reverse().toString();
		if(s.contentEquals(reverseString))
			return true;
		else
			return false;
	}
	public static void main(String[] args) {
		System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
	}
}