text:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using AntlrGrammarEditor.Processors.ParserCompilers;
using AntlrGrammarEditor.Processors.ParserGeneration;
using AntlrGrammarEditor.Sources;
using AntlrGrammarEditor.WorkflowState;
using static AntlrGrammarEditor.Helpers;

namespace AntlrGrammarEditor.Processors.TextParsing
{
    public class TextParser : StageProcessor
    {
        private static readonly Regex TextParserErrorMessageRegex =
            new ($@"line (?<{LineMark}>\d+):(?<{ColumnMark}>\d+) (?<{MessageMark}>.+)", RegexOptions.Compiled);

        private readonly TextParsedState _result;

        public string? TextFileName { get; }

        public bool OnlyTokenize { get; set; }

        public EventHandler<(TextParsedOutput, object)>? TextParsedOutputEvent { get; set; }

        public string? RuntimeLibrary { get; set; }

        public TextParser(ParserCompiledState state, string? textFileName, string? root,
            PredictionMode? predictionMode)
        {
            var grammarCheckedState = state.ParserGeneratedState.GrammarCheckedState;
            TextFileName = textFileName;
            var definedRoot = root ?? grammarCheckedState.Root ??
                grammarCheckedState.GrammarInfos.FirstOrDefault(info => info.Type.IsParser())?.Rules[0] ??
                "";
            var definedPredictionMode = predictionMode ?? grammarCheckedState.PredictionMode ?? PredictionMode.LL;
            _result = new TextParsedState(state,
                definedRoot,
                definedPredictionMode,
                textFileName != null ? new Source(textFileName, File.ReadAllText(textFileName)) : null);
        }

        public TextParsedState Parse(CancellationToken cancellationToken = default)
        {
            if (_result.TextSource == null)
            {
                _result.AddDiagnosis(new TextParsingDiagnosis("File to parse is not specified"));
                return _result;
            }

            var parserCompiledState = _result.ParserCompiledState;
            Processor? processor = null;
            try
            {
                Grammar grammar = parserCompiledState.ParserGeneratedState.GrammarCheckedState.InputState.Grammar;
                Runtime runtime = parserCompiledState.ParserGeneratedState.Runtime;

                var runtimeInfo = runtime.GetRuntimeInfo();
                string runtimeDir = Path.Combine(ParserCompiler.RuntimesDirName, runtime.ToString());
                string runtimeLibraryPath = RuntimeLibrary ?? Path.Combine(runtimeDir, runtimeInfo.RuntimeLibrary);

                string workingDirectory =
                    Path.Combine(ParserGenerator.HelperDirectoryName, grammar.Name, runtime.ToString());

                string args = runtime switch
                {
                    Runtime.CSharp => PrepareCSharpArgs(grammar),
                    Runtime.Java => PrepareJavaArgs(runtimeLibraryPath),
                    Runtime.Go => "",
                    _ => runtimeInfo.MainFile
                };

                args +=
                    $" \"{TextFileName}\" {_result.Root} {OnlyTokenize.ToString().ToLowerInvariant()} {_result.PredictionMode.ToString().ToLowerInvariant()}";

                string runtimeToolName;
                if (runtimeInfo.IsNativeBinary)
                {
                    string fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                        ? Path.ChangeExtension(runtimeInfo.MainFile, ".exe")
                        : Path.GetFileNameWithoutExtension(runtimeInfo.MainFile);

                    runtimeToolName = Path.Combine(workingDirectory, fileName);
                }
                else
                {
                    runtimeToolName = runtimeInfo.RuntimeToolName;
                }

                _result.Command = runtimeToolName + " " + args;
                processor = new Processor(runtimeToolName, args, workingDirectory);
                processor.CancellationToken = cancellationToken;
                processor.ErrorDataReceived += TextParsing_ErrorDataReceived;
                processor.OutputDataReceived += TextParsing_OutputDataReceived;
                foreach (var environmentVariable in runtimeInfo.TextParserEnvironmentVariables)
                    processor.EnvironmentVariables.Add(environmentVariable.Key, environmentVariable.Value);
                processor.Start();

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                AddDiagnosis(new TextParsingDiagnosis(ex));
            }
            finally
            {
                processor?.Dispose();
            }

            return _result;
        }

        private string PrepareCSharpArgs(Grammar grammar)
        {
            return $"\"{Path.Combine("bin", "netcoreapp3.1", grammar.Name + ".dll")}\"";
        }

        private string PrepareJavaArgs(string runtimeLibraryPath)
        {
            string relativeRuntimeLibraryPath = "\"" + Path.Combine("..", "..", "..", runtimeLibraryPath) + "\"";
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                relativeRuntimeLibraryPath += ";.";
            }
            else
            {
                relativeRuntimeLibraryPath = ".:" + relativeRuntimeLibraryPath;
            }

            return $@"-cp {relativeRuntimeLibraryPath} Main";
        }

        private void TextParsing_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!e.IsIgnoredMessage(_result.ParserCompiledState.ParserGeneratedState.Runtime))
            {
                Diagnosis diagnosis;
                try
                {
                    var match = TextParserErrorMessageRegex.Match(e.Data);
                    if (match.Success)
                    {
                        var groups = match.Groups;
                        int beginLine = int.Parse(groups[LineMark].Value);
                        int beginColumn = int.Parse(groups[ColumnMark].Value) + LineColumnTextSpan.StartColumn;
                        var message = groups[MessageMark].Value;
                        var textSource = _result.TextSource!;
                        int start = textSource.LineColumnToPosition(beginLine, beginColumn);
                        var textSpan = AntlrHelper.ExtractTextSpanFromErrorMessage(start, message, textSource);
                        diagnosis = new TextParsingDiagnosis(textSpan, message);
                    }
                    else
                    {
                        diagnosis = new TextParsingDiagnosis(e.Data);
                    }
                }
                catch
                {
                    diagnosis = new TextParsingDiagnosis(e.Data);
                }

                AddDiagnosis(diagnosis);
            }
        }

        private void TextParsing_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!e.IsIgnoredMessage(_result.ParserCompiledState.ParserGeneratedState.Runtime))
            {
                var parts = e.Data.Split(new [] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);

                if (Enum.TryParse(parts[0], out TextParsedOutput outputState))
                {
                    var data = parts[1];
                    switch (outputState)
                    {
                        case TextParsedOutput.LexerTime:
                            _result.LexerTime = TimeSpan.Parse(data);
                            TextParsedOutputEvent?.Invoke(this, (TextParsedOutput.LexerTime, _result.LexerTime));
                            break;
                        case TextParsedOutput.ParserTime:
                            _result.ParserTime = TimeSpan.Parse(data);
                            TextParsedOutputEvent?.Invoke(this, (TextParsedOutput.ParserTime, _result.ParserTime));
                            break;
                        case TextParsedOutput.Tokens:
                            _result.Tokens = data;
                            TextParsedOutputEvent?.Invoke(this, (TextParsedOutput.Tokens, _result.Tokens));
                            break;
                        case TextParsedOutput.Tree:
                            _result.Tree = data.Replace("\\n", "\n");
                            TextParsedOutputEvent?.Invoke(this, (TextParsedOutput.Tree, _result.Tree));
                            break;
                    }
                }
                else
                {
                    AddDiagnosis(new TextParsingDiagnosis(e.Data));
                }
            }
        }

        private void AddDiagnosis(Diagnosis diagnosis)
        {
            DiagnosisEvent?.Invoke(this, diagnosis);
            _result.AddDiagnosis(diagnosis);
        }
    }
}


text:
package org.apache.beam.runners.dataflow.worker;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.beam.runners.dataflow.worker.util.common.worker.ShuffleEntry;
import org.apache.beam.sdk.util.common.Reiterator;
import org.apache.beam.sdk.values.KV;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests of TestShuffleReader. */
@RunWith(JUnit4.class)
public class TestShuffleReaderTest {
  static final String START_KEY = "ddd";
  static final String END_KEY = "mmm";

  static final List<KV<String, KV<String, String>>> NO_ENTRIES = Collections.emptyList();

  static final List<KV<String, KV<String, String>>> IN_RANGE_ENTRIES =
      Arrays.<KV<String, KV<String, String>>>asList(
          KV.of("ddd", KV.of("1", "in 1")),
          KV.of("ddd", KV.of("2", "in 1")),
          KV.of("ddd", KV.of("3", "in 1")),
          KV.of("dddd", KV.of("1", "in 2")),
          KV.of("dddd", KV.of("2", "in 2")),
          KV.of("de", KV.of("1", "in 3")),
          KV.of("ee", KV.of("1", "in 4")),
          KV.of("ee", KV.of("2", "in 4")),
          KV.of("ee", KV.of("3", "in 4")),
          KV.of("ee", KV.of("4", "in 4")),
          KV.of("mm", KV.of("1", "in 5")));
  static final List<KV<String, KV<String, String>>> BEFORE_RANGE_ENTRIES =
      Arrays.<KV<String, KV<String, String>>>asList(
          KV.of("", KV.of("1", "out 1")), KV.of("dd", KV.of("1", "out 2")));
  static final List<KV<String, KV<String, String>>> AFTER_RANGE_ENTRIES =
      Arrays.<KV<String, KV<String, String>>>asList(
          KV.of("mmm", KV.of("1", "out 3")),
          KV.of("mmm", KV.of("2", "out 3")),
          KV.of("mmmm", KV.of("1", "out 4")),
          KV.of("mn", KV.of("1", "out 5")),
          KV.of("zzz", KV.of("1", "out 6")));
  static final List<KV<String, KV<String, String>>> OUT_OF_RANGE_ENTRIES = new ArrayList<>();

  static {
    OUT_OF_RANGE_ENTRIES.addAll(BEFORE_RANGE_ENTRIES);
    OUT_OF_RANGE_ENTRIES.addAll(AFTER_RANGE_ENTRIES);
  }

  static final List<KV<String, KV<String, String>>> ALL_ENTRIES = new ArrayList<>();

