text:
'use strict';

const pubsub = require('pubsub-js');
const _ = require('lodash');
const Promise = require('bluebird');
const eventmesh = require('../../../data-access-layer/eventmesh');
const CONST = require('../../../common/constants');
const logger = require('../../../common/logger');
const lockManager = eventmesh.lockManager;
const errors = require('../../../common/errors');
const NotFound = errors.NotFound;

class UnlockResourcePoller {
  static start() {
    function poller(object, intervalId) {
      //TODO-PR - instead of a poller, its better to convert this to a watcher.
      const lockDetails = JSON.parse(object.spec.options);
      return eventmesh.apiServerClient.getResourceState({
          resourceGroup: lockDetails.lockedResourceDetails.resourceGroup,
          resourceType: lockDetails.lockedResourceDetails.resourceType,
          resourceId: lockDetails.lockedResourceDetails.resourceId
        })
        .then(resourceState => {
          logger.debug(`[Unlock Poller] Got resource ${lockDetails.lockedResourceDetails.resourceId} state of ${lockDetails.lockedResourceDetails.operation}` +
            ` operation for deployment ${object.metadata.name} as`, resourceState);
          //TODO-PR - re use util method is operationCompleted.
          if (_.includes([
              CONST.APISERVER.RESOURCE_STATE.SUCCEEDED,
              CONST.APISERVER.RESOURCE_STATE.FAILED,
              CONST.APISERVER.RESOURCE_STATE.DELETE_FAILED,
              CONST.APISERVER.RESOURCE_STATE.ABORTED
            ], resourceState)) {
            return lockManager.unlock(object.metadata.name, object.metadata.resourceVersion)
              .then(() => UnlockResourcePoller.clearPoller(object.metadata.name, intervalId));
          }
        })
        .catch(NotFound, err => {
          logger.info('Resource not found : ', err);
          return lockManager.unlock(object.metadata.name, object.metadata.resourceVersion)
            .then(() => UnlockResourcePoller.clearPoller(object.metadata.name, intervalId));
        });
    }
    /*
    Starts poller whenever a lock resource is created.
    Polling for only backup operations
    */

    function startPoller(event) {
      logger.debug('Received Lock Event: ', event);
      if (event.type === CONST.API_SERVER.WATCH_EVENT.ADDED || event.type === CONST.API_SERVER.WATCH_EVENT.MODIFIED) {
        UnlockResourcePoller.clearPoller(event.object.metadata.name, UnlockResourcePoller.pollers[event.object.metadata.name]);
        // Start poller only if lockTTL is not expired
        const lockDetails = JSON.parse(_.get(event.object, 'spec.options'));
        const currentTime = new Date();
        const lockTTL = lockManager.getLockTTL(lockDetails.lockedResourceDetails.operation);
        const lockTime = new Date(lockDetails.lockTime);
        if ((currentTime - lockTime) < lockTTL) {
          logger.debug('starting unlock resource poller for deployment', event.object.metadata.name);
          //TODO-PR - its better to convert this to a generic unlocker, which unlocks all types of resources.
          // It can watch on all resources which have completed their operation whose state can be 'Done' and post unlocking it can update it as 'Completed'.
          const intervalId = setInterval(() => poller(event.object, intervalId), CONST.UNLOCK_RESOURCE_POLLER_INTERVAL);
          UnlockResourcePoller.pollers[event.object.metadata.name] = intervalId;
        }
      }
    }
    // Get events for all the resource changes which have state as either undefined or locked (ie. state != unlocked)
    const queryString = `state notin (${CONST.APISERVER.RESOURCE_STATE.UNLOCKED})`;
    return eventmesh.apiServerClient.registerWatcher(CONST.APISERVER.RESOURCE_GROUPS.LOCK, CONST.APISERVER.RESOURCE_TYPES.DEPLOYMENT_LOCKS, startPoller, queryString)
      .then(stream => {
        logger.debug(`Successfully set watcher on resource group ${CONST.APISERVER.RESOURCE_GROUPS.LOCK} and resource ${CONST.APISERVER.RESOURCE_TYPES.DEPLOYMENT_LOCKS}`);
        return Promise
          .delay(CONST.APISERVER.WATCHER_REFRESH_INTERVAL)
          .then(() => {
            logger.debug(`Refreshing stream after ${CONST.APISERVER.WATCHER_REFRESH_INTERVAL}`);
            stream.abort();
            return this.start();
          });
      })
      .catch(e => {
        logger.error(`Error occured in registerWatcher:`, e);
        return Promise
          .delay(CONST.APISERVER.WATCHER_ERROR_DELAY)
          .then(() => {
            logger.debug(`Refreshing stream after ${CONST.APISERVER.WATCHER_ERROR_DELAY}`);
            return this.start();
          });
      });
  }
  static clearPoller(resourceId, intervalId) {
    logger.debug(`Clearing unlock interval for deployment`, resourceId);
    if (intervalId) {
      clearInterval(intervalId);
    }
    _.unset(UnlockResourcePoller.pollers, resourceId);
  }
}

UnlockResourcePoller.pollers = {};
pubsub.subscribe(CONST.TOPIC.APP_STARTUP, (eventName, eventInfo) => {
  logger.debug('-> Received event ->', eventName);
  if (eventInfo.type === 'internal') {
    return eventmesh.apiServerClient.registerCrds(CONST.APISERVER.RESOURCE_GROUPS.LOCK, CONST.APISERVER.RESOURCE_TYPES.DEPLOYMENT_LOCKS)
      .then(() => UnlockResourcePoller.start());
  }
});
module.exports = UnlockResourcePoller;


text:
package com.xem.mzbcustomerapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;

import com.xem.mzbcustomerapp.R;
import com.xem.mzbcustomerapp.base.BaseActivity;
import com.xem.mzbcustomerapp.view.TitleBuilder;

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

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by xuebing on 15/10/30.
 */
public class WebviewAty extends BaseActivity{

    @InjectView(R.id.titlebar_iv_left)
    ImageView back;
    @InjectView(R.id.webView)
    WebView myWebview;