  static {
    ALL_ENTRIES.addAll(BEFORE_RANGE_ENTRIES);
    ALL_ENTRIES.addAll(IN_RANGE_ENTRIES);
    ALL_ENTRIES.addAll(AFTER_RANGE_ENTRIES);
  }

  void runTest(
      List<KV<String, KV<String, String>>> expected,
      List<KV<String, KV<String, String>>> outOfRange,
      String startKey,
      String endKey) {
    TestShuffleReader shuffleReader = new TestShuffleReader();
    List<KV<String, KV<String, String>>> expectedCopy = new ArrayList<>(expected);
    expectedCopy.addAll(outOfRange);
    Collections.shuffle(expectedCopy);
    for (KV<String, KV<String, String>> entry : expectedCopy) {
      shuffleReader.addEntry(
          entry.getKey(),
          entry.getValue().getKey() /* secondary key */,
          entry.getValue().getValue());
    }
    testIteratorReturnsValues(shuffleReader.read(startKey, endKey), expected);
    testIteratorIntermediateCopiesReturnTails(shuffleReader.read(startKey, endKey), expected);
  }

  private void testIteratorReturnsValues(
      Reiterator<ShuffleEntry> iter, List<KV<String, KV<String, String>>> expected) {
    List<KV<String, KV<String, String>>> actual = readShuffleEntries(iter);
    try {
      iter.next();
      fail("should have failed");
    } catch (NoSuchElementException exn) {
      // Success.
    }
    assertEquals(expected, actual);
  }

  private List<KV<String, KV<String, String>>> readShuffleEntries(Reiterator<ShuffleEntry> iter) {
    List<KV<String, KV<String, String>>> actual = new ArrayList<>();
    while (iter.hasNext()) {
      ShuffleEntry entry = iter.next();
      actual.add(
          KV.of(
              (entry.getKey().toStringUtf8()),
              KV.of((entry.getSecondaryKey().toStringUtf8()), (entry.getValue().toStringUtf8()))));
    }
    return actual;
  }

  private void testIteratorIntermediateCopiesReturnTails(
      Reiterator<ShuffleEntry> iter, List<KV<String, KV<String, String>>> expected) {
    List<Reiterator<ShuffleEntry>> iteratorCopies = new ArrayList<>();
    for (; iter.hasNext(); iter.next()) {
      iteratorCopies.add(iter.copy());
    }
    for (int i = 0; i < expected.size(); ++i) {
      assertEquals(
          "" + i, expected.subList(i, expected.size()), readShuffleEntries(iteratorCopies.get(i)));
    }
  }

  @Test
  public void testEmpty() {
    runTest(NO_ENTRIES, NO_ENTRIES, null, null);
  }

  @Test
  public void testEmptyWithRange() {
    runTest(NO_ENTRIES, NO_ENTRIES, START_KEY, END_KEY);
  }

  @Test
  public void testNonEmpty() {
    runTest(ALL_ENTRIES, NO_ENTRIES, null, null);
  }

  @Test
  public void testNonEmptyWithAllInRange() {
    runTest(IN_RANGE_ENTRIES, NO_ENTRIES, START_KEY, END_KEY);
  }

  @Test
  public void testNonEmptyWithSomeOutOfRange() {
    runTest(IN_RANGE_ENTRIES, OUT_OF_RANGE_ENTRIES, START_KEY, END_KEY);
  }

  @Test
  public void testNonEmptyWithAllOutOfRange() {
    runTest(NO_ENTRIES, OUT_OF_RANGE_ENTRIES, START_KEY, END_KEY);
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using StructureMap.Pipeline;

namespace StructureMap
{
    public interface IBuildSession
    {
        object BuildNewInSession(Type pluginType, Instance instance);
        object BuildNewInOriginalContext(Type pluginType, Instance instance);
        object ResolveFromLifecycle(Type pluginType, Instance instance);
        Policies Policies { get; }
        object CreateInstance(Type pluginType, string name);

        void Push(Instance instance);
        void Pop();
    }
}


text:
package org.kairosdb.core.datastore;

import com.google.common.collect.ImmutableSortedMap;
import org.junit.Test;
import org.kairosdb.core.DataPoint;
import org.kairosdb.core.DataPointListener;
import org.kairosdb.core.TestDataPointFactory;
import org.kairosdb.core.aggregator.AggregatorFactory;
import org.kairosdb.core.aggregator.TestAggregatorFactory;
import org.kairosdb.core.datapoints.*;
import org.kairosdb.core.exception.DatastoreException;
import org.kairosdb.core.exception.KairosDBException;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class KairosDatastoreTest
{
	private AggregatorFactory aggFactory;

	public KairosDatastoreTest() throws KairosDBException
	{
		aggFactory = new TestAggregatorFactory();
	}

	@Test(expected = NullPointerException.class)
	public void test_query_nullMetricInvalid() throws KairosDBException
	{
		TestDatastore testds = new TestDatastore();
		KairosDatastore datastore = new KairosDatastore(testds, new QueryQueuingManager(1, "hostname"),
				Collections.<DataPointListener>emptyList(), "hostname", new TestDataPointFactory());

		datastore.createQuery(null);
	}

	@Test
	public void test_query_sumAggregator() throws KairosDBException
	{
		TestDatastore testds = new TestDatastore();
		KairosDatastore datastore = new KairosDatastore(testds, new QueryQueuingManager(1, "hostname"),
				Collections.<DataPointListener>emptyList(), "hostname", new TestDataPointFactory());
		QueryMetric metric = new QueryMetric(1L, 1, "metric1");
		metric.addAggregator(aggFactory.createAggregator("sum"));

		DatastoreQuery dq = datastore.createQuery(metric);
		List<DataPointGroup> results = dq.execute();

		DataPointGroup group = results.get(0);

		DataPoint dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(72L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(32L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(3L));
		assertThat(dataPoint.getLongValue(), equalTo(32L));

		dq.close();
	}

	@Test
	public void test_query_noAggregator() throws KairosDBException
	{
		TestDatastore testds = new TestDatastore();
		KairosDatastore datastore = new KairosDatastore(testds, new QueryQueuingManager(1, "hostname"),
				Collections.<DataPointListener>emptyList(), "hostname", new TestDataPointFactory());
		QueryMetric metric = new QueryMetric(1L, 1, "metric1");

		DatastoreQuery dq = datastore.createQuery(metric);
		List<DataPointGroup> results = dq.execute();

		assertThat(results.size(), is(1));
		DataPointGroup group = results.get(0);

		DataPoint dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(3L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(5L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(10L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(14L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(20L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(1L));
		assertThat(dataPoint.getLongValue(), equalTo(20L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(1L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(3L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(5L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(6L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(8L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(2L));
		assertThat(dataPoint.getLongValue(), equalTo(9L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(3L));
		assertThat(dataPoint.getLongValue(), equalTo(7L));

		dataPoint = group.next();
		assertThat(dataPoint.getTimestamp(), equalTo(3L));
		assertThat(dataPoint.getLongValue(), equalTo(25L));

		dq.close();
	}

	@SuppressWarnings({"ResultOfMethodCallIgnored", "ConstantConditions"})
	@Test
	public void test_cleanCacheDir() throws IOException, DatastoreException
	{
		TestDatastore testds = new TestDatastore();
		KairosDatastore datastore = new KairosDatastore(testds, new QueryQueuingManager(1, "hostname"),
				Collections.<DataPointListener>emptyList(), "hostname", new TestDataPointFactory());

		// Create files in the cache directory
		File cacheDir = new File(datastore.getCacheDir());
		File file1 = new File(cacheDir, "testFile1");
		file1.createNewFile();
		File file2 = new File(cacheDir, "testFile2");
		file2.createNewFile();

		File[] files = cacheDir.listFiles();
		assertTrue(files.length > 0);

		datastore.cleanCacheDir(false);

		assertFalse(file1.exists());
		assertFalse(file2.exists());
	}

	private class TestDatastore implements Datastore
	{
		private DatastoreException m_toThrow = null;

		protected TestDatastore() throws DatastoreException
		{
		}

		@Override
		public void close() throws InterruptedException
		{
		}

		@Override
		public void putDataPoint(String metricName, ImmutableSortedMap<String, String> tags, DataPoint dataPoint) throws DatastoreException
		{
		}

		@Override
		public Iterable<String> getMetricNames()
		{
			return null;
		}

		@Override
		public Iterable<String> getTagNames()
		{
			return null;
		}

		@Override
		public Iterable<String> getTagValues()
		{
			return null;
		}

		public void throwQueryException(DatastoreException toThrow)
		{
			m_toThrow = toThrow;
		}

		@Override
		public void queryDatabase(DatastoreMetricQuery query, QueryCallback queryCallback)
				throws DatastoreException
		{
			if (m_toThrow != null)
				throw m_toThrow;

			try
			{
				queryCallback.startDataPointSet(LegacyDataPointFactory.DATASTORE_TYPE, Collections.<String, String>emptyMap());
				queryCallback.addDataPoint(new LegacyLongDataPoint(1, 3));
				queryCallback.addDataPoint(new LegacyLongDataPoint(1, 10));
				queryCallback.addDataPoint(new LegacyLongDataPoint(1, 20));
				queryCallback.addDataPoint(new LegacyLongDataPoint(2, 1));
				queryCallback.addDataPoint(new LegacyLongDataPoint(2, 3));
				queryCallback.addDataPoint(new LegacyLongDataPoint(2, 5));
				queryCallback.addDataPoint(new LegacyLongDataPoint(3, 25));

				queryCallback.startDataPointSet(LegacyDataPointFactory.DATASTORE_TYPE, Collections.<String, String>emptyMap());
				queryCallback.addDataPoint(new LegacyLongDataPoint(1, 5));
				queryCallback.addDataPoint(new LegacyLongDataPoint(1, 14));
				queryCallback.addDataPoint(new LegacyLongDataPoint(1, 20));
				queryCallback.addDataPoint(new LegacyLongDataPoint(2, 6));
				queryCallback.addDataPoint(new LegacyLongDataPoint(2, 8));
				queryCallback.addDataPoint(new LegacyLongDataPoint(2, 9));
				queryCallback.addDataPoint(new LegacyLongDataPoint(3, 7));

				queryCallback.endDataPoints();
			}
			catch (IOException e)
			{
				throw new DatastoreException(e);
			}
		}

		@Override
		public void deleteDataPoints(DatastoreMetricQuery deleteQuery) throws DatastoreException
		{
		}

		@Override
		public TagSet queryMetricTags(DatastoreMetricQuery query) throws DatastoreException
		{
			return null;  //To change body of implemented methods use File | Settings | File Templates.
		}
	}
}


text:
#ifndef INCLUDED_MESH_SPLITTER
#define INCLUDED_MESH_SPLITTER

// ----------------------------------------------------------------------------
// Note: this is largely based on assimp's SplitLargeMeshes_Vertex process.
// it is refactored and the coding style is slightly improved, though.
// ----------------------------------------------------------------------------

#include <vector>

struct aiScene;
struct aiMesh;
struct aiNode;

// ---------------------------------------------------------------------------
/** Splits meshes of unique vertices into meshes with no more vertices than
 *  a given, configurable threshold value.
 */
class MeshSplitter {
public:
    unsigned int LIMIT;

    void SetLimit(unsigned int l) {
        LIMIT = l;
    }

    unsigned int GetLimit() const {
        return LIMIT;
    }

    // -------------------------------------------------------------------
    /** Executes the post processing step on the given imported data.
	 * At the moment a process is not supposed to fail.
	 * @param pScene The imported data to work at.
	 */
    void Execute(aiScene *pScene);

private:
    void UpdateNode(aiNode *pcNode, const std::vector<std::pair<aiMesh *, unsigned int>> &source_mesh_map);
    void SplitMesh(unsigned int index, aiMesh *mesh, std::vector<std::pair<aiMesh *, unsigned int>> &source_mesh_map);

};

#endif // INCLUDED_MESH_SPLITTER


text:
> New as of 0.4.0

```
plugin:disable <name>                    # Disable an installed plugin (third-party only)
plugin:enable <name>                     # Enable a previously disabled plugin
plugin:install [--core|git-url [--committish tag|branch|commit|--name custom-plugin-name]]           # Optionally download git-url (with custom tag/committish) & run install trigger for active plugins (or only core ones)
plugin:install-dependencies [--core]     # Run install-dependencies trigger for active plugins (or only core ones)
plugin:list                              # Print active plugins
plugin:uninstall <name>                  # Uninstall a plugin (third-party only)
plugin:update [name [committish]]        # Optionally update named plugin from git (with custom tag/committish) & run update trigger for active plugins
```

```shell
# for 0.3.x
cd /var/lib/dokku/plugins
git clone <git url>
dokku plugins-install
```

> These commands require `root` permissions as the `install` and `install-dependencies` plugin triggers may utilize commands such as `apt-get`. For non-core plugins, please inspect those plugins before running the following command as `root` user.

## Usage

You can list all installed plugins using the `plugin` command:

```shell
dokku plugin
```

```
plugn: dev
  00_dokku-standard    0.14.6 enabled    dokku core standard plugin
  20_events            0.14.6 enabled    dokku core events logging plugin
  apps                 0.14.6 enabled    dokku core apps plugin
  build-env            0.14.6 enabled    dokku core build-env plugin
  certs                0.14.6 enabled    dokku core certificate management plugin
  checks               0.14.6 enabled    dokku core checks plugin
  common               0.14.6 enabled    dokku core common plugin
  config               0.14.6 enabled    dokku core config plugin
  docker-options       0.14.6 enabled    dokku core docker-options plugin
  domains              0.14.6 enabled    dokku core domains plugin
  enter                0.14.6 enabled    dokku core enter plugin
  git                  0.14.6 enabled    dokku core git plugin
  logs                 0.14.6 enabled    dokku core logs plugin
  named-containers     0.14.6 enabled    dokku core named containers plugin
  network              0.14.6 enabled    dokku core network plugin
  nginx-vhosts         0.14.6 enabled    dokku core nginx-vhosts plugin
  plugin               0.14.6 enabled    dokku core plugin plugin
  proxy                0.14.6 enabled    dokku core proxy plugin
  ps                   0.14.6 enabled    dokku core ps plugin
  repo                 0.14.6 enabled    dokku core repo plugin
  shell                0.14.6 enabled    dokku core shell plugin
  ssh-keys             0.14.6 enabled    dokku core ssh-keys plugin
  storage              0.14.6 enabled    dokku core storage plugin
  tags                 0.14.6 enabled    dokku core tags plugin
  tar                  0.14.6 enabled    dokku core tar plugin
```

Installing a plugin is easy as well using the `plugin:install` command. This command will also trigger the `install` pluginhook on all existing plugins.

```shell
dokku plugin:install https://github.com/dokku/dokku-postgres.git
```

```
-----> Cloning plugin repo https://github.com/dokku/dokku-postgres.git to /var/lib/dokku/plugins/available/postgres
Cloning into 'postgres'...
remote: Counting objects: 646, done.
remote: Total 646 (delta 0), reused 0 (delta 0), pack-reused 646
Receiving objects: 100% (646/646), 134.24 KiB | 0 bytes/s, done.
Resolving deltas: 100% (406/406), done.
Checking connectivity... done.
-----> Plugin postgres enabled
```

You can also uninstall a third-party plugin using the `plugin:uninstall` command:

```shell
dokku plugin:uninstall postgres
```

```
-----> Plugin postgres uninstalled
```

Enabling or disabling a plugin can also be useful in cases where you are debugging whether a third-party plugin is causing issues in your Dokku installation:

```shell
dokku plugin:disable postgres
```

```
-----> Plugin postgres disabled
```

```shell
dokku plugin:enable postgres
```

```
-----> Plugin postgres enabled
```

Finally, you can update an installed third-party plugin. This should be done after any upgrades of Dokku as there may be changes in the internal api that require an update of how the plugin interfaces with Dokku.

```shell
dokku plugin:update postgres
```

```
Plugin (postgres) updated
```


text:
namespace njli {
WorldInput::WorldInput()
    : m_AllTouches(new njli::DeviceTouch*[njli::DeviceTouch::MAX_TOUCHES])
    , m_CurrentTouches(new njli::DeviceTouch*[njli::DeviceTouch::MAX_TOUCHES])
    , m_NumTouches(0)
    , m_Orientation(0)
{
    for (u32 i = 0; i < njli::DeviceTouch::MAX_TOUCHES; ++i) {
        m_AllTouches[i] = new njli::DeviceTouch();
    }
    clearTouches();
}

WorldInput::~WorldInput()
{
    for (u32 i = 0; i < njli::DeviceTouch::MAX_TOUCHES; ++i) {
        delete m_AllTouches[i];
    }
    delete[] m_AllTouches;
    delete[] m_CurrentTouches;
}

const char* WorldInput::getClassName() const
{
    return "WorldInput";
}

s32 WorldInput::getType() const
{
    return JLI_OBJECT_TYPE_WorldInput;
}

WorldInput::operator std::string() const
{
    return "TODO";
}

DeviceTouch* WorldInput::getTouch(const s32 index)
{
    if (index >= 0 && index < DeviceTouch::MAX_TOUCHES) {
        return m_CurrentTouches[index];
    }
    return NULL;
}

const DeviceTouch* WorldInput::getTouch(const s32 index) const
{
    if (index >= 0 && index < DeviceTouch::MAX_TOUCHES) {
        return m_CurrentTouches[index];
    }
    return NULL;
}

s32 WorldInput::numberOfTouches() const
{
    return m_NumTouches;
}

//    void WorldInput::resetTouches()
//    {
//        m_NumTouches = 0;
//    }

void WorldInput::setTouch(const void* touch, const int index, const int num_touches)
{
    DEBUG_LOG_V("TAG", "setTouch(%d, %d)", 0, 0);
    m_CurrentTouches[index] = m_AllTouches[index];
    m_CurrentTouches[index]->set(touch, index, num_touches);
    m_NumTouches = num_touches;
}
void WorldInput::setTouch(const int x, const int y, const int index, const int num_touches, float scaleFactor)
{
    DEBUG_LOG_V("TAG", "setTouch(%d, %d)", x, y);
    m_CurrentTouches[index] = m_AllTouches[index];
    m_CurrentTouches[index]->set(x, y, index, num_touches, scaleFactor);
    m_NumTouches = num_touches;
}

void WorldInput::clearNodeTouches()
{
    clearTouches();
    if (njli::World::getInstance()->getScene())
        njli::World::getInstance()->getScene()->clearNodeTouches();
}

void WorldInput::touchDown()
{
    DEBUG_LOG_V("TAG", "WorldInput::touchDown(%s)", "jim");
    njli::World::getInstance()->touchDown(m_CurrentTouches);
    //        clearTouches();
}
void WorldInput::touchUp()
{
    njli::World::getInstance()->touchUp(m_CurrentTouches);
    //        clearTouches();
}
void WorldInput::touchMove()
{
    njli::World::getInstance()->touchMove(m_CurrentTouches);
    //        clearTouches();
}
void WorldInput::touchCancelled()
{
    njli::World::getInstance()->touchCancelled(m_CurrentTouches);
    //        clearTouches();
}

    void WorldInput::keyboardShow()
    {
        njli::World::getInstance()->keyboardShow();
    }

    void WorldInput::keyboardCancel()
    {
        njli::World::getInstance()->keyboardCancel();
    }

    void WorldInput::keyboardReturn(const char* text)
    {
        njli::World::getInstance()->keyboardReturn(text);
    }

void WorldInput::setOrientation(const s32 orientation)
{
    m_Orientation = orientation;
}

bool WorldInput::isPortraitOrientation() const
{
    // return (((UIInterfaceOrientation)m_Orientation == UIInterfaceOrientationPortrait) || ((UIInterfaceOrientation)m_Orientation == UIInterfaceOrientationPortraitUpsideDown));
    return false;
}

bool WorldInput::isLandscapeOrientation() const
{
    // return (((UIInterfaceOrientation)m_Orientation == UIInterfaceOrientationLandscapeLeft) || ((UIInterfaceOrientation)m_Orientation == UIInterfaceOrientationLandscapeRight));
    return true;
}

s32 WorldInput::getOrientation() const
{
    return m_Orientation;
}

void WorldInput::showKeyboard(const char* currentText)
{
    DEBUG_LOG_WRITE_V("TAG", "cannot show keyboard yet on android\n");
}

void WorldInput::clearTouches()
{
    for (u32 i = 0; i < njli::DeviceTouch::MAX_TOUCHES; ++i) {
        m_CurrentTouches[i] = NULL;
    }
}
}


text:
<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class UpdateUniqueCount extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'crowdlinker:updatecount';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Updates unique count field of shortlink table.';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		$views = LinkView::all()->toArray();
        $count = array_fetch($views, 'shortlink_id');
        $final = array_count_values($count);
        foreach($final as $key=>$value)
        {
            $shortlink = ShortLink::where('id','=',$key)->first();
            $unique_clicks = (int)$shortlink->unique_clicks + $value;
            $shortlink->unique_clicks = $unique_clicks;
            $shortlink->save();
        }
        LinkView::truncate();
        $this->info('Unique Click column updated !');
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return array(
			//array('example', InputArgument::REQUIRED, 'An example argument.'),
		);
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array(
			//array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
		);
	}

}


text:
using Arcinect.Properties;
using Microsoft.Kinect.Fusion;
using NLog;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace Arcinect
{
    class VolumeBuilder : Disposable
    {
        /// <summary>
        /// Logger of current class
        /// </summary>
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Settings of Arcinect
        /// </summary>
        private static readonly Settings settings = Settings.Default;

        /// <summary>
        /// Data source
        /// </summary>
        private Scanner source;

        /// <summary>
        /// UI dispatcher
        /// </summary>
        private Dispatcher dispatcher;

        /// <summary>
        /// The Kinect Fusion volume, enabling color reconstruction
        /// </summary
        private ColorReconstruction volume;

        /// <summary>
        /// Intermediate storage for the depth float data converted from depth image frame
        /// </summary>
        private FusionFloatImageFrame depthFloatFrame;

        /// <summary>
        /// Intermediate storage for the smoothed depth float image frame
        /// </summary>
        private FusionFloatImageFrame smoothDepthFloatFrame;

        /// <summary>
        /// Kinect color re-sampled to be the same size as the depth frame
        /// </summary>
        private FusionColorImageFrame resampledColorFrame;

        /// <summary>
        /// Kinect color mapped into depth frame
        /// </summary>
        private FusionColorImageFrame resampledColorFrameDepthAligned;

        /// <summary>
        /// Per-pixel alignment values
        /// </summary>
        private FusionFloatImageFrame deltaFromReferenceFrame;

        /// <summary>
        /// Shaded surface frame from shading point cloud frame
        /// </summary>
        private FusionColorImageFrame shadedSurfaceFrame;

        /// <summary>
        /// Calculated point cloud frame from image integration
        /// </summary>
        private FusionPointCloudImageFrame raycastPointCloudFrame;
        /// <summary>
        /// Calculated point cloud frame from input depth
        /// </summary>
        private FusionPointCloudImageFrame depthPointCloudFrame;

        /// <summary>
        /// Intermediate storage for the depth float data converted from depth image frame
        /// </summary>
        private FusionFloatImageFrame downsampledDepthFloatFrame;

        /// <summary>
        /// Intermediate storage for the depth float data following smoothing
        /// </summary>
        private FusionFloatImageFrame downsampledSmoothDepthFloatFrame;

        /// <summary>
        /// Calculated point cloud frame from image integration
        /// </summary>
        private FusionPointCloudImageFrame downsampledRaycastPointCloudFrame;

        /// <summary>
        /// Calculated point cloud frame from input depth
        /// </summary>
        private FusionPointCloudImageFrame downsampledDepthPointCloudFrame;

        /// <summary>
        /// Kinect color delta from reference frame data from AlignPointClouds
        /// </summary>
        private FusionColorImageFrame downsampledDeltaFromReferenceFrameColorFrame;

        /// <summary>
        /// Bitmap contains shaded surface frame data for rendering
        /// </summary>
        private WriteableBitmap volumeBitmap;

        /// <summary>
        /// Intermediate storage for the color data received from the camera in 32bit color, re-sampled to depth image size
        /// </summary>
        private int[] resampledColorData;

        /// <summary>
        /// Pixel buffer of depth float frame with pixel data in float format, downsampled for AlignPointClouds
        /// </summary>
        private float[] downsampledDepthData;

        /// <summary>
        /// Intermediate storage for the color data downsampled from depth image size and used in AlignPointClouds
        /// </summary>
        private int[] downsampledDeltaFromReferenceColorPixels;

        /// <summary>
        /// Pixel buffer of delta from reference frame in 32bit color
        /// </summary>
        private int[] deltaFromReferenceFramePixelsArgb;

        /// <summary>
        /// Pixels buffer of shaded surface frame in 32bit color
        /// </summary>
        private int[] shadedSurfaceFramePixelsArgb;

        /// <summary>
        /// Alignment energy from AlignDepthFloatToReconstruction for current frame
        /// </summary>
        private float alignmentEnergy;

        /// <summary>
        /// The counter for image process successes
        /// </summary>
        private int successfulFrameCount;

        /// <summary>
        /// The counter for frames that have been processed
        /// </summary>
        private int processedFrameCount;

        /// <summary>
        /// The transformation between the world and camera view coordinate system
        /// </summary>
        private Matrix4 worldToCameraTransform;

        /// <summary>
        /// The color mapping of the rendered reconstruction visualization.
        /// </summary>
        private Matrix4 worldToBGRTransform;

        /// <summary>
        /// The default transformation between the world and volume coordinate system
        /// </summary>
        private Matrix4 defaultWorldToVolumeTransform;

        /// <summary>
        /// The counter for image process failures
        /// </summary>
        private int trackingErrorCount = 0;

        /// <summary>
        /// Set true when tracking fails
        /// </summary>
        private bool trackingFailed;

        /// <summary>
        /// Set true when tracking fails and stays false until integration resumes.
        /// </summary>
        private bool trackingHasFailedPreviously;

        /// <summary>
        /// A camera pose finder to store image frames and poseCount to a database then match the input frames
        /// when tracking is lost to help us recover tracking.
        /// </summary>
        private CameraPoseFinder cameraPoseFinder;

        /// <summary>
        /// Set true when the camera pose finder has stored frames in its database and is able to match camera frames.
        /// </summary>
        private bool cameraPoseFinderAvailable;

        /// <summary>
        /// Worker thread to process color and depth data
        /// </summary>
        private Thread workerThread;

        /// <summary>
        /// Event to stop worker thread
        /// </summary>
        private ManualResetEvent workerThreadStopEvent = new ManualResetEvent(false);

        /// <summary>
        /// Event to notify that data is ready for process
        /// </summary>
        private ManualResetEvent frameDataUpdateEvent = new ManualResetEvent(false);

        public VolumeBuilder(Scanner source, Dispatcher dispatcher)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            this.source = source;
            this.dispatcher = dispatcher;

            // Set the world-view transform to identity, so the world origin is the initial camera location.
            this.worldToCameraTransform = Matrix4.Identity;

            // Map world X axis to blue channel, Y axis to green channel and Z axis to red channel,
            // normalizing each to the range [0, 1]. We also add a shift of 0.5 to both X,Y channels
            // as the world origin starts located at the center of the front face of the volume,
            // hence we need to map negative x,y world vertex locations to positive color values.
            this.worldToBGRTransform = Matrix4.Identity;
            this.worldToBGRTransform.M11 = settings.VoxelsPerMeter / settings.VoxelsX;
            this.worldToBGRTransform.M22 = settings.VoxelsPerMeter / settings.VoxelsY;
            this.worldToBGRTransform.M33 = settings.VoxelsPerMeter / settings.VoxelsZ;
            this.worldToBGRTransform.M41 = 0.5f;
            this.worldToBGRTransform.M42 = 0.5f;
            this.worldToBGRTransform.M44 = 1.0f;

            var volumeParameters = new ReconstructionParameters(settings.VoxelsPerMeter, settings.VoxelsX, settings.VoxelsY, settings.VoxelsZ);
            this.volume = ColorReconstruction.FusionCreateReconstruction(volumeParameters, ReconstructionProcessor.Amp, -1, this.worldToCameraTransform);

            var depthWidth = this.source.Frame.DepthWidth;
            var depthHeight = this.source.Frame.DepthHeight;
            var depthSize = depthWidth * depthHeight;

            this.depthFloatFrame = new FusionFloatImageFrame(depthWidth, depthHeight);
            this.smoothDepthFloatFrame = new FusionFloatImageFrame(depthWidth, depthHeight);
            this.resampledColorFrame = new FusionColorImageFrame(depthWidth, depthHeight);
            this.resampledColorFrameDepthAligned = new FusionColorImageFrame(depthWidth, depthHeight);
            this.deltaFromReferenceFrame = new FusionFloatImageFrame(depthWidth, depthHeight);
            this.shadedSurfaceFrame = new FusionColorImageFrame(depthWidth, depthHeight);
            this.raycastPointCloudFrame = new FusionPointCloudImageFrame(depthWidth, depthHeight);
            this.depthPointCloudFrame = new FusionPointCloudImageFrame(depthWidth, depthHeight);

            var downsampledDepthWidth = depthWidth / settings.DownsampleFactor;
            var downsampledDepthHeight = depthHeight / settings.DownsampleFactor;
            var downsampledDepthSize = downsampledDepthWidth * downsampledDepthHeight;

            this.downsampledDepthFloatFrame = new FusionFloatImageFrame(downsampledDepthWidth, downsampledDepthHeight);
            this.downsampledSmoothDepthFloatFrame = new FusionFloatImageFrame(downsampledDepthWidth, downsampledDepthHeight);
            this.downsampledRaycastPointCloudFrame = new FusionPointCloudImageFrame(downsampledDepthWidth, downsampledDepthHeight);
            this.downsampledDepthPointCloudFrame = new FusionPointCloudImageFrame(downsampledDepthWidth, downsampledDepthHeight);
            this.downsampledDeltaFromReferenceFrameColorFrame = new FusionColorImageFrame(downsampledDepthWidth, downsampledDepthHeight);

            this.resampledColorData = new int[depthSize];
            this.downsampledDepthData = new float[downsampledDepthSize];
            this.downsampledDeltaFromReferenceColorPixels = new int[downsampledDepthSize];
            this.deltaFromReferenceFramePixelsArgb = new int[depthSize];
            this.shadedSurfaceFramePixelsArgb = new int[this.shadedSurfaceFrame.PixelDataLength];

            this.defaultWorldToVolumeTransform = this.volume.GetCurrentWorldToVolumeTransform();

            this.volumeBitmap = new WriteableBitmap(depthWidth, depthHeight, settings.DefaultSystemDPI, settings.DefaultSystemDPI, PixelFormats.Bgr32, null);

            // Create a camera pose finder with default parameters
            this.cameraPoseFinder = CameraPoseFinder.FusionCreateCameraPoseFinder(CameraPoseFinderParameters.Defaults);

            this.workerThread = new Thread(WorkerThreadProc);
            this.workerThread.Start();
            this.source.Frame.OnDataUpdate += OnFrameDataUpdate;
        }

        protected override void DisposeManaged()
        {
            this.workerThreadStopEvent.Set();
            this.workerThread.Join();

            this.source.Frame.OnDataUpdate -= OnFrameDataUpdate;

            SafeDispose(ref this.volume);

            SafeDispose(ref this.depthFloatFrame);
            SafeDispose(ref this.smoothDepthFloatFrame);
            SafeDispose(ref this.resampledColorFrame);
            SafeDispose(ref this.resampledColorFrameDepthAligned);
            SafeDispose(ref this.deltaFromReferenceFrame);
            SafeDispose(ref this.shadedSurfaceFrame);
            SafeDispose(ref this.raycastPointCloudFrame);
            SafeDispose(ref this.depthPointCloudFrame);
            SafeDispose(ref this.downsampledDepthFloatFrame);
            SafeDispose(ref this.downsampledSmoothDepthFloatFrame);
            SafeDispose(ref this.downsampledRaycastPointCloudFrame);
            SafeDispose(ref this.downsampledDepthPointCloudFrame);
            SafeDispose(ref this.downsampledDeltaFromReferenceFrameColorFrame);

            SafeDispose(ref this.cameraPoseFinder);

            base.DisposeManaged();
        }

        /// <summary>
        /// Reset reconstruction object to initial state
        /// </summary>
        private void ResetReconstruction()
        {
            logger.Trace("Start reset reconstruction");

            // Reset tracking error counter
            this.trackingErrorCount = 0;

            // Set the world-view transform to identity, so the world origin is the initial camera location.
            this.worldToCameraTransform = Matrix4.Identity;

            // Reset volume
            try
            {
                // Translate the reconstruction volume location away from the world origin by an amount equal
                // to the minimum depth threshold. This ensures that some depth signal falls inside the volume.
                // If set false, the default world origin is set to the center of the front face of the
                // volume, which has the effect of locating the volume directly in front of the initial camera
                // position with the +Z axis into the volume along the initial camera direction of view.
                if (settings.TranslateResetPoseByMinDepthThreshold)
                {
                    var worldToVolumeTransform = this.defaultWorldToVolumeTransform;

                    // Translate the volume in the Z axis by the minDepthClip distance
                    float minDistance = Math.Min(settings.MinDepthClip, settings.MaxDepthClip);
                    worldToVolumeTransform.M43 -= minDistance * settings.VoxelsPerMeter;

                    this.volume.ResetReconstruction(this.worldToCameraTransform, worldToVolumeTransform);
                }
                else
                {
                    this.volume.ResetReconstruction(this.worldToCameraTransform);
                }
            }
            catch (InvalidOperationException error)
            {
                logger.Error("Failed to reset reconstruction. Error: {0}", error);
            }

            logger.Trace("Finish reset reconstruction");
        }

        #region Worker Thread

        private void WorkerThreadProc(object state)
        {
            var events = new WaitHandle[] { this.frameDataUpdateEvent, this.workerThreadStopEvent };

            for (var i = WaitHandle.WaitAny(events); i != 1; i = WaitHandle.WaitAny(events))
            {
                switch (i)
                {
                    case 0:
                        this.frameDataUpdateEvent.Reset();
                        Process();
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("Unexpected event index");
                }
            }
        }

        #endregion

        #region Process frames

        private void OnFrameDataUpdate(object sender)
        {
            this.frameDataUpdateEvent.Set();
        }

        /// <summary>
        /// The main process function
        /// </summary>
        private void Process()
        {
            try
            {
                var stopwatch = Stopwatch.StartNew();

                // Check if camera pose finder is available
                this.cameraPoseFinderAvailable = this.cameraPoseFinder.GetStoredPoseCount() > 0;

                // Convert depth to float and render depth frame
                this.volume.DepthToDepthFloatFrame(this.source.Frame.DepthData, this.depthFloatFrame, settings.MinDepthClip, settings.MaxDepthClip, false);

                // Track camera pose
                TrackCamera();

                // Only continue if we do not have tracking errors
                if (this.trackingErrorCount == 0)
                {
                    // Integrate depth
                    IntegrateData();

                    // Raycast and render
                    UpdateVolumeData();

                    // Update camera pose finder, adding key frames to the database
                    if (!this.trackingHasFailedPreviously
                        && this.successfulFrameCount > settings.MinSuccessfulTrackingFramesForCameraPoseFinder
                        && this.processedFrameCount % settings.CameraPoseFinderProcessFrameCalculationInterval == 0)
                    {
                        UpdateCameraPoseFinder();
                    }
                }

                logger.Trace("Volume data processed. Spent {0}ms", stopwatch.ElapsedMilliseconds);
            }
            catch (InvalidOperationException ex)
            {
                logger.Error("Failed to process. Error: {0}", ex);
            }
        }

        /// <summary>
        /// Track the camera pose
        /// </summary>
        private void TrackCamera()
        {
            bool calculateDeltaFrame = this.processedFrameCount % settings.DeltaFrameCalculationInterval == 0;

            // Get updated camera transform from image alignment
            var calculatedCameraPos = this.worldToCameraTransform;

            // Track using AlignPointClouds
            var trackingSucceeded = TrackCameraAlignPointClouds(ref calculateDeltaFrame, ref calculatedCameraPos);

            if (!trackingSucceeded && this.successfulFrameCount != 0)
            {
                this.SetTrackingFailed();

                if (this.cameraPoseFinderAvailable)
                {
                    // Here we try to find the correct camera pose, to re-localize camera tracking.
                    // We can call either the version using AlignDepthFloatToReconstruction or the
                    // version using AlignPointClouds, which typically has a higher success rate.
                    // trackingSucceeded = this.FindCameraPoseAlignDepthFloatToReconstruction();
                    trackingSucceeded = FindCameraPoseAlignPointClouds();
                }
            }
            else
            {
                SetTrackingSucceeded();

                this.worldToCameraTransform = calculatedCameraPos;
            }

            if (trackingSucceeded)
            {
                // Increase processed frame counter
                this.processedFrameCount++;
            }
        }

        /// <summary>
        /// Track camera pose using AlignPointClouds
        /// </summary>
        /// <param name="calculateDeltaFrame">A flag to indicate it is time to calculate the delta frame.</param>
        /// <param name="calculatedCameraPose">The calculated camera pose.</param>
        /// <returns>Returns true if tracking succeeded, false otherwise.</returns>
        private bool TrackCameraAlignPointClouds(ref bool calculateDeltaFrame, ref Matrix4 calculatedCameraPose)
        {
            var trackingSucceeded = false;

            DownsampleDepthFrameNearestNeighbor();

            // Smooth the depth frame
            this.volume.SmoothDepthFloatFrame(this.downsampledDepthFloatFrame, this.downsampledSmoothDepthFloatFrame, settings.SmoothingKernelWidth, settings.SmoothingDistanceThreshold);

            // Calculate point cloud from the smoothed frame
            FusionDepthProcessor.DepthFloatFrameToPointCloud(this.downsampledSmoothDepthFloatFrame, this.downsampledDepthPointCloudFrame);

            // Get the saved pose view by raycasting the volume from the current camera pose
            this.volume.CalculatePointCloud(this.downsampledRaycastPointCloudFrame, calculatedCameraPose);

            var initialPose = calculatedCameraPose;

            // Note that here we only calculate the deltaFromReferenceFrame every
            // DeltaFrameCalculationInterval frames to reduce computation time
            if (calculateDeltaFrame)
            {
                trackingSucceeded = FusionDepthProcessor.AlignPointClouds(
                    this.downsampledRaycastPointCloudFrame,
                    this.downsampledDepthPointCloudFrame,
                    FusionDepthProcessor.DefaultAlignIterationCount,
                    this.downsampledDeltaFromReferenceFrameColorFrame,
                    ref calculatedCameraPose);

                UpsampleColorDeltasFrameNearestNeighbor();

                // Set calculateDeltaFrame to false as we are rendering it here
                calculateDeltaFrame = false;
            }
            else
            {
                // Don't bother getting the residual delta from reference frame to cut computation time
                trackingSucceeded = FusionDepthProcessor.AlignPointClouds(
                    this.downsampledRaycastPointCloudFrame,
                    this.downsampledDepthPointCloudFrame,
                    FusionDepthProcessor.DefaultAlignIterationCount,
                    null,
                    ref calculatedCameraPose);
            }

            if (trackingSucceeded)
            {
                trackingSucceeded = MathUtils.CheckTransformChange(
                    initialPose,
                    calculatedCameraPose,
                    settings.MaxTranslationDeltaAlignPointClouds,
                    settings.MaxRotationDeltaAlignPointClouds);
            }

            return trackingSucceeded;
        }

        /// <summary>
        /// Downsample depth pixels with nearest neighbor
        /// </summary>
        /// <param name="dest">The destination depth image.</param>
        /// <param name="factor">The downsample factor (2=x/2,y/2, 4=x/4,y/4, 8=x/8,y/8, 16=x/16,y/16).</param>
        private void DownsampleDepthFrameNearestNeighbor()
        {
            var width = this.source.Frame.DepthWidth;
            var height = this.source.Frame.DepthHeight;
            var downsampledWidth = this.source.Frame.DepthWidth / settings.DownsampleFactor;
            var downsampledHeight = this.source.Frame.DepthHeight / settings.DownsampleFactor;

            for (var y = 0; y < downsampledHeight; y++)
            {
                int flippedDestIndex = (y * downsampledWidth) + (downsampledWidth - 1);
                int sourceIndex = y * width * settings.DownsampleFactor;

                for (int x = 0; x < downsampledWidth; ++x, --flippedDestIndex, sourceIndex += settings.DownsampleFactor)
                {
                    // Copy depth value
                    this.downsampledDepthData[flippedDestIndex] = (float)this.source.Frame.DepthData[sourceIndex] * 0.001f;
                }
            }

            this.downsampledDepthFloatFrame.CopyPixelDataFrom(this.downsampledDepthData);
        }

        /// <summary>
        /// Up sample color delta from reference frame with nearest neighbor - replicates pixels
        /// </summary>
        /// <param name="factor">The up sample factor (2=x*2,y*2, 4=x*4,y*4, 8=x*8,y*8, 16=x*16,y*16).</param>
        private void UpsampleColorDeltasFrameNearestNeighbor()
        {
            var width = this.source.Frame.DepthWidth;
            var height = this.source.Frame.DepthHeight;
            var downsampledWidth = this.source.Frame.DepthWidth / settings.DownsampleFactor;
            var downsampledHeight = this.source.Frame.DepthHeight / settings.DownsampleFactor;
            var factor = settings.DownsampleFactor;

            this.downsampledDeltaFromReferenceFrameColorFrame.CopyPixelDataTo(this.downsampledDeltaFromReferenceColorPixels);

            for (var y = 0; y < downsampledHeight; y++)
            {
                var destIndex = y * width * factor;
                var sourceColorIndex = y * downsampledWidth;

                for (var x = 0; x < downsampledWidth; ++x, ++sourceColorIndex)
                {
                    var color = this.source.Frame.DepthData[sourceColorIndex];

                    // Replicate pixels horizontally
                    for (var colFactorIndex = 0; colFactorIndex < factor; ++colFactorIndex, ++destIndex)
                    {
                        // Replicate pixels vertically
                        for (var rowFactorIndex = 0; rowFactorIndex < factor; ++rowFactorIndex)
                        {
                            // Copy color pixel
                            this.deltaFromReferenceFramePixelsArgb[destIndex + (rowFactorIndex * width)] = color;
                        }
                    }
                }
            }

            var sizeOfInt = sizeof(int);
            var rowByteSize = downsampledHeight * sizeOfInt;

            // Duplicate the remaining rows with memcpy
            for (var y = 0; y < downsampledHeight; ++y)
            {
                // iterate only for the smaller number of rows
                var srcRowIndex = width * factor * y;

                // Duplicate lines
                for (var r = 1; r < factor; ++r)
                {
                    int index = width * ((y * factor) + r);

                    Buffer.BlockCopy(
                        this.deltaFromReferenceFramePixelsArgb, srcRowIndex * sizeOfInt, this.deltaFromReferenceFramePixelsArgb, index * sizeOfInt, rowByteSize);
                }
            }
        }

        /// <summary>
        /// Set variables if camera tracking succeeded
        /// </summary>
        private void SetTrackingFailed()
        {
            // Clear successful frame count and increment the track error count
            this.trackingFailed = true;
            this.trackingHasFailedPreviously = true;
            this.trackingErrorCount++;
            this.successfulFrameCount = 0;
        }

        /// <summary>
        /// Set variables if camera tracking succeeded
        /// </summary>
        private void SetTrackingSucceeded()
        {
            // Clear track error count and increment the successful frame count
            this.trackingFailed = false;
            this.trackingErrorCount = 0;
            this.successfulFrameCount++;
        }

        /// <summary>
        /// Reset tracking variables
        /// </summary>
        private void ResetTracking()
        {
            this.trackingFailed = false;
            this.trackingHasFailedPreviously = false;
            this.trackingErrorCount = 0;
            this.successfulFrameCount = 0;

            this.cameraPoseFinder.ResetCameraPoseFinder();
        }

        /// <summary>
        /// Perform camera pose finding when tracking is lost using AlignPointClouds.
        /// This is typically more successful than FindCameraPoseAlignDepthFloatToReconstruction.
        /// </summary>
        /// <returns>Returns true if a valid camera pose was found, otherwise false.</returns>
        private bool FindCameraPoseAlignPointClouds()
        {
            if (!this.cameraPoseFinderAvailable)
            {
                return false;
            }

            ProcessColorForCameraPoseFinder();

            var matchCandidates = this.cameraPoseFinder.FindCameraPose(
                this.depthFloatFrame,
                this.resampledColorFrame);

            if (matchCandidates == null)
            {
                return false;
            }

            var poseCount = matchCandidates.GetPoseCount();
            var minDistance = matchCandidates.CalculateMinimumDistance();

            if (poseCount == 0 || minDistance >= settings.CameraPoseFinderDistanceThresholdReject)
            {
                return false;
            }

            // Smooth the depth frame
            this.volume.SmoothDepthFloatFrame(this.depthFloatFrame, this.smoothDepthFloatFrame, settings.SmoothingKernelWidth, settings.SmoothingDistanceThreshold);

            // Calculate point cloud from the smoothed frame
            FusionDepthProcessor.DepthFloatFrameToPointCloud(this.smoothDepthFloatFrame, this.depthPointCloudFrame);

            var smallestEnergy = double.MaxValue;
            var smallestEnergyNeighborIndex = -1;

            var bestNeighborIndex = -1;
            var bestNeighborCameraPose = Matrix4.Identity;

            var bestNeighborAlignmentEnergy = settings.MaxAlignPointCloudsEnergyForSuccess;

            // Run alignment with best matched poseCount (i.e. k nearest neighbors (kNN))
            var maxTests = Math.Min(settings.MaxCameraPoseFinderPoseTests, poseCount);

            var neighbors = matchCandidates.GetMatchPoses();

            for (var n = 0; n < maxTests; n++)
            {
                // Run the camera tracking algorithm with the volume
                // this uses the raycast frame and pose to find a valid camera pose by matching the raycast against the input point cloud
                var poseProposal = neighbors[n];

                // Get the saved pose view by raycasting the volume
                this.volume.CalculatePointCloud(this.raycastPointCloudFrame, poseProposal);

                var success = this.volume.AlignPointClouds(
                    this.raycastPointCloudFrame,
                    this.depthPointCloudFrame,
                    FusionDepthProcessor.DefaultAlignIterationCount,
                    this.resampledColorFrame,
                    out this.alignmentEnergy,
                    ref poseProposal);

                var relocSuccess = success && this.alignmentEnergy < bestNeighborAlignmentEnergy && this.alignmentEnergy > settings.MinAlignPointCloudsEnergyForSuccess;

                if (relocSuccess)
                {
                    bestNeighborAlignmentEnergy = this.alignmentEnergy;
                    bestNeighborIndex = n;

                    // This is after tracking succeeds, so should be a more accurate pose to store...
                    bestNeighborCameraPose = poseProposal;

                    // Update the delta image
                    this.resampledColorFrame.CopyPixelDataTo(this.deltaFromReferenceFramePixelsArgb);
                }

                // Find smallest energy neighbor independent of tracking success
                if (this.alignmentEnergy < smallestEnergy)
                {
                    smallestEnergy = this.alignmentEnergy;
                    smallestEnergyNeighborIndex = n;
                }
            }

            matchCandidates.Dispose();

            // Use the neighbor with the smallest residual alignment energy
            // At the cost of additional processing we could also use kNN+Mean camera pose finding here
            // by calculating the mean pose of the best n matched poses and also testing this to see if the
            // residual alignment energy is less than with kNN.
            if (bestNeighborIndex > -1)
            {
                this.worldToCameraTransform = bestNeighborCameraPose;
                this.SetReferenceFrame(this.worldToCameraTransform);

                // Tracking succeeded!
                this.SetTrackingSucceeded();

                return true;
            }
            else
            {
                this.worldToCameraTransform = neighbors[smallestEnergyNeighborIndex];
                this.SetReferenceFrame(this.worldToCameraTransform);

                // Camera pose finding failed - return the tracking failed error code
                this.SetTrackingFailed();

                return false;
            }
        }

        /// <summary>
        /// Process input color image to make it equal in size to the depth image
        /// </summary>
        private void ProcessColorForCameraPoseFinder()
        {
            var rawDepthHeight = this.source.Frame.DepthWidth / 4 * 3;
            var factor = this.source.Frame.ColorWidth / rawDepthHeight;
            var filledZeroMargin = (this.source.Frame.DepthHeight - rawDepthHeight) / 2;

            for (var y = filledZeroMargin; y < this.source.Frame.DepthHeight - filledZeroMargin; y++)
            {
                var destIndex = y * this.source.Frame.DepthWidth;

                for (var x = 0; x < this.source.Frame.DepthWidth; ++x, ++destIndex)
                {
                    var srcX = (int)(x * factor);
                    var srcY = (int)(y * factor);
                    var sourceColorIndex = (srcY * this.source.Frame.ColorWidth) + srcX;

                    this.resampledColorData[destIndex] = this.source.Frame.ColorData[destIndex];
                }
            }

            this.resampledColorFrame.CopyPixelDataFrom(this.resampledColorData);
        }

        /// <summary>
        /// This is used to set the reference frame.
        /// </summary>
        /// <param name="pose">The pose to use.</param>
        private void SetReferenceFrame(Matrix4 pose)
        {
            // Get the saved pose view by raycasting the volume
            this.volume.CalculatePointCloudAndDepth(this.raycastPointCloudFrame, this.smoothDepthFloatFrame, null, pose);

            // Set this as the reference frame for the next call to AlignDepthFloatToReconstruction
            this.volume.SetAlignDepthFloatToReconstructionReferenceFrame(this.smoothDepthFloatFrame);
        }

        /// <summary>
        /// Perform volume depth data integration
        /// </summary>
        /// <returns>Returns true if a color frame is available for further processing, false otherwise.</returns>
        private void IntegrateData()
        {
            // Don't integrate depth data into the volume if:
            // 1) tracking failed
            // 2) camera pose finder is off and we have paused capture
            // 3) camera pose finder is on and we are still under the m_cMinSuccessfulTrackingFramesForCameraPoseFinderAfterFailure
            //    number of successful frames count.
            var integrateData = !this.trackingFailed
                    && (!this.cameraPoseFinderAvailable
                    || (this.cameraPoseFinderAvailable
                    && !(this.trackingHasFailedPreviously
                    && this.successfulFrameCount < settings.MinSuccessfulTrackingFramesForCameraPoseFinderAfterFailure)));

            // Integrate the frame to volume
            if (integrateData)
            {
                // Reset this flag as we are now integrating data again
                this.trackingHasFailedPreviously = false;

                // Just integrate depth
                this.volume.IntegrateFrame(
                    this.depthFloatFrame,
                    settings.IntegrationWeight,
                    this.worldToCameraTransform);
            }
        }

        /// <summary>
        /// Update the camera pose finder data.
        /// </summary
        private void UpdateCameraPoseFinder()
        {
            ProcessColorForCameraPoseFinder();

            bool poseHistoryTrimmed;
            bool addedPose;

            // This function will add the pose to the camera pose finding database when the input frame's minimum
            // distance to the existing database is equal to or above CameraPoseFinderDistanceThresholdAccept
            // (i.e. indicating that the input has become dis-similar to the existing database and a new frame
            // should be captured). Note that the color and depth frames must be the same size, however, the
            // horizontal mirroring setting does not have to be consistent between depth and color. It does have
            // to be consistent between camera pose finder database creation and calling FindCameraPose though,
            // hence we always reset both the reconstruction and database when changing the mirror depth setting.
            this.cameraPoseFinder.ProcessFrame(this.depthFloatFrame, this.resampledColorFrame, this.worldToCameraTransform, settings.CameraPoseFinderDistanceThresholdAccept,
                    out addedPose, out poseHistoryTrimmed);
        }

        /// <summary>
        /// Update the volume data.
        /// </summary
        private void UpdateVolumeData()
        {
            // For capture color
            //this.volume.CalculatePointCloud(this.raycastPointCloudFrame, this.shadedSurfaceFrame, this.worldToCameraTransform);

            this.volume.CalculatePointCloud(this.raycastPointCloudFrame, this.worldToCameraTransform);

            // Shade point cloud frame for rendering
            FusionDepthProcessor.ShadePointCloud(
                    this.raycastPointCloudFrame,
                    this.worldToCameraTransform,
                    this.worldToBGRTransform,
                    this.shadedSurfaceFrame, null);

            // Copy pixel data to pixel buffer
            this.shadedSurfaceFrame.CopyPixelDataTo(this.shadedSurfaceFramePixelsArgb);

            this.dispatcher.BeginInvoke((Action)RenderVolumeBitmap);
        }

        private void RenderVolumeBitmap()
        {
            if (!this.Disposed)
            {
                this.volumeBitmap.Lock();

                // Write pixels to bitmap
                this.volumeBitmap.WritePixels(
                        new Int32Rect(0, 0, this.shadedSurfaceFrame.Width, this.shadedSurfaceFrame.Height),
                        this.shadedSurfaceFramePixelsArgb,
                        this.volumeBitmap.PixelWidth * sizeof(int),
                        0);

                this.volumeBitmap.Unlock();
            }
        }

        #endregion

        public ColorMesh CreateMesh()
        {
            return this.volume.CalculateMesh(1);
        }

        #region Properties

        public BitmapSource VolumeBitmap
        {
            get { return this.volumeBitmap; }
        }

        #endregion
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Papulospora biformospora Kiril.

### Remarks
null


text:
#import "UIViewController.h"

@class _ADUIViewControllerAdController;

@interface UIViewController (iAdAdditions_Private)
- (void)_iAd_requestForInterstitialAdDidSucceed:(_Bool)arg1 resultMessage:(id)arg2;
@property(readonly, nonatomic) _ADUIViewControllerAdController *_iAd_advertisingController;
@end


text:
package com.monitor.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.monitor.R;
import com.monitor.dal.RecordDAL;
import com.monitor.model.RecordInfo;

public class DataFragment extends BaseFragment {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//return super.onCreateView(inflater, container, savedInstanceState);

		View view = LayoutInflater.from(getActivity()).inflate(R.layout.data_main, null);

		WebView web = (WebView)view.findViewById(R.id.data_main_web);

		WebSettings setting = web.getSettings();
		setting.setJavaScriptEnabled(true);
		setting.setCacheMode(WebSettings.LOAD_NO_CACHE);

		web.setScrollBarStyle(0);
		web.loadUrl("file:///android_asset/data.html");
		web.addJavascriptInterface(new GetAllSiteData(getActivity()), "JavaScriptInterface");

		return view;
	}
}

class GetAllSiteData{
	private Context context;
	public GetAllSiteData(Context context){
		this.context = context;
	}

	public String getData(){
		JSONObject map;
		JSONArray array = new JSONArray();

		try {
			RecordDAL dal = new RecordDAL(context);
			ArrayList<RecordInfo> list = dal.queryAll();
			dal.close();

			for(int i = 0; i < list.size(); i++){
				map = new JSONObject();
				map.put("recordId", list.get(i).recordId);
				map.put("siteId", list.get(i).siteId);
				map.put("addTime", list.get(i).addTime);
				map.put("streamLength", list.get(i).streamLength);
				array.put(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return array.toString();
	}
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.04.10 at 03:03:08 PM CEST
//

package org.cumulus.pandtocs;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for TargetOfCertificationType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="TargetOfCertificationType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="ID" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TargetOfCertificationType")
public class TargetOfCertificationType {

    @XmlAttribute(name = "ID", required = true)
    protected String id;

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getID() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setID(String value) {
        this.id = value;
    }

}


text:
package be.ugent;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.MongoClient;

public class MongoDBSingleton {

 private static MongoDBSingleton mDbSingleton;

 private static MongoClient mongoClient;

 private static DB db ;

 private static final String dbHost = "127.0.0.1";
 private static final int dbPort = 9000;
 private static final String dbName = "CHRONIC";

 private MongoDBSingleton(){};

 public static MongoDBSingleton getInstance(){
  if(mDbSingleton == null){
   mDbSingleton = new MongoDBSingleton();
  }
  return mDbSingleton;
 }

 public DB getTestdb(){
  if(mongoClient == null){
   try {
    mongoClient = new MongoClient(dbHost , dbPort);
   } catch (UnknownHostException e) {
    return null;
   }
  }
  if(db == null)
   db = mongoClient.getDB(dbName);
//  if(!db.isAuthenticated()){
//   boolean auth = db.authenticate(dbUser, dbPassword.toCharArray());
//  }
  return db;
 }

 public boolean isOnline(String targetDB){
	 if(getTestdb()!=null){
		 try{
			 List<String> databaseNames = mongoClient.getDatabaseNames();
			 if(databaseNames.contains(targetDB)){
				 return true;
			 }
			 return false;
		 }catch(Exception e){
			 return false;
		 }
	 }
	 else{
		 try{
		 getInstance();
		 List<String> databaseNames = mongoClient.getDatabaseNames();
		 if(databaseNames.contains(targetDB)){
			 return true;
		 }
		 return false;}
		 catch(Exception e){
			 return false;
		 }
	 }
 }
}


text:
package domain

import model.Pence
import play.api.libs.json.{JsPath, Reads, Json}
import play.api.libs.functional.syntax._

case class Order(id: String,
                 netAmountInPence: Pence,
                 commissionAmountInPence: Pence,
                 grossAmountInPence: Pence,
                 rate: BigDecimal) {

  val hasAmountInfo = grossAmountInPence.value != 0L

}

object Order {

  implicit val orderReads: Reads[Order] = (
    (JsPath \ "id").read[String] and
    (JsPath \ "netAmountInPence").read[Pence] and
    (JsPath \ "commissionAmountInPence").read[Pence] and
    (JsPath \ "totalAmountInPence").read[Pence] and
    (JsPath \ "rate").read[BigDecimal]
    )(Order.apply _)

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.mq;

/**
 *
 * <p>
 * 详情见: https://redkale.org
 *
 * @author zhangjx
 *
 * @since 2.1.0
 */
public interface MessageProcessor {

    default void begin(int size) {
    }

    public void process(MessageRecord message, Runnable callback);

    default void commit() {
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<Microsoft.NetCore.Analyzers.Security.DoNotHardCodeCertificate, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;

namespace Microsoft.NetCore.Analyzers.Security.UnitTests
{
    public class DoNotHardCodeCertificateTests : TaintedDataAnalyzerTestBase<DoNotHardCodeCertificate, DoNotHardCodeCertificate>
    {
        protected override DiagnosticDescriptor Rule => DoNotHardCodeCertificate.Rule;

        [Fact]
        public async Task Test_Source_ContantByteArray_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate.X509Certificate(string fileName)", "void TestClass.TestMethod(string path)", "byte[]", "void TestClass.TestMethod(string path)"));
        }

        [Fact]
        public async Task Test_Source_ConvertFromBase64String_WithConstantString_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path)
    {
        byte[] bytes = Convert.FromBase64String(""AAAAAaazaoensuth"");
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}",
            GetCSharpResultAt(12, 9, 10, 24, "X509Certificate.X509Certificate(string fileName)", "void TestClass.TestMethod(string path)", "byte[] Convert.FromBase64String(string s)", "void TestClass.TestMethod(string path)"));
        }

        [Fact]
        public async Task Test_Source_ASCIIEncodingGetBytes_WithConstantString_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path)
    {
        byte[] bytes = new ASCIIEncoding().GetBytes(""AAAAAaazaoensuth"");
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}",
            GetCSharpResultAt(12, 9, 10, 24, "X509Certificate.X509Certificate(string fileName)", "void TestClass.TestMethod(string path)", "byte[] Encoding.GetBytes(string s)", "void TestClass.TestMethod(string path)"));
        }

        [Fact]
        public async Task Test_Source_EncodingUTF8GetBytes_WithConstantString_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(""AAAAAaazaoensuth"");
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}",
            GetCSharpResultAt(12, 9, 10, 24, "X509Certificate.X509Certificate(string fileName)", "void TestClass.TestMethod(string path)", "byte[] Encoding.GetBytes(string s)", "void TestClass.TestMethod(string path)"));
        }

        [Fact]
        public async Task Test_Source_ASCIIEncodingGetBytes_WithStringAndInt32AndInt32AndByteArrayAndInt32Parameters_WithConstantString_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(byte[] bytes, string path)
    {
        new ASCIIEncoding().GetBytes(""AAAAAaazaoensuth"", 0, 3, bytes, 0);
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}",
            GetCSharpResultAt(12, 9, 10, 38, "X509Certificate.X509Certificate(string fileName)", "void TestClass.TestMethod(byte[] bytes, string path)", "string chars", "int ASCIIEncoding.GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithStringAndSecureStringAndX509KeyStorageFlagsParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, SecureString password, X509KeyStorageFlags keyStorageFlags)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path, password, keyStorageFlags);
    }
}",
            GetCSharpResultAt(12, 9, 10, 24, "X509Certificate.X509Certificate(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)", "void TestClass.TestMethod(string path, SecureString password, X509KeyStorageFlags keyStorageFlags)", "byte[]", "void TestClass.TestMethod(string path, SecureString password, X509KeyStorageFlags keyStorageFlags)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithByteArrayAndStringAndX509KeyStorageFlagsParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, string password, X509KeyStorageFlags keyStorageFlags)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes, password, keyStorageFlags);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate.X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)", "void TestClass.TestMethod(string path, string password, X509KeyStorageFlags keyStorageFlags)", "byte[]", "void TestClass.TestMethod(string path, string password, X509KeyStorageFlags keyStorageFlags)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithStringAndStringParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, string password)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes, password);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate.X509Certificate(byte[] rawData, string password)", "void TestClass.TestMethod(string path, string password)", "byte[]", "void TestClass.TestMethod(string path, string password)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithStringAndSecureStringParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, SecureString password)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes, password);
    }
}",
            GetCSharpResultAt(12, 9, 10, 24, "X509Certificate.X509Certificate(byte[] rawData, SecureString password)", "void TestClass.TestMethod(string path, SecureString password)", "byte[]", "void TestClass.TestMethod(string path, SecureString password)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithStringAndStringAndX509KeyStorageFlagsParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, string password, X509KeyStorageFlags keyStorageFlags)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes, password, keyStorageFlags);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate.X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)", "void TestClass.TestMethod(string path, string password, X509KeyStorageFlags keyStorageFlags)", "byte[]", "void TestClass.TestMethod(string path, string password, X509KeyStorageFlags keyStorageFlags)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithByteArrayAndSecureStringParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, SecureString password)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes, password);
    }
}",
            GetCSharpResultAt(12, 9, 10, 24, "X509Certificate.X509Certificate(byte[] rawData, SecureString password)", "void TestClass.TestMethod(string path, SecureString password)", "byte[]", "void TestClass.TestMethod(string path, SecureString password)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithByteArrayParameter_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, string password)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate.X509Certificate(byte[] data)", "void TestClass.TestMethod(string path, string password)", "byte[]", "void TestClass.TestMethod(string path, string password)"));
        }

        [Fact]
        public async Task Test_Sink_X509Certificate_WithByteArrayAndStringParameters_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path, string password)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate(bytes, password);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate.X509Certificate(byte[] rawData, string password)", "void TestClass.TestMethod(string path, string password)", "byte[]", "void TestClass.TestMethod(string path, string password)"));
        }

        [Fact]
        public async Task Test_X509Certificates2_Diagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string path)
    {
        byte[] bytes = new byte[] {1, 2, 3};
        File.WriteAllBytes(path, bytes);
        new X509Certificate2(path);
    }
}",
            GetCSharpResultAt(11, 9, 9, 24, "X509Certificate2.X509Certificate2(string fileName)", "void TestClass.TestMethod(string path)", "byte[]", "void TestClass.TestMethod(string path)"));
        }

        // For now, we didn't take serialization into consideration.
        [Fact]
        public async Task Test_Sink_X509Certificate_WithSerializationInfoAndStreamingContextParameters_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(SerializationInfo info, StreamingContext context)
    {
        new X509Certificate(info, context);
    }
}");
        }

        [Fact]
        public async Task Test_Source_NotContantByteArray_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(byte[] bytes, string path)
    {
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}");
        }

        [Fact]
        public async Task Test_Source_ConvertFromBase64String_WithNotConstantString_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(string s, string path)
    {
        byte[] bytes = Convert.FromBase64String(s);
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}");
        }

        [Fact]
        public async Task Test_X509Certificate2_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(byte[] bytes, string path)
    {
        File.WriteAllBytes(path, bytes);
        new X509Certificate2(path);
    }
}");
        }

        [Fact]
        public async Task Test_Source_ASCIIEncodingGetBytes_WithCharArrayAndInt32AndInt32AndByteArrayAndInt32Parameters_WithConstantCharArray_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System.IO;