    @Override
    protected void initView() {
        setContentView(R.layout.notification_aty);
        ButterKnife.inject(this);
        new TitleBuilder(this).setTitleText("美之伴").setLeftImage(R.mipmap.top_view_back);
        Intent intent = getIntent();

        if (null != intent) {
            Bundle bundle = getIntent().getExtras();

            String content = bundle.getString("extra");
            try {
                JSONObject object = new JSONObject(content);

                if (object.length() != 0) {
                    String url = object.getString("url");
                    myWebview.loadUrl(url);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //启用支持javascript
        WebSettings settings = myWebview.getSettings();
        settings.setJavaScriptEnabled(true);

    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.titlebar_iv_left})
    public void Ondo(View v) {
        switch (v.getId()) {
            case R.id.titlebar_iv_left:
//                intent2Aty(E0_InfoAty.class);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            intent2Aty(E0_InfoAty.class);
            finish();
            return true;
        }
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Samlr
  module Tools
    module Timestamp

      # Generate a current timestamp in ISO8601 format
      def self.stamp(time = Time.now)
        time.utc.iso8601
      end

      def self.parse(value)
        Time.iso8601(value)
      end

      # Is the current time on or after the given time?
      def self.not_on_or_after?(time)
        Time.now.to_i <= (time.to_i + Samlr.jitter.to_i)
      end

      # True when the current time is not before the given time
      def self.not_before?(time)
        Time.now.to_i >= (time.to_i - Samlr.jitter.to_i)
      end

    end
  end
end


text:
local

if fs.exists("AUTONOMUS/AI/data/pos") then
    os.loadAPI("AUTONOMUS/AI/data/pos")
else
    pos = {
        x = 0,
        y = 0,
        z = 0,
        direction = 1
    }
end

oldUp = turtle.up
oldDown = turtle.down
oldForward = turtle.forward
oldBack = turtle.back
oldLeft = turtle.turnLeft
oldRight = turtle.turnRight

local update = function()
    pos

turtle.up = function()
    oldUp()
    pos.y = pos.y + 1
end


text:
using System;
using System.Linq;

namespace Flood.GUI.Controls
{
    /// <summary>
    /// Radio button group.
    /// </summary>
    public class RadioButtonGroup : GroupBox
    {
        private LabeledRadioButton m_Selected;

        /// <summary>
        /// Selected radio button.
        /// </summary>
        public LabeledRadioButton Selected { get { return m_Selected; } }

        /// <summary>
        /// Internal name of the selected radio button.
        /// </summary>
        public String SelectedName { get { return m_Selected.Name; } }

        /// <summary>
        /// Text of the selected radio button.
        /// </summary>
        public String SelectedLabel { get { return m_Selected.Text; } }

        /// <summary>
        /// Index of the selected radio button.
        /// </summary>
        public int SelectedIndex { get { return Children.IndexOf(m_Selected); } }

        /// <summary>
        /// Invoked when the selected option has changed.
        /// </summary>
        public event GwenEventHandler SelectionChanged;

        /// <summary>
        /// Initializes a new instance of the <see cref="RadioButtonGroup"/> class.
        /// </summary>
        /// <param name="parent">Parent control.</param>
        /// <param name="label">Label for the outlining GroupBox.</param>
        public RadioButtonGroup(Control parent, String label)
            : base(parent)
        {
            IsTabable = false;
            KeyboardInputEnabled = true;
            Text = label;
            AutoSizeToContents = true;
        }

        /// <summary>
        /// Adds a new option.
        /// </summary>
        /// <param name="text">Option text.</param>
        /// <returns>Newly created control.</returns>
        public virtual LabeledRadioButton AddOption(String text)
        {
            return AddOption(text, String.Empty);
        }

        /// <summary>
        /// Adds a new option.
        /// </summary>
        /// <param name="text">Option text.</param>
        /// <param name="optionName">Internal name.</param>
        /// <returns>Newly created control.</returns>
        public virtual LabeledRadioButton AddOption(String text, String optionName)
        {
            LabeledRadioButton lrb = new LabeledRadioButton(this);
            lrb.Name = optionName;
            lrb.Text = text;
            lrb.RadioButton.Checked += OnRadioClicked;
            lrb.Dock = Pos.Top;
            lrb.Margin = new Margin(0, 0, 0, 1); // 1 bottom
            lrb.KeyboardInputEnabled = false; // todo: true?
            lrb.IsTabable = true;

            Invalidate();
            return lrb;
        }

        /// <summary>
        /// Handler for the option change.
        /// </summary>
        /// <param name="fromPanel">Event source.</param>
        protected virtual void OnRadioClicked(Control fromPanel)
        {
            RadioButton @checked = fromPanel as RadioButton;
            foreach (LabeledRadioButton rb in Children.OfType<LabeledRadioButton>()) // todo: optimize
            {
                if (rb.RadioButton == @checked)
                    m_Selected = rb;
                else
                    rb.RadioButton.IsChecked = false;
            }

            OnChanged();
        }
        /*
        /// <summary>
        /// Sizes to contents.
        /// </summary>
        public override void SizeToContents()
        {
            RecurseLayout(Skin); // options are docked so positions are not updated until layout runs
            //base.SizeToContents();
            int width = 0;
            int height = 0;
            foreach (Base child in Children)
            {
                width = Math.Max(child.Width, width);
                height += child.Height;
            }
            SetSize(width, height);
            InvalidateParent();
        }
        */
        protected virtual void OnChanged()
        {
            if (SelectionChanged != null)
                SelectionChanged.Invoke(this);
        }

        /// <summary>
        /// Selects the specified option.
        /// </summary>
        /// <param name="index">Option to select.</param>
        public void SetSelection(int index)
        {
            if (index < 0 || index >= Children.Count)
                return;

            (Children[index] as LabeledRadioButton).RadioButton.Press();
        }
    }
}


text:
// Copyright 2018, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Florian Kramer (florian.kramer@mail.uni-freiburg.de)

#include <gtest/gtest.h>
#include <cstdio>
#include "../src/engine/CallFixedSize.h"
#include "../src/engine/GroupBy.h"

// This fixture is used to create an Index for the tests.
// The full index creation is required for initialization of the vocabularies.
class GroupByTest : public ::testing::Test {
 public:
  GroupByTest() {
    // Create the index. The full index creation is run here to allow for
    // loading a docsDb file, which is not otherwise accessible
    std::string docsFileContent = "0\tExert 1\n1\tExert 2\n2\tExert3";
    std::string wordsFileContent =
        "Exert\t0\t0\t0\n"
        "1\t0\t0\t0\n"
        "Exert\t1\t0\t0\n"
        "2\t1\t0\t0\n"
        "Exert\t2\t0\t0\n"
        "3\t2\t0\t0\n";
    std::string ntFileContent = "<a>\t<b>\t<c>\t.";
    ad_utility::File docsFile("group_by_test.documents", "w");
    ad_utility::File wordsFile("group_by_test.words", "w");
    ad_utility::File ntFile("group_by_test.nt", "w");
    docsFile.write(docsFileContent.c_str(), docsFileContent.size());
    wordsFile.write(wordsFileContent.c_str(), wordsFileContent.size());
    ntFile.write(ntFileContent.c_str(), ntFileContent.size());
    docsFile.close();
    wordsFile.close();
    ntFile.close();
    try {
      _index.setKbName("group_by_test");
      _index.setTextName("group_by_test");
      _index.setOnDiskBase("group_ty_test");
      _index.createFromFile<NTriplesParser>("group_by_test.nt");
      _index.addTextFromContextFile("group_by_test.words");
      _index.buildDocsDB("group_by_test.documents");

      _index.addTextFromOnDiskIndex();
    } catch (const ad_semsearch::Exception& e) {
      std::cout << "semsearch exception: " << e.getErrorMessage()
                << e.getErrorDetails() << std::endl;
    } catch (std::exception& e) {
      std::cout << "std exception" << e.what() << std::endl;
    }
  }

  virtual ~GroupByTest() {
    // delete all files created during index creation
    std::remove("group_by_test.documents");
    std::remove("group_by_test.words");
    std::remove("group_by_test.text.vocabulary");
    std::remove("group_by_test.vocabulary");
    std::remove("group_by_test.text.index");
    std::remove("group_by_test.text.docsDB");
    std::remove("group_by_test.index.pso");
    std::remove("group_by_test.index.pos");
    std::remove("group_by_test.nt");
  }

  Index _index;
};

TEST_F(GroupByTest, doGroupBy) {
  using std::string;
  using std::vector;

  // There are 7 different aggregates, of which 5 (all apart from SAMPLE and
  // COUNT) react different to the 5 different ResultTypes.

  Id floatBuffers[3];
  float floatValues[3] = {-3, 2, 1231};
  for (int i = 0; i < 3; i++) {
    std::memcpy(&floatBuffers[i], &floatValues[i], sizeof(float));
  }

  // add some words to the index's vocabulary
  Vocabulary<CompressedString>& vocab =
      const_cast<Vocabulary<CompressedString>&>(_index.getVocab());
  vocab.push_back("<entity1>");
  vocab.push_back("<entity2>");
  vocab.push_back("<entity3>");
  vocab.push_back(ad_utility::convertFloatStringToIndexWord("1.1231"));
  vocab.push_back(ad_utility::convertFloatStringToIndexWord("-5"));
  vocab.push_back(ad_utility::convertFloatStringToIndexWord("17"));

  // create an input result table with a local vocabulary
  ResultTable inTable;
  inTable._localVocab->push_back("<local1>");
  inTable._localVocab->push_back("<local2>");
  inTable._localVocab->push_back("<local3>");

  IdTable inputData(6);
  // The input data types are
  //                   KB, KB, VERBATIM, TEXT, FLOAT,           STRING
  inputData.push_back({1, 4, 123, 0, floatBuffers[0], 0});
  inputData.push_back({1, 5, 0, 1, floatBuffers[1], 1});

  inputData.push_back({2, 6, 41223, 2, floatBuffers[2], 2});
  inputData.push_back({2, 7, 123, 0, floatBuffers[0], 0});
  inputData.push_back({2, 7, 123, 0, floatBuffers[0], 0});

  inputData.push_back({3, 8, 0, 1, floatBuffers[1], 1});
  inputData.push_back({3, 9, 41223, 2, floatBuffers[2], 2});

  std::vector<ResultTable::ResultType> inputTypes = {
      ResultTable::ResultType::KB,       ResultTable::ResultType::KB,
      ResultTable::ResultType::VERBATIM, ResultTable::ResultType::TEXT,
      ResultTable::ResultType::FLOAT,    ResultTable::ResultType::LOCAL_VOCAB};

  /*
    COUNT,
    GROUP_CONCAT,
    FIRST,
    LAST,
    SAMPLE,
    MIN,
    MAX,
    SUM,
    AVG
   */

  std::vector<size_t> groupByCols = {0};
  std::string delim1(", ");
  std::vector<GroupBy::Aggregate> aggregates = {
      // type                                in out userdata
      {GroupBy::AggregateType::COUNT, 1, 1, nullptr},

      {GroupBy::AggregateType::GROUP_CONCAT, 1, 2, &delim1},
      {GroupBy::AggregateType::GROUP_CONCAT, 2, 3, &delim1},
      {GroupBy::AggregateType::GROUP_CONCAT, 3, 4, &delim1},
      {GroupBy::AggregateType::GROUP_CONCAT, 4, 5, &delim1},
      {GroupBy::AggregateType::GROUP_CONCAT, 5, 6, &delim1},

      {GroupBy::AggregateType::SAMPLE, 1, 7, nullptr},

      {GroupBy::AggregateType::MIN, 1, 8, nullptr},
      {GroupBy::AggregateType::MIN, 2, 9, nullptr},
      {GroupBy::AggregateType::MIN, 3, 10, nullptr},
      {GroupBy::AggregateType::MIN, 4, 11, nullptr},

      {GroupBy::AggregateType::MAX, 1, 12, nullptr},
      {GroupBy::AggregateType::MAX, 2, 13, nullptr},
      {GroupBy::AggregateType::MAX, 3, 14, nullptr},
      {GroupBy::AggregateType::MAX, 4, 15, nullptr},

      {GroupBy::AggregateType::SUM, 1, 16, nullptr},
      {GroupBy::AggregateType::SUM, 2, 17, nullptr},
      {GroupBy::AggregateType::SUM, 3, 18, nullptr},
      {GroupBy::AggregateType::SUM, 4, 19, nullptr},

      {GroupBy::AggregateType::AVG, 1, 20, nullptr},
      {GroupBy::AggregateType::AVG, 2, 21, nullptr},
      {GroupBy::AggregateType::AVG, 3, 22, nullptr},
      {GroupBy::AggregateType::AVG, 4, 23, nullptr}};

  ResultTable outTable;

  // This is normally done when calling computeResult in the GroupBy
  // operation.
  outTable._data.setCols(24);

  int inWidth = inputData.cols();
  int outWidth = outTable._data.cols();
  CALL_FIXED_SIZE_2(inWidth, outWidth, doGroupBy, inputData, inputTypes,
                    groupByCols, aggregates, &outTable._data, &inTable,
                    &outTable, this->_index);

  ASSERT_EQ(3u, outTable._data.size());

  ASSERT_EQ(24u, outTable._data[0].size());
  ASSERT_EQ(24u, outTable._data[1].size());
  ASSERT_EQ(24u, outTable._data[2].size());

  // COUNT CHECKS
  ASSERT_EQ(2u, outTable._data[0][1]);
  ASSERT_EQ(3u, outTable._data[1][1]);
  ASSERT_EQ(2u, outTable._data[2][1]);

  // GROUP CONCAT CHECKS
  // check that the local vocab ids are ascending
  for (int i = 0; i < 5; i++) {
    ASSERT_EQ(0u + i, outTable._data[0][2 + i]);
    ASSERT_EQ(0u + i + 5, outTable._data[1][2 + i]);
    ASSERT_EQ(0u + i + 10, outTable._data[2][2 + i]);
  }
  // check for a local vocab entry for each of the 5 input cols
  ASSERT_EQ(std::string("<entity1>, <entity2>"), (*outTable._localVocab)[0]);
  ASSERT_EQ(std::string("123, 0"), (*outTable._localVocab)[1]);
  ASSERT_EQ(std::string("Exert 1, Exert 2"), (*outTable._localVocab)[2]);
  std::ostringstream groupConcatFloatString;
  groupConcatFloatString << floatValues[0] << ", " << floatValues[1];
  ASSERT_EQ(groupConcatFloatString.str(), (*outTable._localVocab)[3]);
  ASSERT_EQ(std::string("<local1>, <local2>"), (*outTable._localVocab)[4]);

  // SAMPLE CHECKS
  ASSERT_EQ(5u, outTable._data[0][7]);
  ASSERT_EQ(7u, outTable._data[1][7]);
  ASSERT_EQ(9u, outTable._data[2][7]);

  // MIN CHECKS
  float buffer;
  ASSERT_EQ(4u, outTable._data[0][8]);
  ASSERT_EQ(6u, outTable._data[1][8]);
  ASSERT_EQ(8u, outTable._data[2][8]);

  ASSERT_EQ(0u, outTable._data[0][9]);
  ASSERT_EQ(123u, outTable._data[1][9]);
  ASSERT_EQ(0u, outTable._data[2][9]);

  ASSERT_EQ(ID_NO_VALUE, outTable._data[0][10]);
  ASSERT_EQ(ID_NO_VALUE, outTable._data[1][10]);
  ASSERT_EQ(ID_NO_VALUE, outTable._data[2][10]);

  std::memcpy(&buffer, &outTable._data[0][11], sizeof(float));
  ASSERT_FLOAT_EQ(-3, buffer);
  std::memcpy(&buffer, &outTable._data[1][11], sizeof(float));
  ASSERT_FLOAT_EQ(-3, buffer);
  std::memcpy(&buffer, &outTable._data[2][11], sizeof(float));
  ASSERT_FLOAT_EQ(2, buffer);

  // MAX CHECKS
  ASSERT_EQ(5u, outTable._data[0][12]);
  ASSERT_EQ(7u, outTable._data[1][12]);
  ASSERT_EQ(9u, outTable._data[2][12]);

  ASSERT_EQ(123u, outTable._data[0][13]);
  ASSERT_EQ(41223u, outTable._data[1][13]);
  ASSERT_EQ(41223u, outTable._data[2][13]);

  ASSERT_EQ(ID_NO_VALUE, outTable._data[0][14]);
  ASSERT_EQ(ID_NO_VALUE, outTable._data[1][14]);
  ASSERT_EQ(ID_NO_VALUE, outTable._data[2][14]);

  std::memcpy(&buffer, &outTable._data[0][15], sizeof(float));
  ASSERT_FLOAT_EQ(2, buffer);
  std::memcpy(&buffer, &outTable._data[1][15], sizeof(float));
  ASSERT_FLOAT_EQ(1231, buffer);
  std::memcpy(&buffer, &outTable._data[2][15], sizeof(float));
  ASSERT_FLOAT_EQ(1231, buffer);

  // SUM CHECKS
  std::memcpy(&buffer, &outTable._data[0][16], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[1][16], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[2][16], sizeof(float));
  ASSERT_FLOAT_EQ(12, buffer);

  std::memcpy(&buffer, &outTable._data[0][17], sizeof(float));
  ASSERT_FLOAT_EQ(123, buffer);
  std::memcpy(&buffer, &outTable._data[1][17], sizeof(float));
  ASSERT_FLOAT_EQ(41469, buffer);
  std::memcpy(&buffer, &outTable._data[2][17], sizeof(float));
  ASSERT_FLOAT_EQ(41223, buffer);

  std::memcpy(&buffer, &outTable._data[0][18], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[1][18], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[2][18], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));

  std::memcpy(&buffer, &outTable._data[0][19], sizeof(float));
  ASSERT_FLOAT_EQ(-1, buffer);
  std::memcpy(&buffer, &outTable._data[1][19], sizeof(float));
  ASSERT_FLOAT_EQ(1225, buffer);
  std::memcpy(&buffer, &outTable._data[2][19], sizeof(float));
  ASSERT_FLOAT_EQ(1233, buffer);

  // AVG CHECKS
  std::memcpy(&buffer, &outTable._data[0][20], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[1][20], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[2][20], sizeof(float));
  ASSERT_FLOAT_EQ(6, buffer);

  std::memcpy(&buffer, &outTable._data[0][21], sizeof(float));
  ASSERT_FLOAT_EQ(61.5, buffer);
  std::memcpy(&buffer, &outTable._data[1][21], sizeof(float));
  ASSERT_FLOAT_EQ(13823, buffer);
  std::memcpy(&buffer, &outTable._data[2][21], sizeof(float));
  ASSERT_FLOAT_EQ(20611.5, buffer);

  std::memcpy(&buffer, &outTable._data[0][22], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[1][22], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));
  std::memcpy(&buffer, &outTable._data[2][22], sizeof(float));
  ASSERT_TRUE(std::isnan(buffer));

  std::memcpy(&buffer, &outTable._data[0][23], sizeof(float));
  ASSERT_FLOAT_EQ(-0.5, buffer);
  std::memcpy(&buffer, &outTable._data[1][23], sizeof(float));
  ASSERT_FLOAT_EQ(408.3333333333333, buffer);
  std::memcpy(&buffer, &outTable._data[2][23], sizeof(float));
  ASSERT_FLOAT_EQ(616.5, buffer);
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * DNS Library for handling lookups and updates.
 *
 * PHP Version 5
 *
 * Copyright (c) 2010, Mike Pultz <mike@mikepultz.com>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *   * Neither the name of Mike Pultz nor the names of his contributors
 *     may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @category  Networking
 * @package   Net_DNS2
 * @author    Mike Pultz <mike@mikepultz.com>
 * @copyright 2010 Mike Pultz <mike@mikepultz.com>
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version   SVN: $Id: Request.php 155 2012-05-06 23:45:23Z mike.pultz $
 * @link      http://pear.php.net/package/Net_DNS2
 * @since     File available since Release 0.6.0
 *
 */

/**
 * This class handles building new DNS request packets; packets used for DNS
 * queries and updates.
 *
 * @category Networking
 * @package  Net_DNS2
 * @author   Mike Pultz <mike@mikepultz.com>
 * @license  http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @link     http://pear.php.net/package/Net_DNS2
 * @see      Net_DNS2_Packet
 *
 */
class Net_DNS2_Packet_Request extends Net_DNS2_Packet
{
    /**
     * Constructor - builds a new Net_DNS2_Packet_Request object
     *
     * @param string $name  the domain name for the packet
     * @param string $type  the DNS RR type for the packet
     * @param string $class the DNS class for the packet
     *
     * @throws Net_DNS2_Exception
     * @access public
     *
     */
    public function __construct($name, $type = null, $class = null)
    {
        $this->set($name, $type, $class);
    }

    /**
     * builds a new Net_DNS2_Packet_Request object
     *
     * @param string $name  the domain name for the packet
     * @param string $type  the DNS RR type for the packet
     * @param string $class the DNS class for the packet
     *
     * @return boolean
     * @throws Net_DNS2_Exception
     * @access public
     *
     */
    public function set($name, $type = 'A', $class = 'IN')
    {
        //
        // generate a new header
        //
        $this->header = new Net_DNS2_Header;

        //
        // add a new question
        //
        $q = new Net_DNS2_Question();

        $name   = trim(strtolower($name), " \t\n\r\0\x0B.");
        $type   = strtoupper(trim($type));
        $class  = strtoupper(trim($class));

        //
        // check that the input string has some data in it
        //
        if (empty($name)) {

            throw new Net_DNS2_Exception(
                'empty query string provided',
                Net_DNS2_Lookups::E_PACKET_INVALID
            );
        }

        //
        // if the type is "*", rename it to "ANY"- both are acceptable.
        //
        if ($type == '*') {

            $type = 'ANY';
        }

        //
        // check that the type and class are valid
        //
        if (   (!isset(Net_DNS2_Lookups::$rr_types_by_name[$type]))
            || (!isset(Net_DNS2_Lookups::$classes_by_name[$class]))
        ) {
            throw new Net_DNS2_Exception(
                'invalid type (' . $type . ') or class (' . $class . ') specified.',
                Net_DNS2_Lookups::E_PACKET_INVALID
            );
        }

        //
        // if it's a PTR request for an IP address, then make sure we tack on
        // the arpa domain
        //
        if ($type == 'PTR') {

            if (Net_DNS2::isIPv4($name) == true) {

                //
                // IPv4
                //
                $name = implode('.', array_reverse(explode('.', $name)));
                $name .= '.in-addr.arpa';

            } else if (Net_DNS2::isIPv6($name) == true) {

                //
                // IPv6
                //
                $e = Net_DNS2::expandIPv6($name);
                if ($e !== false) {

                    $name = implode(
                        '.', array_reverse(str_split(str_replace(':', '', $e)))
                    );

                    $name .= '.ip6.arpa';

                } else {

                    throw new Net_DNS2_Exception(
                        'unsupported PTR value: ' . $name,
                        Net_DNS2_Lookups::E_PACKET_INVALID
                    );
                }

            } else if (preg_match('/arpa$/', $name) == true) {

                //
                // an already formatted IPv4 or IPv6 address in the arpa domain
                //

            } else {

                throw new Net_DNS2_Exception(
                    'unsupported PTR value: ' . $name,
                    Net_DNS2_Lookups::E_PACKET_INVALID
                );
            }
        }

        //
        // store the data
        //
        $q->qname           = $name;
        $q->qtype           = $type;
        $q->qclass          = $class;

        $this->question[]   = $q;

        //
        // the answer, authority and additional are empty; they can be modified
        // after the request is created for UPDATE requests if needed.
        //
        $this->answer       = array();
        $this->authority    = array();
        $this->additional   = array();

        return true;
    }
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */
?>


text:
package org.kie.services.remote.rest;

import static org.kie.services.remote.util.CommandsRequestUtil.processJaxbCommandsRequest;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.spi.BadRequestException;
import org.jbpm.kie.services.api.IdentityProvider;
import org.jbpm.services.task.commands.*;
import org.jbpm.services.task.impl.model.TaskImpl;
import org.jbpm.services.task.impl.model.xml.JaxbTask;
import org.jbpm.services.task.query.TaskSummaryImpl;
import org.kie.api.command.Command;
import org.kie.api.task.model.OrganizationalEntity;
import org.kie.api.task.model.Status;
import org.kie.api.task.model.Task;
import org.kie.api.task.model.TaskSummary;
import org.kie.services.client.serialization.jaxb.JaxbCommandsRequest;
import org.kie.services.client.serialization.jaxb.JaxbCommandsResponse;
import org.kie.services.client.serialization.jaxb.impl.JaxbTaskSummaryListResponse;
import org.kie.services.client.serialization.jaxb.rest.JaxbGenericResponse;
import org.kie.services.remote.cdi.ProcessRequestBean;
import org.kie.services.remote.util.Paginator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("/task")
@RequestScoped
public class TaskResource extends ResourceBase {

    private static final Logger logger = LoggerFactory.getLogger(RuntimeResource.class);

    @Inject
    private ProcessRequestBean processRequestBean;

    @Context
    private HttpServletRequest request;

    @Inject
    private IdentityProvider identityProvider;

    private static String[] allowedOperations = {
        "activate",
        "claim",
        "claimnextavailable",
        "complete",
        "delegate",
        "exit",
        "fail",
        "forward",
        "release",
        "resume",
        "skip",
        "start",
        "stop",
        "suspend",
        "nominate" };

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)
    @Path("/execute")
    public JaxbCommandsResponse execute(JaxbCommandsRequest cmdsRequest) {
        return processJaxbCommandsRequest(cmdsRequest, processRequestBean);
    }

    private static String [] allowedQueryParams = {
        "workItemId",
        "taskId",
        "businessAdministrator",
        "potentialOwner",
        "status",
        "taskOwner",
        "processInstanceId",
        "language"
    };

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("/query")
    public JaxbTaskSummaryListResponse query(@Context UriInfo uriInfo) {
        Map<String, List<String>> params = getRequestParams(request);

        List<Long> workItemIdList = getLongListParam(allowedQueryParams[0], false, params, "query", true);
        List<Long> taskIdList = getLongListParam(allowedQueryParams[1], false, params, "query", true);
        List<String> busAdminList = getStringListParam(allowedQueryParams[2], false, params, "query");
        List<String> potOwnList = getStringListParam(allowedQueryParams[3], false, params, "query");
        List<String> statusStrList = getStringListParam(allowedQueryParams[4], false, params, "query");
        List<String> taskOwnList = getStringListParam(allowedQueryParams[5], false, params, "query");
        List<Long> procInstIdList = getLongListParam(allowedQueryParams[6], false, params, "query", true);
        String language = getStringParam(allowedQueryParams[7], false, params, "query");
        for( String queryParam : params.keySet() ) {
            boolean allowed = false;
            for( String allowedParam : allowedQueryParams ) {
                if( allowedParam.equalsIgnoreCase(queryParam) ) {
                   allowed = true;
                   break;
                }
            }
            if( ! allowed ) {
                throw new BadRequestException(queryParam + " is an unknown and unsupported query param for the task query operation." );
            }
        }

        int [] pageInfo = getPageNumAndPageSize(params);
        Paginator<TaskSummaryImpl> paginator = new Paginator<TaskSummaryImpl>();

        /**
         * TODO: talk with Mauricio about new query command that accepts all of the above params?
        String andStr = getStringParam("and", false, params, "query");
        boolean and = false;
        if( andStr != null && Boolean.parseBoolean(andStr) ) {
            and = true;
        }
        */

        // clean up params
        if (language == null) {
            language = "en-UK";
        }
        List<Status> statusList = convertStringListToStatusList(statusStrList);

        // process params/cmds
        Queue<Command<?>> cmds = new LinkedList<Command<?>>();
        if (!workItemIdList.isEmpty()) {
            for (Long workItemId : workItemIdList) {
                cmds.add(new GetTaskByWorkItemIdCommand(workItemId));
            }
        }
        if (!taskIdList.isEmpty()) {
            for (Long taskId : taskIdList) {
                cmds.add(new GetTaskCommand(taskId));
            }
        }

        Set<TaskSummaryImpl> alreadyRetrievedSet = new HashSet<TaskSummaryImpl>();
        List<TaskSummaryImpl> results = new ArrayList<TaskSummaryImpl>();

        Command<?> cmd = null;
        while (!cmds.isEmpty()) {
            cmd = cmds.poll();
            TaskImpl task = (TaskImpl) processRequestBean.doTaskOperation(cmd);
            if (task != null) {
                TaskSummaryImpl taskSum = convertTaskToTaskSummary(task);
                if( alreadyRetrievedSet.add(taskSum) ) {
                    results.add(taskSum);
                }
            }
        }

        if( results.size() >= pageInfo[2] ) {
            results = paginator.paginate(pageInfo, results);
            return new JaxbTaskSummaryListResponse(results);
        }

        int assignments = 0;
        assignments += potOwnList.isEmpty() ? 0 : 1;
        assignments += busAdminList.isEmpty() ? 0 : 1;
        assignments += taskOwnList.isEmpty() ? 0 : 1;

        if (assignments == 0) {
            if (!procInstIdList.isEmpty()) {
                if (!statusList.isEmpty()) {
                    for (Long procInstId : procInstIdList) {
                        cmds.add(new GetTasksByStatusByProcessInstanceIdCommand(procInstId.longValue(), language, statusList));
                    }
                } else {
                    for (Long procInstId : procInstIdList) {
                        cmd = new GetTasksByProcessInstanceIdCommand(procInstId);
                        @SuppressWarnings("unchecked")
                        List<Long> procInstTaskIdList = (List<Long>) processRequestBean.doTaskOperation(cmd);
                        for (Long taskId : procInstTaskIdList) {
                            cmd = new GetTaskCommand(taskId);
                            TaskImpl task = (TaskImpl) processRequestBean.doTaskOperation(cmd);
                            if (task != null) {
                                TaskSummaryImpl taskSum = convertTaskToTaskSummary(task);
                                if( alreadyRetrievedSet.add(taskSum) ) {
                                    results.add(taskSum);
                                }
                            }
                        }
                        if( results.size() >= pageInfo[2] ) {
                            results = paginator.paginate(pageInfo, results);
                            return new JaxbTaskSummaryListResponse(results);
                        }
                    }
                }
            }
        } else {
            if (!busAdminList.isEmpty()) {
                for (String userId : busAdminList) {
                    cmds.add(new GetTaskAssignedAsBusinessAdminCommand(userId, language));
                }
            }
            if (!potOwnList.isEmpty()) {
                if (statusList.isEmpty()) {
                    for (String userId : potOwnList) {
                        cmds.add(new GetTaskAssignedAsPotentialOwnerCommand(userId, language));
                    }
                } else {
                    for (String userId : potOwnList) {
                        cmds.add(new GetTaskAssignedAsPotentialOwnerCommand(userId, language, statusList));
                    }

                }
            }
            if (!taskOwnList.isEmpty()) {
                if (statusList.isEmpty()) {
                    for (String userId : taskOwnList) {
                        cmds.add(new GetTasksOwnedCommand(userId, language));
                    }
                } else {
                    for (String userId : taskOwnList) {
                        cmds.add(new GetTasksOwnedCommand(userId, language, statusList));
                    }
                }
            }
        }

        while (!cmds.isEmpty()) {
            cmd = cmds.poll();
            @SuppressWarnings("unchecked")
            List<TaskSummary> taskSummaryList = (List<TaskSummary>) processRequestBean.doTaskOperation(cmd);
            if (taskSummaryList != null && !taskSummaryList.isEmpty()) {
                for (TaskSummary taskSummary : taskSummaryList) {
                    TaskSummaryImpl taskSum = (TaskSummaryImpl) taskSummary;
                    if( alreadyRetrievedSet.add(taskSum) ) {
                        results.add(taskSum);
                    }
                }
            }
            if( results.size() >= pageInfo[2] ) {
                results = paginator.paginate(pageInfo, results);
                return new JaxbTaskSummaryListResponse(results);
            }
        }

        results = paginator.paginate(pageInfo, results);
        return new JaxbTaskSummaryListResponse(results);
    }

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("/{id: [0-9-]+}")
    public JaxbTask getTaskInstanceInfo(@PathParam("id") long taskId) {
        Command<?> cmd = new GetTaskCommand(taskId);
        Task task = (Task) processRequestBean.doTaskOperation(cmd);
        return new JaxbTask(task);
    }

    @POST
    @Produces(MediaType.APPLICATION_XML)
    @Path("/{id: [0-9-]+}/{oper: [a-zA-Z]+}")
    public JaxbGenericResponse doTaskOperation(@PathParam("id") long taskId, @PathParam("oper") String operation) {
        Map<String, List<String>> params = getRequestParams(request);
        operation = checkThatOperationExists(operation, allowedOperations);
        String userId = identityProvider.getName();
        logger.debug("Executing " + operation + " on task " + taskId + " by user " + userId );

        Command<?> cmd = null;
        if ("activate".equalsIgnoreCase(operation)) {
            cmd = new ActivateTaskCommand(taskId, userId);
        } else if ("claim".equalsIgnoreCase(operation)) {
            cmd = new ClaimTaskCommand(taskId, userId);
        } else if ("claimnextavailable".equalsIgnoreCase(operation)) {
            String language = getStringParam("language", false, params, operation);
            if (language == null) {
                language = "en-UK";
            }
            cmd = new ClaimNextAvailableTaskCommand(userId, language);
        } else if ("complete".equalsIgnoreCase(operation)) {
            Map<String, Object> data = extractMapFromParams(params, operation);
            cmd = new CompleteTaskCommand(taskId, userId, data);
        } else if ("delegate".equalsIgnoreCase(operation)) {
            String targetEntityId = getStringParam("targetEntityId", true, params, operation);
            cmd = new DelegateTaskCommand(taskId, userId, targetEntityId);
        } else if ("exit".equalsIgnoreCase(operation)) {
            cmd = new ExitTaskCommand(taskId, userId);
        } else if ("fail".equalsIgnoreCase(operation)) {
            Map<String, Object> data = extractMapFromParams(params, operation);
            cmd = new FailTaskCommand(taskId, userId, data);
        } else if ("forward".equalsIgnoreCase(operation)) {
            String targetEntityId = getStringParam("targetEntityId", true, params, operation);
            cmd = new ForwardTaskCommand(taskId, userId, targetEntityId);
        } else if ("release".equalsIgnoreCase(operation)) {
            cmd = new ReleaseTaskCommand(taskId, userId);
        } else if ("resume".equalsIgnoreCase(operation)) {
            cmd = new ResumeTaskCommand(taskId, userId);
        } else if ("skip".equalsIgnoreCase(operation)) {
            cmd = new SkipTaskCommand(taskId, userId);
        } else if ("start".equalsIgnoreCase(operation)) {
            cmd = new StartTaskCommand(taskId, userId);
        } else if ("stop".equalsIgnoreCase(operation)) {
            cmd = new StopTaskCommand(taskId, userId);
        } else if ("suspend".equalsIgnoreCase(operation)) {
            cmd = new SuspendTaskCommand(taskId, userId);
        } else if ("nominate".equalsIgnoreCase(operation)) {
            List<OrganizationalEntity> potentialOwners = getOrganizationalEntityListFromParams(params);
            cmd = new NominateTaskCommand(taskId, userId, potentialOwners);
        } else {
            throw new BadRequestException("Unsupported operation: /task/" + taskId + "/" + operation);
        }
        processRequestBean.doTaskOperation(cmd);
        return new JaxbGenericResponse(request);
    }

}


text:
/**
 * @file
 * libcdio CD grabbing
 */

#include <cdio/cdda.h>
#include <cdio/paranoia.h>

#include "libavutil/log.h"
#include "libavutil/mem.h"
#include "libavutil/opt.h"

#include "libavformat/avformat.h"
#include "libavformat/internal.h"

/* cdio returns some malloced strings that need to be free()d */
#undef free

typedef struct CDIOContext {
    const AVClass       *class;
    cdrom_drive_t       *drive;
    cdrom_paranoia_t *paranoia;
    int32_t last_sector;

    /* private options */
    int speed;
    int paranoia_mode;
} CDIOContext;

static av_cold int read_header(AVFormatContext *ctx)
{
    CDIOContext *s = ctx->priv_data;
    AVStream *st;
    int ret, i;
    char *err = NULL;

    if (!(st = avformat_new_stream(ctx, NULL)))
        return AVERROR(ENOMEM);
    s->drive = cdio_cddap_identify(ctx->filename, CDDA_MESSAGE_LOGIT, &err);
    if (!s->drive) {
        av_log(ctx, AV_LOG_ERROR, "Could not open drive %s.\n", ctx->filename);
        return AVERROR(EINVAL);
    }
    if (err) {
        av_log(ctx, AV_LOG_VERBOSE, "%s\n", err);
        free(err);
    }
    if ((ret = cdio_cddap_open(s->drive)) < 0 || !s->drive->opened) {
        av_log(ctx, AV_LOG_ERROR, "Could not open disk in drive %s.\n", ctx->filename);
        return AVERROR(EINVAL);
    }

    cdio_cddap_verbose_set(s->drive, CDDA_MESSAGE_LOGIT, CDDA_MESSAGE_LOGIT);
    if (s->speed)
        cdio_cddap_speed_set(s->drive, s->speed);

    s->paranoia = cdio_paranoia_init(s->drive);
    if (!s->paranoia) {
        av_log(ctx, AV_LOG_ERROR, "Could not init paranoia.\n");
        return AVERROR(EINVAL);
    }
    cdio_paranoia_modeset(s->paranoia, s->paranoia_mode);

    st->codec->codec_type      = AVMEDIA_TYPE_AUDIO;
    if (s->drive->bigendianp)
        st->codec->codec_id    = CODEC_ID_PCM_S16BE;
    else
        st->codec->codec_id    = CODEC_ID_PCM_S16LE;
    st->codec->sample_rate     = 44100;
    st->codec->channels        = 2;
    if (s->drive->audio_last_sector != CDIO_INVALID_LSN &&
        s->drive->audio_first_sector != CDIO_INVALID_LSN)
        st->duration           = s->drive->audio_last_sector - s->drive->audio_first_sector;
    else if (s->drive->tracks)
        st->duration = s->drive->disc_toc[s->drive->tracks].dwStartSector;
    avpriv_set_pts_info(st, 64, CDIO_CD_FRAMESIZE_RAW, 2*st->codec->channels*st->codec->sample_rate);

    for (i = 0; i < s->drive->tracks; i++) {
        char title[16];
        snprintf(title, sizeof(title), "track %02d", s->drive->disc_toc[i].bTrack);
        avpriv_new_chapter(ctx, i, st->time_base, s->drive->disc_toc[i].dwStartSector,
                       s->drive->disc_toc[i+1].dwStartSector, title);
    }

    s->last_sector = cdio_cddap_disc_lastsector(s->drive);

    return 0;
}

static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
{
    CDIOContext *s = ctx->priv_data;
    int ret;
    uint16_t *buf;
    char *err = NULL;

    if (ctx->streams[0]->cur_dts > s->last_sector)
        return AVERROR_EOF;

    buf = cdio_paranoia_read(s->paranoia, NULL);
    if (!buf)
        return AVERROR_EOF;

    if (err = cdio_cddap_errors(s->drive)) {
        av_log(ctx, AV_LOG_ERROR, "%s\n", err);
        free(err);
        err = NULL;
    }
    if (err = cdio_cddap_messages(s->drive)) {
        av_log(ctx, AV_LOG_VERBOSE, "%s\n", err);
        free(err);
        err = NULL;
    }

    if ((ret = av_new_packet(pkt, CDIO_CD_FRAMESIZE_RAW)) < 0)
        return ret;
    memcpy(pkt->data, buf, CDIO_CD_FRAMESIZE_RAW);
    return 0;
}

static av_cold int read_close(AVFormatContext *ctx)
{
    CDIOContext *s = ctx->priv_data;
    cdio_paranoia_free(s->paranoia);
    cdio_cddap_close(s->drive);
    return 0;
}

static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp,
                     int flags)
{
    CDIOContext *s = ctx->priv_data;
    AVStream *st = ctx->streams[0];

    cdio_paranoia_seek(s->paranoia, timestamp, SEEK_SET);
    st->cur_dts = timestamp;
    return 0;
}

#define OFFSET(x) offsetof(CDIOContext, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM
static const AVOption options[] = {
    { "speed",              "Drive reading speed.", OFFSET(speed),         AV_OPT_TYPE_INT,   { 0 }, 0,       INT_MAX, DEC },
    { "paranoia_mode",      "Error recovery mode.", OFFSET(paranoia_mode), AV_OPT_TYPE_FLAGS, { 0 }, INT_MIN, INT_MAX, DEC, "paranoia_mode" },
        { "verify",         "Verify data integrity in overlap area", 0,    AV_OPT_TYPE_CONST, { PARANOIA_MODE_VERIFY },    0, 0, DEC, "paranoia_mode" },
        { "overlap",        "Perform overlapped reads.",             0,    AV_OPT_TYPE_CONST, { PARANOIA_MODE_OVERLAP },   0, 0, DEC, "paranoia_mode" },
        { "neverskip",      "Do not skip failed reads.",             0,    AV_OPT_TYPE_CONST, { PARANOIA_MODE_NEVERSKIP }, 0, 0, DEC, "paranoia_mode" },
    { NULL },
};

static const AVClass libcdio_class = {
    .class_name = "libcdio indev",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

AVInputFormat ff_libcdio_demuxer = {
    .name           = "libcdio",
    .read_header    = read_header,
    .read_packet    = read_packet,
    .read_close     = read_close,
    .read_seek      = read_seek,
    .priv_data_size = sizeof(CDIOContext),
    .flags          = AVFMT_NOFILE,
    .priv_class     = &libcdio_class,
};


text:
In the previous error concept it was very useful to generate macros as we often added new errors.
The code generation itself, however, was not ideal for cross compilation.

## Constraints

## Assumptions

- Error codes do not change very often

## Considered Alternatives

- Migrate to a more modern and easier way to generate code with our mustache system, and let this generate the (mapping) code for all compiled languages (C, C++, Java, Rust, Go).
  All we get out of this is the removal of `std::cout << ...` code from C++ but not much more.

- Migrate to CMake code that generates such macros/classes.
  Mustache templates have to be supplied with the input data somehow. Either we have to use a custom executable that is compiled at build time.
  In that case we would just get rid of the `std::cout << ...` in the C++ code, but not much else would change.
  The other option is to use the default mustache executable, which is a Ruby script and therefore requires Ruby to be installed.
  Also `kdb gen` cannot be reused, since that would require compiling kdb first, which needs kdberrors.h.

## Decision

Write down the few macros manually, and also manually write down exceptions for the language bindings (and also the mappings from Elektra's internal errors to nice errors specific for the languages).

Since error codes and crucial parts Elektra's core implementation will not often change this is the best approach with minimal effort.

The existing code will be refactored so that error macros directly call macros.

When adding a new error code, language bindings have to be adapted accordingly such as the Rust or Java Binding.

## Rationale

- Updates to error codes will imply syncing every binding.
  This though should happen in very rare circumstances.

## Implications

- The current bindings stay untouched.
- Tutorial on how to write a binding should be written.

## Related Decisions

## Notes

- See also [Issue #2814](https://issues.libelektra.org/2814)
- See also [Issue #2871](https://issues.libelektra.org/2871)


text:
package com.gu.management

import org.slf4j.Logger
import java.util.concurrent.Callable

class StopWatch {
  val startTime = System.currentTimeMillis
  def elapsed = System.currentTimeMillis - startTime
}

object Timing {

  def debug[T](logger: Logger, activity: String): (=> T) => T =
    time(activity, logger.debug, logger.debug, None)

  def debug[T](logger: Logger, activity: String, metric: TimingMetric): (=> T) => T =
    time(activity, logger.debug, logger.debug, Some(metric))

  def info[T](logger: Logger, activity: String): (=> T) => T =
    time(activity, logger.info, logger.info, None)

  def info[T](logger: Logger, activity: String, metric: TimingMetric): (=> T) => T =
    time(activity, logger.info, logger.info, Some(metric))

  def time[T](activity: String,
    onSuccess: String => Unit,
    onFailure: (String, Throwable) => Unit,
    metric: Option[TimingMetric])(block: => T): T = {
    val stopWatch = new StopWatch
    try {
      val result = block
      metric foreach (_.recordTimeSpent(stopWatch.elapsed))
      onSuccess(activity + " completed in " + stopWatch.elapsed + " ms")
      result
    } catch {
      case t: Throwable =>
        onFailure(activity + " caused exception after " + stopWatch.elapsed + " ms", t)
        throw t
    }
  }

  def debug[T](logger: Logger, activity: String, metric: TimingMetric, callable: Callable[T]): T =
    debug(logger, activity, metric)(callable.call())

  def info[T](logger: Logger, activity: String, metric: TimingMetric, callable: Callable[T]): T =
    info(logger, activity, metric)(callable.call())

  def debug(logger: Logger, activity: String, metric: TimingMetric, runnable: Runnable): Unit =
    debug(logger, activity, metric)(runnable.run())

  def info(logger: Logger, activity: String, metric: TimingMetric, runnable: Runnable): Unit =
    info(logger, activity, metric)(runnable.run())

  def debug[T](logger: Logger, activity: String, callable: Callable[T]): T =
    debug(logger, activity)(callable.call())

  def info[T](logger: Logger, activity: String, callable: Callable[T]): T =
    info(logger, activity)(callable.call())

  def debug(logger: Logger, activity: String, runnable: Runnable): Unit =
    debug(logger, activity)(runnable.run())

  def info(logger: Logger, activity: String, runnable: Runnable): Unit =
    info(logger, activity)(runnable.run())
}


text:
package org.ScripterRon.BitcoinMonitor;

import java.util.Date;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

/**
 * The SizedTable class is a JTable with column sizes based on the column data types
 */
public final class SizedTable extends JTable {

    /** Date column */
    public static final int DATE = 1;

    /** Integer column */
    public static final int INTEGER = 2;

    /** Block hash column */
    public static final int HASH = 3;

    /** Status column */
    public static final int STATUS = 4;

    /** IP address column */
    public static final int ADDRESS = 5;

    /** Subversion column */
    public static final int SUBVERSION = 6;

    /** Services column */
    public static final int SERVICES = 7;

    /** Name column */
    public static final int NAME = 8;

    /** Thread identifier column */
    public static final int TID = 9;

    /** Identity hash column */
    public static final int HID = 10;

    /** Count column */
    public static final int COUNT = 11;

    /** Block version */
    public static final int VERSION = 12;

    /**
     * Create a new sized table
     *
     * @param       tableModel      The table model
     * @param       columnTypes     Array of column types
     */
    public SizedTable(TableModel tableModel, int[] columnTypes) {
        //
        // Create the table
        //
        super(tableModel);
        //
        // Set the cell renderers and column widths
        //
        Component component;
        TableCellRenderer renderer;
        TableColumn column;
        TableColumnModel columnModel = getColumnModel();
        TableCellRenderer headRenderer = getTableHeader().getDefaultRenderer();
        if (headRenderer instanceof DefaultTableCellRenderer) {
            DefaultTableCellRenderer defaultRenderer = (DefaultTableCellRenderer)headRenderer;
            defaultRenderer.setHorizontalAlignment(JLabel.CENTER);
        }
        int columnCount = tableModel.getColumnCount();
        if (columnCount > columnTypes.length)
            throw new IllegalArgumentException("More columns than column types");
        for (int i=0; i<columnCount; i++) {
            Object value = null;
            column = columnModel.getColumn(i);
            switch (columnTypes[i]) {
                case DATE:
                    column.setCellRenderer(new DateRenderer());
                    value = new Date();
                    break;
                case INTEGER:                                       // 6 digits
                    value = "mmmmmn";
                    break;
                case HASH:                                          // 64 characters
                    column.setCellRenderer(new StringRenderer(JLabel.RIGHT));
                    value = "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn";
                    break;
                case STATUS:                                        // 16 character
                    column.setCellRenderer(new StringRenderer(JLabel.CENTER));
                    value = "Mmmmmmmmmmmmmmmm";
                    break;
                case ADDRESS:                                       // IP address
                    column.setCellRenderer(new StringRenderer(JLabel.RIGHT));
                    value = "[nnnn:nnnn:nnnn:nnnn:nnnn:nnnn:nnnn:nnnn]:nnnnn";
                    break;
                case SUBVERSION:                                    // 32 characters
                    column.setCellRenderer(new StringRenderer(JLabel.CENTER));
                    value = "Mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm";
                    break;
                case SERVICES:                                      // 24 characters
                    column.setCellRenderer(new StringRenderer(JLabel.CENTER));
                    value = "Mmmmmmmmmmmmmmmmmmmmmmmm";
                    break;
                case NAME:                                          // 32 characters
                    column.setCellRenderer(new StringRenderer(JLabel.RIGHT));
                    value = "Mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm";
                    break;
                case TID:                                           // 6 characters
                    value = "mmmmmn";
                    break;
                case HID:                                           // 9 characters
                    value = "mmmmmmmmm";
                    break;
                case COUNT:                                         // Numeric count
                    column.setCellRenderer(new CountRenderer());
                    value = 9999999999L;
                    break;
                case VERSION:                                       // 8 characters
                    column.setCellRenderer(new StringRenderer(JLabel.CENTER));
                    value = "xxxxxxxx";
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported column type "+columnTypes[i]);
            }
            component = headRenderer.getTableCellRendererComponent(this, tableModel.getColumnName(i),
                                                                   false, false, 0, i);
            int headWidth = component.getPreferredSize().width;
            renderer = column.getCellRenderer();
            if (renderer == null)
                renderer = getDefaultRenderer(tableModel.getColumnClass(i));
            component = renderer.getTableCellRendererComponent(this, value, false, false, 0, i);
            int cellWidth = component.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headWidth+10, cellWidth+30));
        }
        //
        // Resize all column proportionally
        //
        setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }
}


text:
package jvm.monitor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * created By vincent
 * Time: 02/09/2017 22:55
 */
public class OomObject {
  public byte[] placeholder = new byte[1024 * 64];

  public static void main(String[] args) throws InterruptedException {
    List<OomObject> list = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
      TimeUnit.MILLISECONDS.sleep(50);
      list.add(new OomObject());
    }
    System.gc();
  }
}


text:
namespace llvm {
class StringRef;

class ARMAttributeParser : public ELFAttributeParser {
  struct DisplayHandler {
    ARMBuildAttrs::AttrType attribute;
    Error (ARMAttributeParser::*routine)(ARMBuildAttrs::AttrType);
  };
  static const DisplayHandler displayRoutines[];

  Error handler(uint64_t tag, bool &handled) override;

  Error stringAttribute(ARMBuildAttrs::AttrType tag);

  Error CPU_arch(ARMBuildAttrs::AttrType tag);
  Error CPU_arch_profile(ARMBuildAttrs::AttrType tag);
  Error ARM_ISA_use(ARMBuildAttrs::AttrType tag);
  Error THUMB_ISA_use(ARMBuildAttrs::AttrType tag);
  Error FP_arch(ARMBuildAttrs::AttrType tag);
  Error WMMX_arch(ARMBuildAttrs::AttrType tag);
  Error Advanced_SIMD_arch(ARMBuildAttrs::AttrType tag);
  Error MVE_arch(ARMBuildAttrs::AttrType tag);
  Error PCS_config(ARMBuildAttrs::AttrType tag);
  Error ABI_PCS_R9_use(ARMBuildAttrs::AttrType tag);
  Error ABI_PCS_RW_data(ARMBuildAttrs::AttrType tag);
  Error ABI_PCS_RO_data(ARMBuildAttrs::AttrType tag);
  Error ABI_PCS_GOT_use(ARMBuildAttrs::AttrType tag);
  Error ABI_PCS_wchar_t(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_rounding(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_denormal(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_exceptions(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_user_exceptions(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_number_model(ARMBuildAttrs::AttrType tag);
  Error ABI_align_needed(ARMBuildAttrs::AttrType tag);
  Error ABI_align_preserved(ARMBuildAttrs::AttrType tag);
  Error ABI_enum_size(ARMBuildAttrs::AttrType tag);
  Error ABI_HardFP_use(ARMBuildAttrs::AttrType tag);
  Error ABI_VFP_args(ARMBuildAttrs::AttrType tag);
  Error ABI_WMMX_args(ARMBuildAttrs::AttrType tag);
  Error ABI_optimization_goals(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_optimization_goals(ARMBuildAttrs::AttrType tag);
  Error compatibility(ARMBuildAttrs::AttrType tag);
  Error CPU_unaligned_access(ARMBuildAttrs::AttrType tag);
  Error FP_HP_extension(ARMBuildAttrs::AttrType tag);
  Error ABI_FP_16bit_format(ARMBuildAttrs::AttrType tag);
  Error MPextension_use(ARMBuildAttrs::AttrType tag);
  Error DIV_use(ARMBuildAttrs::AttrType tag);
  Error DSP_extension(ARMBuildAttrs::AttrType tag);
  Error T2EE_use(ARMBuildAttrs::AttrType tag);
  Error Virtualization_use(ARMBuildAttrs::AttrType tag);
  Error nodefaults(ARMBuildAttrs::AttrType tag);

public:
  ARMAttributeParser(ScopedPrinter *sw)
      : ELFAttributeParser(sw, ARMBuildAttrs::ARMAttributeTags, "aeabi") {}
  ARMAttributeParser()
      : ELFAttributeParser(ARMBuildAttrs::ARMAttributeTags, "aeabi") {}
};
}

#endif


text:
<!DOCTYPE html>

<meta charset=utf-8>
<meta name=description content="LEAN Unit Test">
<meta name=viewport content=width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1>
<meta name=app-version content=0.0.1>
<meta name=app-support-native content=1>
<link rel="shortcut icon" href=data:;base64,iVBORw0KGgo=>
<title>LEAN: unit test</title>

Test result is in console panel


text:
try:
    import unittest2 as unittest
except ImportError:
    import unittest

import os

from cnab240 import errors
from cnab240.bancos import itau
from cnab240.tipos import Arquivo
from tests.data import get_itau_data_from_dict, get_itau_file_remessa, \
    ARQS_DIRPATH

class TestCnab240(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(TestCnab240, self).__init__(*args, **kwargs)
        self.maxDiff = None

    def setUp(self):
        self.itau_data = get_itau_data_from_dict()
        self.arquivo = Arquivo(itau, **self.itau_data['arquivo'])

    def test_unicode(self):
        self.arquivo.incluir_cobranca(**self.itau_data['cobranca'])
        self.assertEqual(str(self.arquivo), get_itau_file_remessa())

    def test_empty_data(self):
        arquivo = Arquivo(itau)
        self.assertRaises(errors.ArquivoVazioError, str, arquivo)

    def test_leitura_itau(self):
        return_file_path = os.path.join(ARQS_DIRPATH, 'cobranca.itau.ret')
        ret_file = open(return_file_path, "rt", encoding='ascii')
        arquivo = Arquivo(itau, arquivo=ret_file)

        ret_file.seek(0)
        self.assertEqual(ret_file.read(), str(arquivo))
        ret_file.close()

if __name__ == '__main__':
    unittest.main()


text:
'use strict';

var PageProperty = require('../modules/PageProperty');
var PagePropertyValidator = require('../validators/PagePropertyValidator');

class PagePropertyBuilder {

    constructor(obj) {
        this.helperName = obj && obj.helperName;
        this.validator = (obj && obj.validator) || new PagePropertyValidator({helperName: this.helperName});
    }

    build() {
        return new PageProperty({
            validator: this.validator,
            helperName: this.helperName
        });
    }

}

module.exports = PagePropertyBuilder;


text:
package jodd.madvoc;

import jodd.madvoc.component.RootPackages;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

class RootPackagesTest {

	@Test
	void testRootPackagesPackagePath() {
		RootPackages rootPackages = new RootPackages();

		rootPackages.addRootPackage("xx");
		rootPackages.addRootPackage("xx.admin.actions", "admin");
		rootPackages.addRootPackage("xx.cms.actions", "cms");

		for (int i = 0; i < 2; i++) {   // test cache
			assertEquals("", rootPackages.findPackagePathForActionPackage("xx"));
			assertEquals("/admin", rootPackages.findPackagePathForActionPackage("xx.admin.actions"));
			assertEquals("/admin/hey", rootPackages.findPackagePathForActionPackage("xx.admin.actions.hey"));
			assertEquals("/cms", rootPackages.findPackagePathForActionPackage("xx.cms.actions"));
			assertEquals("/cms/hay", rootPackages.findPackagePathForActionPackage("xx.cms.actions.hay"));
		}
	}

	@Test
	void testRootPackagesFindForPath() {
		RootPackages rootPackages = new RootPackages();

		rootPackages.addRootPackage("xx");
		rootPackages.addRootPackage("xx.admin.actions", "admin");
		rootPackages.addRootPackage("xx.cms.actions", "cms");

		assertEquals("xx", rootPackages.findRootPackageForActionPath("/foo"));
		assertEquals("xx.admin.actions", rootPackages.findRootPackageForActionPath("/admin"));
		assertEquals("xx.admin.actions", rootPackages.findRootPackageForActionPath("/admin/hey"));
		assertEquals("xx.cms.actions", rootPackages.findRootPackageForActionPath("/cms"));
		assertEquals("xx.cms.actions", rootPackages.findRootPackageForActionPath("/cms/hay"));
	}

	@Test
	void testDuplicateRootPackages() {
		RootPackages rootPackages = new RootPackages();
		rootPackages.addRootPackage("xx.zz", "foo");
		try {
			rootPackages.addRootPackage("xx.zz", "bar");
			fail("error");
		} catch (MadvocException ignore) {}
	}

}


text:
#ifndef DIMOFLT_H
#define DIMOFLT_H

#include "dcmtk/config/osconfig.h"
#include "dcmtk/ofstd/oftypes.h"
#include "dcmtk/ofstd/ofcast.h"

#include "dcmtk/dcmimgle/dimopxt.h"
#include "dcmtk/dcmimgle/diflipt.h"

/*---------------------*
 *  class declaration  *
 *---------------------*/

/** Template class to flip monochrome images (on pixel data level)
 *  horizontally and vertically
 */
template<class T>
class DiMonoFlipTemplate
  : public DiMonoPixelTemplate<T>,
    protected DiFlipTemplate<T>
{

 public:

    /** constructor
     *
     ** @param  pixel    pointer to intermediate pixel representation
     *  @param  columns  number of columns
     *  @param  rows     number of rows
     *  @param  frames   number of frames
     *  @param  horz     flip horizontally if true
     *  @param  vert     flip vertically if true
     */
    DiMonoFlipTemplate(const DiMonoPixel *pixel,
                       const Uint16 columns,
                       const Uint16 rows,
                       const Uint32 frames,
                       const int horz,
                       const int vert)
      : DiMonoPixelTemplate<T>(pixel, OFstatic_cast(unsigned long, columns) * OFstatic_cast(unsigned long, rows) * frames),
        DiFlipTemplate<T>(1, columns, rows, frames)
    {
        if ((pixel != NULL) && (pixel->getCount() > 0))
        {
            if (pixel->getCount() == OFstatic_cast(unsigned long, columns) * OFstatic_cast(unsigned long, rows) * frames)
                flip(OFstatic_cast(const T *, pixel->getData()), horz, vert);
            else {
                DCMIMGLE_WARN("could not flip image ... corrupted data");
            }
        }
    }

    /** destructor
     */
    ~DiMonoFlipTemplate()
    {
    }

 private:

    /** choose flipping algorithm depending on given parameters
     *
     ** @param  pixel  pointer to pixel data which should be flipped
     *  @param  horz   flip horizontally if true
     *  @param  vert   flip vertically if true
     */
    inline void flip(const T *pixel,
                     const int horz,
                     const int vert)
    {
        if (pixel != NULL)
        {
            this->Data = new T[this->getCount()];
            if (this->Data != NULL)
            {
                if (horz && vert)
                    this->flipHorzVert(&pixel, &this->Data);
                else if (horz)
                    this->flipHorz(&pixel, &this->Data);
                else if (vert)
                    this->flipVert(&pixel, &this->Data);
            }
        }
    }
};

#endif


text:
<?php return array(
	'contact'=>array('fr'=>'contact'),
	'contact_submit'=>array('fr'=>'contact_submit'),
);


text:
<?php

/**
 * News page and controller.
 *
 * NewsHolderPage
 *
 * @package News/blog module
 * @author Simon 'Sphere'
 * @property Boolean IsPrimary
 * @method News Newsitems() linked to this page (for Translatable)
 * @todo WHOAH! This thing is fat. Slim it down boy!
 * @todo besides the general getters, the news-functions should be in the model
 */
class NewsHolderPage extends Page
{
	/** @var string $description PageType's description */
	private static $description = 'HolderPage for newsitems';
	private static $db = array(
		'IsPrimary' => 'Boolean(false)',
	);

	/** @var array $many_many many-to-many relationships */
	private static $many_many = array(
		'Newsitems' => 'News'
	);

	/** @var array $allowed_children Allowed Children */
	private static $allowed_children = array(
		'News',
	);

	/**
	 * Create a default NewsHolderPage. This prevents error500 because of a missing page.
	 */
	public function requireDefaultRecords()
	{
		parent::requireDefaultRecords();
		if (NewsHolderPage::get()->count() == 0) {
			$page = NewsHolderPage::create();
			$page->Title = _t('NewsHolderPage.DEFAULTPAGETITLE', 'Newspage');
			$page->Content = '';
			$page->URLSegment = 'news';
			$page->Sort = 1;
			$page->Status = 'Published';
			$page->IsPrimary = true;
			$page->write();
			$page->publish('Stage', 'Live');
			$page->flushCache();
			DB::alteration_message('Newsholder Page created', 'created');
		} else {
			/** Migration is only possible, if the module is installed. We're assuming, this means there's at least one Holderpage. */
			$this->migrateUp();
		}
	}

	private function migrateUp()
	{
		$this->migratePublish();
		$this->migrateAuthors();
		$this->migratePages();
		$this->migrateOrphans();
	}

	/**
	 * Migrate the Publish feature form one of the first versions.
	 * This old version didn't work with PublishFrom but with Created.
	 * So, we update here, to set the PublishFrom to the Created value.
	 */
	private function migratePublish()
	{
		/** Backwards compatibility for upgraders. Update the PublishFrom field */
		$sql = "UPDATE `News` SET `PublishFrom` = `Created` WHERE `PublishFrom` IS NULL";
		DB::query($sql);
	}

	/**
	 * For each author, add an AuthorHelper
	 */
	private function migrateAuthors()
	{
		/** @var SQLQuery $query */
		$query = new SQLQuery();
		$query->setSelect('Author')
			->setFrom('News')
			->setDistinct(true);
		$authors = $query->execute();
		foreach ($authors as $author) {
			/** Create a new author if it doesn't exist */
			if (!$authorHelper = AuthorHelper::get()->filter(array('OriginalName' => trim($author['Author'])))->first()) {
				/** @var AuthorHelper $authorHelper */
				$authorHelper = AuthorHelper::create();
				$authorHelper->OriginalName = $author['Author'];
				$authorHelper->write();
			}
			$sql = "UPDATE `News` SET `AuthorHelperID` = '" . $authorHelper->ID . "' WHERE Author = '" . $author['Author'] . "'";
			DB::query($sql);
		}
	}

	/**
	 * This is to migrate existing newsitems to the new release with the new relational method.
	 * It is forward-non-destructive.
	 * Only run if there is a column NewsHolderPageID
	 * @todo This needs a rewrite, could be done with less queries with an add Items to Page instead of the current situation.
	 */
	private function migratePages()
	{
		$existquery = "SHOW COLUMNS FROM `News` LIKE 'NewsHolderPageID';";
		/** @var DB $exists */
		$exists = DB::query($existquery);
		if ($count = $exists->numRecords()) {
			/** @var SQLQuery $query */
			$query = new SQLQuery();
			$query->setSelect(array('ID', 'NewsHolderPageID'))
				->setFrom('News');
			$newsitems = $query->execute();
			foreach ($newsitems as $newsitem) {
				if ($newsitem['NewsHolderPageID'] && NewsHolderPage::get()->byID($newsitem['NewsHolderPageID'])) {
					News::get()
						->byID($newsitem['ID'])
						->NewsHolderPages()->add($newsitem['NewsHolderPageID']);
				}
			}
		}
	}

	/**
	 * Migrate orphanaged newsitems.
	 * @todo make this work as wished. As it's doing.... not so very much
	 */
	private function migrateOrphans()
	{

	}

	/**
	 * Support for children.
	 * Just call <% loop Children.Limit(x) %>$Title<% end_loop %> from your template to get the news-children.
	 * @return DataObjectSet NewsItems belonging to this page
	 */
	public function Children()
	{
		$now = SS_DateTime::now()->Format('Y-m-d');
		return $this->Newsitems()
			->filter(array('Live' => true))
			->exclude(array('PublishFrom:GreaterThan' => $now));
	}

}

class NewsHolderPage_Controller extends Page_Controller
{
	private static $allowed_actions = array(
		'show',
		'tag',
		'tags',
		'rss',
		'archive',
		'author',
		'CommentForm',
		'migrate',
		'latest',
	);
	private static $url_handlers = array();
	protected $current_item;
	protected $current_tag;
	protected $current_siteconfig;

	/**
	 * Setup the allowed actions to work with the SiteConfig settings.
	 * @param string $limitToClass
	 * @return array
	 */
	public function allowedActions($limitToClass = null)
	{
		$actions = parent::allowedActions($limitToClass);
		$defaultMapping = $this->stat('allowed_actions');
		$siteConfig = $this->getCurrentSiteConfig();
		foreach ($defaultMapping as $map) {
			$key = ucfirst($map . 'Action');
			if ($siteConfig->$key) {
				self::$allowed_actions[] = $siteConfig->$key;
			}
		}
		if (is_array($actions)) {
			return array_merge($actions, self::$allowed_actions);
		}
		return self::$allowed_actions;
	}

	/**
	 * Setup the handling of the actions. This is needed for the custom URL Actions set in the SiteConfig
	 * @param SS_Request $request The given request
	 * @param string $action The requested action
	 * @return parent::handleAction
	 */
	public function handleAction($request, $action)
	{
		$handles = parent::allowedActions(false);
		$defaultMapping = $this->stat('allowed_actions');
		$handles['index'] = 'handleIndex';
		$siteConfig = $this->getCurrentSiteConfig();
		foreach ($defaultMapping as $key) {
			$map = ucfirst($key . 'Action');
			if ($siteConfig->$map) {
				$handles[$siteConfig->$map] = $key;
			}
			if (!isset($handles[$key])) {
				$handles[$key] = $key;
			}
		}
		self::$url_handlers = $handles;
		$this->needsRedirect();
		return parent::handleAction($request, $handles[$action]);
	}

	/**
	 * Include the tagcloud scripts. Configure in newsmodule.js!
	 */
	public function init()
	{
		parent::init();
		// I would advice to put these in a combined file, but it works this way too.
		Requirements::javascript('silverstripe-newsmodule/javascript/jquery.tagcloud.js');
		Requirements::javascript('silverstripe-newsmodule/javascript/newsmodule.js');
	}

	/**
	 * Set the current newsitem, if available.
	 */
	private function setNews()
	{
		$Params = $this->getURLParams();
		/** @var array $segmentFilter Array containing the filter for current or any item */
		$segmentFilter = $this->setupFilter($Params);
		$news = $this->Newsitems()
			->filter($segmentFilter)
			->exclude(array('PublishFrom:GreaterThan' => SS_Datetime::now()->format('Y-m-d')))
			->first();
		$this->current_item = $news;
	}

	/**
	 * Get the current newsitem
	 * @return News The current newsitem
	 */
	public function getNews()
	{
		if (!$this->current_item) {
			$this->setNews();
		}
		return $this->current_item;
	}

	/**
	 * Set the current tag
	 */
	private function setTag()
	{
		$Params = $this->getURLParams();
		$tag = Tag::get()
			->filter(array('URLSegment' => Convert::raw2sql($Params['ID'])))->first();
		$this->current_tag = $tag;
	}

	/**
	 * Get the current tag.
	 * @todo Implement translations?
	 * @return Tag with tags or news.
	 */
	public function getTag()
	{
		if (!$this->current_tag) {
			$this->setTag();
		}
		return $this->current_tag;
	}

	/**
	 * Set the current SiteConfig
	 */
	private function setCurrentSiteConfig()
	{
		$this->current_siteconfig = SiteConfig::current_site_config();
	}

	/**
	 * Get the current SiteConfig
	 * @return SiteConfig
	 */
	public function getCurrentSiteConfig()
	{
		if (!$this->current_siteconfig) {
			$this->setCurrentSiteConfig();
		}
		return $this->current_siteconfig;
	}

	public function getCurrentAuthor()
	{
		$id = $this->getRequest()->param('ID');
		return AuthorHelper::get()->filter(array('URLSegment' => $id))->first();
	}

	/**
	 * This feature is cleaner for redirection.
	 * Saves requests to the database if I'm not mistaken.
	 * @return $this|null redirect to either the correct page/object or do nothing (In that case, the item exists and we're gonna show it lateron).
	 */
	private function needsRedirect()
	{
		/** @var int|string $id */
		$id = $this->getRequest()->param('ID');
		/** @var string $action */
		$action = $this->getRequest()->param('Action');
		/** @var array $handlers */
		$handlers = self::$url_handlers;
		if (isset($handlers[$action]) && $handlers[$action] == 'show' && !$news = $this->getNews()) {
			if ($id && is_numeric($id)) {
				/** @var News $redirect */
				$redirect = $this->Newsitems()->byId($id);
				$this->redirect($redirect->Link(), 301);
			} else {
				/** @var Renamed $renamed */
				$renamed = Renamed::get()->filter(array('OldLink' => $id));
				if ($renamed->count() > 0) {
					$this->redirect($renamed->First()->News()->Link(), 301);
				} else {
					$this->redirect($this->Link(), 404);
				}
			}
		} elseif ($action === 'latest') {
			/** @var News $item */
			$item = News::get()->filter(array('Live' => true))->first();
			$this->redirect($item->Link(), 302);
		}
	}

	/**
	 * Meta! This is so Meta! I mean, MetaTitle!
	 */
	public function MetaTitle()
	{
		$mapping = self::$url_handlers;
		if ($action = $this->getRequest()->param('Action')) {
			switch ($mapping[$action]) {
				case 'show' :
					$news = $this->getNews();
					if (isset($news))
					{
						$this->Title = $news->Title . ' - ' . $this->Title;
					}
					break;
				case 'tag' :
					$tags = $this->getTag();
					if (isset($tags))
					{
						$this->Title = $tags->Title . ' - ' . $this->Title;
					}
					break;
				case 'tags' :
					$this->Title = _t('News.ALLTAGS_PAGE', 'All tags - ') . $this->Title;
					break;
				case 'author' :
					$this->Title = _t('News.AUTHOR_PAGE', 'Items by ') . ucfirst($this->getRequest()->param('ID')) . ' - ' . $this->Title;
					break;
				case 'archive' :
					$this->Title = _t('News.ARCHIVE_PAGE', 'Items per period ') . $this->Title;
					break;
			}
		}
	}

	/**
	 * I should make this configurable from SiteTree?
	 * Generate an RSS-feed.
	 * @todo obey translatable.
	 * @return RSSFeed $rss RSS-feed output.
	 */
	public function rss()
	{
		$rss = RSSFeed::create(
			$list = $this->getRSSFeed(), $link = $this->Link('rss'), $title = _t('News.RSSFEED', 'News feed')
		);
		return $rss->outputToBrowser();
	}

	/**
	 * @todo make language-specific versions
	 * @return DataList $return with Newsitems
	 */
	public function getRSSFeed()
	{
		$return = $this->NewsItems()
			->filter(array('Live' => 1))
			->exclude(array('PublishFrom:GreaterThan' => SS_Datetime::now()->Rfc2822()))
			->limit(10);
		return $return;
	}

	/**
	 * Setup the filter for the getters. This keeps in mind if the user is allowed to view this item.
	 * @param String $params returntype setting.
	 * @return Array $filter filter for general getter.
	 */
	private function setupFilter($params)
	{
		$filter = array(
			'URLSegment'           => Convert::raw2sql($params['ID']),
			'Live'                 => 1,
		);
		if (Member::currentUserID() != 0 && !Permission::checkMember(Member::currentUserID(), array('VIEW_NEWS', 'CMS_ACCESS_NewsAdmin'))) {
			$filter['Live'] = 0;
		}
		return $filter;
	}

	/**
	 * @todo can this be made smaller? Would be nice!
	 * @return ArrayList $allEntries|$records The newsitems, sliced by the amount of length. Set to wished value
	 */
	public function allNews()
	{
		$siteConfig = $this->getCurrentSiteConfig();
		$exclude = array(
			'PublishFrom:GreaterThan' => SS_Datetime::now()->Format('Y-m-d'),
		);
		$filter = $this->generateAddedFilter();
		$allEntries = $this->Newsitems()
			->filter($filter)
			->exclude($exclude);
		/** Pagination pagination pagination. */
		if ($allEntries->count() > $siteConfig->PostsPerPage && $siteConfig->PostsPerPage > 0) {
			$records = PaginatedList::create($allEntries, $this->getRequest());
			$records->setPageLength($siteConfig->PostsPerPage);
			return $records;
		}
		return $allEntries;
	}

	/**
	 * @todo Make this language-specific
	 * @return Tag All tags in a list.
	 */
	public function allTags()
	{
		return Tag::get();
	}

	/**
	 * Get the items, per month/year/author
	 * If no month or year is set, current month/year is assumed
	 * @todo cleanup the month-method maybe?
	 * @return Array $filter Filtering for the allNews getter
	 */
	public function generateAddedFilter()
	{
		$mapping = self::$url_handlers;
		$params = $this->getURLParams();
		/** @var array $filter Generic/default filter */
		$filter = array(
			'Live' => 1,
		);
		if (isset($params['Action'])) {
			switch ($mapping[$params['Action']]) {
				/** Archive */
				case 'archive':
					if (!isset($params['ID'])) {
						$month = SS_DateTime::now()->Format('m');
						$year = SS_DateTime::now()->Format('Y');
					} elseif (!isset($params['OtherID']) && isset($params['ID'])) {
						$year = $params['ID'];
						$month = '';
					} else {
						$year = $params['ID'];
						$month = date_parse('01-' . $params['OtherID'] . '-1970');
						$month = str_pad((int)$month['month'], 2, "0", STR_PAD_LEFT);
					}
					$filter['PublishFrom:PartialMatch'] = $year . '-' . $month;
					break;
				/** Author */
				case 'author' :
					$filter['AuthorHelper.URLSegment:ExactMatch'] = $params['ID'];
					break;
			}
		}
		return $filter;
	}

	/**
	 * I'm tired of writing comments!
	 * @return form for Comments
	 */
	public function CommentForm()
	{
		$siteconfig = $this->getCurrentSiteConfig();
		$params = $this->getURLParams();
		return (CommentForm::create($this, 'CommentForm', $siteconfig, $params));
	}

}


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_BOOLEAN_FUNCTIONS_LOGICAL_NOTAND_HPP_INCLUDED
#define BOOST_SIMD_BOOLEAN_FUNCTIONS_LOGICAL_NOTAND_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>
#include <boost/proto/tags.hpp>

namespace boost { namespace simd
{
  namespace tag
  {
   /*!
     @brief logical_notand generic tag

     Represents the logical_notand function in generic contexts.

     @par Models:
        Hierarchy
   **/
    struct logical_notand_ : ext::elementwise_<logical_notand_>
    {
      /// @brief Parent hierarchy
      typedef ext::elementwise_<logical_notand_> parent;
    };
  }
  /*!
    return the logical and of the negation of the first parameter and the second parameter
    the result type is logical type associated to the first parameter

    @par Semantic:

    For every parameters of types respectively T0, T1:

    @code
    as_logical<T0> r = logical_notand(a0,a1);
    @endcode

    is similar to:

    @code
    as_logical<T0> r = !a0 && a1;
    @endcode

    @par Alias:
    @c l_notand

    @param a0

    @param a1

    @return a value of the logical type asssociated to the first parameter
  **/
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::logical_notand_      , logical_notand     , 2)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::logical_notand_      , l_notand           , 2)
} }

#include <boost/simd/operator/specific/common.hpp>

#endif


text:
<?php
class TmdWeather extends CI_Model
{
    var $access_token='';
    var $status_code;
	function __construct()
	{
		parent::__construct();
       // $this->load->library('guzzle');
        $this->load->config('tmd_weather');
		$this->access_token=$this->config->item('tmd_access_token');

	}
	function is_in_range_forecasts($date)
	{
        $headers=array();
        $url=$this->config->item('tmd_api_forecasts_range_date');
		// via header parameter
        $headers['authorization']='Bearer '.$this->access_token;
        $headers['accept']='application/json';

		$client = new GuzzleHttp\Client();

  		try{

                $response = $client->request('GET',$url , ['headers' =>$headers]);
				$this->status_code=$response->getStatusCode();
				$forecasts=json_decode($response->getBody()->getContents());
				$start_date=$forecasts->daily_data->min;
				$end_date=$forecasts->daily_data->max;
			//	print $start_date;
				//print_r($forecasts);
				$now = new DateTime($date);
				$startdate = new DateTime($start_date);
				$enddate = new DateTime($end_date);

				if($startdate <= $now && $now <= $enddate) {
					return TRUE;
				}else{
					return FALSE;
				}

		 } catch (GuzzleHttp\Exception\BadResponseException $e) {
			$this->status_code=400;
			$this->output->set_status_header($this->status_code);
		    $response = $e->getResponse();
			return json_decode($response->getBody()->getContents());
		  }
	}
    function getDailyFocecasts($date=null,$lat=null,$lon=null)
	{
		if($this->is_in_range_forecasts($date))
		{

			$headers=array();
			$url=$this->config->item('tmd_api_forecasts_locatin_based').'?fields=tc_max,cond,rain,rh&duration=1&date='.$date.'&lat='.$lat.'&lon='.$lon;
			// via header parameter
			$headers['authorization']='Bearer '.$this->access_token;
			$headers['accept']='application/json';

			$client = new GuzzleHttp\Client();

			try{

					$response = $client->request('GET',$url , ['headers' =>$headers]);
					$this->status_code=$response->getStatusCode();
					return json_decode($response->getBody()->getContents());

			} catch (GuzzleHttp\Exception\BadResponseException $e) {
				$this->status_code=400;
				$this->output->set_status_header($this->status_code);
				$response = $e->getResponse();
				return json_decode($response->getBody()->getContents());
			}
		}
		else return FALSE;
    }
}


text:
using System;

namespace Cumulus.Configuration.Settings
{
    public class HeartbeatIntervalSetting : Setting<TimeSpan>
    {
        public override TimeSpan Default
        {
            get { return TimeSpan.FromSeconds(30); }
        }
    }
}


text:
package org.apache.pdfbox.pdmodel.interactive.form;

import java.io.IOException;
import java.net.URL;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.io.RandomAccessReadBuffer;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 *
 * @author Tilman Hausherr
 */
class PDFieldTreeTest
{

    /**
     * PDFBOX-5044 stack overflow
     *
     * @throws IOException
     */
    @Test
    void test5044() throws IOException
    {
        String sourceUrl = "https://issues.apache.org/jira/secure/attachment/13016994/PDFBOX-4131-0.pdf";

        try (PDDocument doc = Loader.loadPDF(
                RandomAccessReadBuffer.createBufferFromStream(new URL(sourceUrl).openStream())))
        {
            PDDocumentCatalog catalog = doc.getDocumentCatalog();
            PDAcroForm acroForm = catalog.getAcroForm();
            int count = 0;
            for (PDField field : acroForm.getFieldTree())
            {
                ++count;
            }
            Assertions.assertEquals(4, count);
        }
    }
}


text:
using System.IO;

namespace NBitcoin.BouncyCastle.Asn1
{
    internal class DerSequenceGenerator
        : DerGenerator
    {
        private readonly MemoryStream _bOut = new MemoryStream();

        public DerSequenceGenerator(
            Stream outStream)
            : base(outStream)
        {
        }

        public DerSequenceGenerator(
            Stream outStream,
            int tagNo,
            bool isExplicit)
            : base(outStream, tagNo, isExplicit)
        {
        }

        public override void AddObject(
            Asn1Encodable obj)
        {
            new DerOutputStream(this._bOut).WriteObject(obj);
        }

        public override Stream GetRawOutputStream()
        {
            return this._bOut;
        }

        public override void Close()
        {
            WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Sequence, this._bOut.ToArray());
        }
    }
}


text:
#pragma once
#include <aws/s3/S3_EXPORTS.h>
#include <aws/s3/S3Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/s3/model/BucketLifecycleConfiguration.h>

namespace Aws
{
namespace S3
{
namespace Model
{

  /**
   */
  class AWS_S3_API PutBucketLifecycleConfigurationRequest : public S3Request
  {
  public:
    PutBucketLifecycleConfigurationRequest();
    Aws::String SerializePayload() const override;

    inline bool ShouldComputeContentMd5() const override { return true; }

    inline const Aws::String& GetBucket() const{ return m_bucket; }

    inline void SetBucket(const Aws::String& value) { m_bucketHasBeenSet = true; m_bucket = value; }

    inline void SetBucket(Aws::String&& value) { m_bucketHasBeenSet = true; m_bucket = value; }

    inline void SetBucket(const char* value) { m_bucketHasBeenSet = true; m_bucket.assign(value); }

    inline PutBucketLifecycleConfigurationRequest& WithBucket(const Aws::String& value) { SetBucket(value); return *this;}

    inline PutBucketLifecycleConfigurationRequest& WithBucket(Aws::String&& value) { SetBucket(value); return *this;}

    inline PutBucketLifecycleConfigurationRequest& WithBucket(const char* value) { SetBucket(value); return *this;}

    inline const BucketLifecycleConfiguration& GetLifecycleConfiguration() const{ return m_lifecycleConfiguration; }

    inline void SetLifecycleConfiguration(const BucketLifecycleConfiguration& value) { m_lifecycleConfigurationHasBeenSet = true; m_lifecycleConfiguration = value; }

    inline void SetLifecycleConfiguration(BucketLifecycleConfiguration&& value) { m_lifecycleConfigurationHasBeenSet = true; m_lifecycleConfiguration = value; }

    inline PutBucketLifecycleConfigurationRequest& WithLifecycleConfiguration(const BucketLifecycleConfiguration& value) { SetLifecycleConfiguration(value); return *this;}

    inline PutBucketLifecycleConfigurationRequest& WithLifecycleConfiguration(BucketLifecycleConfiguration&& value) { SetLifecycleConfiguration(value); return *this;}

  private:
    Aws::String m_bucket;
    bool m_bucketHasBeenSet;
    BucketLifecycleConfiguration m_lifecycleConfiguration;
    bool m_lifecycleConfigurationHasBeenSet;
  };

} // namespace Model
} // namespace S3
} // namespace Aws


text:
/**
 * @file
 *    This is a unit test suite for <tt>chip::Time::TimeSource</tt>. Tests mainly
 *    the ability to compile and use the test implementation of the time source.
 */

#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif

#include <system/SystemConfig.h>

#include <lib/support/CodeUtils.h>
#include <lib/support/ErrorStr.h>
#include <lib/support/UnitTestRegistration.h>
#include <nlunit-test.h>
#include <system/TimeSource.h>

namespace {

void TestTimeSourceSetAndGet(nlTestSuite * inSuite, void * inContext)
{

    chip::Time::TimeSource<chip::Time::Source::kTest> source;

    NL_TEST_ASSERT(inSuite, source.GetMonotonicTimestamp() == chip::System::Clock::kZero);

    constexpr chip::System::Clock::Milliseconds64 k1234 = chip::System::Clock::Milliseconds64(1234);
    source.SetMonotonicTimestamp(k1234);
    NL_TEST_ASSERT(inSuite, source.GetMonotonicTimestamp() == k1234);
}

void SystemTimeSourceGet(nlTestSuite * inSuite, void * inContext)
{

    chip::Time::TimeSource<chip::Time::Source::kSystem> source;

    chip::System::Clock::Timestamp oldValue = source.GetMonotonicTimestamp();

    // a basic monotonic test. This is likely to take less than 1ms, so the
    // actual test value lies mostly in ensuring things compile.
    for (int i = 0; i < 100; i++)
    {
        chip::System::Clock::Timestamp newValue = source.GetMonotonicTimestamp();
        NL_TEST_ASSERT(inSuite, newValue >= oldValue);
        oldValue = newValue;
    }
}

} // namespace

/**
 *   Test Suite. It lists all the test functions.
 */
// clang-format off
static const nlTest sTests[] =
{
    NL_TEST_DEF("TimeSource<Test>::SetAndGet", TestTimeSourceSetAndGet),
    NL_TEST_DEF("TimeSource<System>::SetAndGet", SystemTimeSourceGet),
    NL_TEST_SENTINEL()
};
// clang-format on

int TestTimeSource(void)
{
    nlTestSuite theSuite = {
        "chip-timesource", &sTests[0], nullptr /* setup */, nullptr /* teardown */
    };

    // Run test suit againt one context.
    nlTestRunner(&theSuite, nullptr /* context */);

    return (nlTestRunnerStats(&theSuite));
}

CHIP_REGISTER_TEST_SUITE(TestTimeSource)