using System.Text;

using System.Security.Cryptography.X509Certificates;

class TestClass
{
    public void TestMethod(byte[] bytes, string path)
    {
        char[] chars = new char[] {'1', '2', '3'};
        new ASCIIEncoding().GetBytes(chars, 0, 3, bytes, 0);
        File.WriteAllBytes(path, bytes);
        new X509Certificate(path);
    }
}");
        }

        // Didn't find out what causes NRE.
        [Fact, WorkItem(3012, "https://github.com/dotnet/roslyn-analyzers/issues/3012")]
        public async Task Test_ExampleCodeFromTheIssue_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;

class Constants
{
    public static Regex UnhashedNameIdRegex = new Regex(@""^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$"");
}

class TestClass
{
    public static string Calculate(string unhashedNameId)
    {
        if (string.IsNullOrWhiteSpace(unhashedNameId))
        {
            throw new ArgumentNullException(nameof(unhashedNameId), $""{ nameof(unhashedNameId)} must not be null, empty or whitespace."");
        }

        if (!Constants.UnhashedNameIdRegex.IsMatch(unhashedNameId))
        {
            throw new ArgumentException($""{ nameof(unhashedNameId)} does not match '{Constants.UnhashedNameIdRegex}'."", nameof(unhashedNameId));
        }

        using (var sha = new SHA256Managed())
        {
            byte[] textData = Encoding.UTF8.GetBytes(unhashedNameId);
            byte[] crypto = sha.ComputeHash(textData);

            var nameId = new StringBuilder();
            foreach (byte hash in crypto)
            {
                nameId.Append(hash.ToString(""x2"", CultureInfo.InvariantCulture));
            }

            return nameId.ToString();
        }
    }
}");
        }

        [Fact]
        public async Task Test_NullCfg_NoDiagnostic()
        {
            await VerifyCS.VerifyAnalyzerAsync(@"
using System;

public class TestClass
{
    public static string ContentName => ""Satya"";

    public static readonly byte[] ByteArray = Convert.FromBase64String(""Some strings."");
}");
        }
    }
}


text:
//---------------------------------------//

/**
 * The following function exposes the $decorated logger to allow the defaults to be overridden
 * @param $log - $log instance
 * @returns {*} - returns $log instance fitted for external configurations and regular use
 */
var exposeSafeLog = function ($log) {
  return createLogObj($log, allowedMethods);
};


text:
package org.mifos.framework.components.audit.util.helpers;

import java.util.Locale;

import org.mifos.framework.struts.tags.MifosTagUtils;
import org.mifos.framework.util.helpers.DateUtils;

public class AuditLogView {

    private String date;
    private String field;
    private String oldValue;
    private String newValue;
    private String user;
    private Locale mfiLocale;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getMfiDate() {
        // return DateUtils.getUserLocaleDate(getMfiLocale(),
        // getDate().toString());
        return DateUtils.getUserLocaleDate(getDate().toString());
    }

    public Locale getMfiLocale() {
        return mfiLocale;
    }

    public void setMfiLocale(Locale mfiLocale) {
        this.mfiLocale = mfiLocale;
    }

    public String getNewValue() {
        return MifosTagUtils.xmlEscape(newValue);
    }

    public void setNewValue(String newValue) {
        this.newValue = newValue;
    }

    public String getOldValue() {
        return MifosTagUtils.xmlEscape(oldValue);
    }

    public void setOldValue(String oldValue) {
        this.oldValue = oldValue;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

}