text:
import { useQuery, gql } from '@apollo/client';
import { fragmentTextForQuery } from '../../lib/vulcan-lib/fragments';
import { defaultAlgorithmSettings } from '../../lib/collections/users/recommendationSettings';
import type { RecommendationsAlgorithm } from '../../lib/collections/users/recommendationSettings';

export const useRecommendations = (algorithm: RecommendationsAlgorithm): {
  recommendationsLoading: boolean,
  recommendations: PostsList[]|undefined,
}=> {
  const {data, loading} = useQuery(gql`
    query RecommendationsQuery($count: Int, $algorithm: JSON) {
      Recommendations(count: $count, algorithm: $algorithm) {
        ...PostsList
      }
    }
    ${fragmentTextForQuery("PostsList")}
  `, {
    variables: {
      count: algorithm?.count || 10,
      algorithm: algorithm || defaultAlgorithmSettings,
    },
    ssr: true,
  });
  return {
    recommendationsLoading: loading,
    recommendations: data?.Recommendations,
  };
}

redpajama_set_name: RedPajamaGithub


text:
package tsu.tsu_04;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 使用 CyclicBarrier 类完成分治编程技术
 * 在一个大矩阵中寻找一个数字。
 * 将大矩阵分为几个子集,每个线程在一个子集中查找。一旦所有线程都完成查找,最终的任务将统一这些结果。
 */
public class Main {

    public static void main(String[] args) {

        final int ROWS = 10000;
        final int NUMBERS = 1000;
        final int SEARCH = 5;
        final int PARTICIPANTS = 5;
        final int LINES_PARTICIPANT = 2000;
        MatrixMock mock = new MatrixMock(ROWS, NUMBERS, SEARCH);

        // 存储计算结果
        Results results = new Results(ROWS);

        // 执行合并的对象
        Grouper grouper = new Grouper(results);

        CyclicBarrier barrier = new CyclicBarrier(PARTICIPANTS, grouper);

        Searcher searchers[] = new Searcher[PARTICIPANTS];
        for (int i = 0; i < PARTICIPANTS; i++) {
            searchers[i] = new Searcher(i * LINES_PARTICIPANT, (i * LINES_PARTICIPANT) + LINES_PARTICIPANT, mock, results, 5, barrier);
            Thread thread = new Thread(searchers[i]);
            thread.start();
        }
        System.out.printf("Main: The main thread has finished.\n");

    }

}

/**
 * 模拟被查找的矩阵
 */
class MatrixMock {

    private final int data[][];

    public MatrixMock(int size, int length, int number) {
        int counter = 0;
        data = new int[size][length];
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < length; j++) {
                data[i][j] = random.nextInt(10);
                if (data[i][j] == number) {
                    counter++;
                }
            }
        }
        System.out.printf("Mock: There are %d occurrences of number %d in generated data.\n", counter, number);
    }

    public int[] getRow(int row) {
        if ((row >= 0) && (row < data.length)) {
            return data[row];
        }
        return null;
    }

}

/**
 * 用来存储矩阵中每一行出现的目标数字的个数
 */
class Results {

    private final int data[];

    public Results(int size) {
        data = new int[size];
    }

    public void setData(int position, int value) {
        data[position] = value;
    }

    public int[] getData() {
        return data;
    }
}

/**
 * 每个子任务,负责矩阵中一个子集的查找
 */
class Searcher implements Runnable {

    private final int firstRow;
    private final int lastRow;
    private final MatrixMock mock;
    private final Results results;
    private final int number;
    private final CyclicBarrier barrier;

    public Searcher(int firstRow, int lastRow, MatrixMock mock, Results results, int number, CyclicBarrier barrier) {
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.mock = mock;
        this.results = results;
        this.number = number;
        this.barrier = barrier;
    }

    @Override
    public void run() {
        int counter;
        System.out.printf("%s: Processing lines from %d to %d.\n", Thread.currentThread().getName(), firstRow, lastRow);
        for (int i = firstRow; i < lastRow; i++) {
            int row[] = mock.getRow(i);
            counter = 0;
            for (int aRow : row) {
                if (aRow == number) {
                    counter++;
                }
            }
            results.setData(i, counter);
        }
        System.out.printf("%s: Lines processed.\n", Thread.currentThread().getName());
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

}

/**
 * 最终的合并线程
 */
class Grouper implements Runnable {

    private final Results results;

    public Grouper(Results results) {
        this.results = results;
    }

    @Override
    public void run() {
        int finalResult = 0;
        System.out.printf("Grouper: Processing results...\n");
        int data[] = results.getData();
        for (int number : data) {
            finalResult += number;
        }
        System.out.printf("Grouper: Total result: %d.\n", finalResult);
    }

}


text:
package org.intellij.xquery.runner.ui.datasources.details;

import org.intellij.xquery.BaseGuiTest;
import org.intellij.xquery.PanelTestingFrame;
import org.intellij.xquery.runner.rt.XQueryDataSourceType;
import org.intellij.xquery.runner.state.datasources.XQueryDataSourceConfiguration;
import org.intellij.xquery.runner.ui.datasources.ConfigurationChangeListener;
import org.junit.Test;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

/**
 * User: ligasgr
 * Date: 01/11/13
 * Time: 19:49
 */
public class DataSourceConfigurationAggregatingPanelGuiTest extends BaseGuiTest {

    private DataSourceConfigurationAggregatingPanel panel;
    private ConfigurationChangeListener nameChangedListener;
    private XQueryDataSourceConfiguration configuration;

    @Override
    protected PanelTestingFrame getPanelTestingFrame() {
        nameChangedListener = mock(ConfigurationChangeListener.class);
        configuration = new XQueryDataSourceConfiguration("config", XQueryDataSourceType.SAXON);
        panel = new DataSourceConfigurationAggregatingPanel(configuration, nameChangedListener);
        return new PanelTestingFrame(panel.getPanel());
    }

    @Test
    public void shouldShowMainPanel() {
        assertThat(panel.getPanel().isVisible(), is(true));
    }

    @Test
    public void shouldReturnTheSameValues() {
        XQueryDataSourceConfiguration currentConfig = panel.getCurrentConfigurationState();

        assertThat(currentConfig.equals(configuration), is(true));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MobilePhone
{
    public class Call
    {
        public DateTime Date { get; set; }
        public string DialedPhone { get; set; }
        public int Duration { get; set; }

        public Call(DateTime date, string dialedNumber, int duration)
        {
            this.Date = date;
            this.DialedPhone = dialedNumber;
            this.Duration = duration;
        }

        public override string ToString()
        {
            return string.Format("Date: {0}, time: {1}, Duration: {2}", this.Date.ToShortDateString(), this.Date.TimeOfDay, this.Duration);
        }
    }
}


text:
package com.cloudera.oryx.app.serving.als.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import net.openhft.koloboke.collect.map.ObjIntMap;
import net.openhft.koloboke.collect.map.ObjObjMap;
import net.openhft.koloboke.collect.map.hash.HashObjIntMaps;
import net.openhft.koloboke.collect.map.hash.HashObjObjMaps;
import net.openhft.koloboke.collect.set.ObjSet;
import net.openhft.koloboke.collect.set.hash.HashObjSets;
import net.openhft.koloboke.function.ObjDoubleToDoubleFunction;
import net.openhft.koloboke.function.Predicate;
import org.apache.commons.math3.linear.RealMatrix;

import com.cloudera.oryx.app.als.FeatureVectors;
import com.cloudera.oryx.app.als.RescorerProvider;
import com.cloudera.oryx.app.serving.als.CosineDistanceSensitiveFunction;
import com.cloudera.oryx.common.collection.KeyOnlyBiPredicate;
import com.cloudera.oryx.common.collection.NotContainsPredicate;
import com.cloudera.oryx.common.collection.Pair;
import com.cloudera.oryx.common.collection.PairComparators;
import com.cloudera.oryx.common.collection.Predicates;
import com.cloudera.oryx.common.lang.AutoLock;
import com.cloudera.oryx.common.lang.AutoReadWriteLock;
import com.cloudera.oryx.common.lang.LoggingCallable;
import com.cloudera.oryx.common.math.LinearSystemSolver;
import com.cloudera.oryx.common.math.Solver;

/**
 * Contains all data structures needed to serve real-time requests for an ALS-based recommender.
 */
public final class ALSServingModel {

  /** Number of partitions for items data structures. */
  private static final ExecutorService executor = Executors.newFixedThreadPool(
      Runtime.getRuntime().availableProcessors(),
      new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ALSServingModel-%d").build());

  private final LocalitySensitiveHash lsh;
  /** User-feature matrix. */
  private final FeatureVectors X;
  /** Item-feature matrix. This is partitioned into several maps for parallel access. */
  private final FeatureVectors[] Y;
  /** Maps item IDs to their existing partition, if any */
  private final ObjIntMap<String> yPartitionMap;
  /** Controls access to yPartitionMap. */
  private final AutoReadWriteLock yPartitionMapLock;
  /** Remembers items that each user has interacted with*/
  private final ObjObjMap<String,ObjSet<String>> knownItems; // Right now no corresponding "knownUsers" object
  private final AutoReadWriteLock knownItemsLock;
  /** Number of features used in the model. */
  private final int features;
  /** Whether model uses implicit feedback. */
  private final boolean implicit;
  private final RescorerProvider rescorerProvider;

  /**
   * Creates an empty model.
   *
   * @param features number of features expected for user/item feature vectors
   * @param implicit whether model implements implicit feedback
   * @param sampleRate consider only approximately this fraction of all items when making recommendations.
   *  Candidates are chosen intelligently with locality sensitive hashing.
   * @param rescorerProvider optional instance of a {@link RescorerProvider}
   */
  ALSServingModel(int features, boolean implicit, double sampleRate, RescorerProvider rescorerProvider) {
    Preconditions.checkArgument(features > 0);
    Preconditions.checkArgument(sampleRate > 0.0 && sampleRate <= 1.0);

    lsh = new LocalitySensitiveHash(sampleRate, features);

    X = new FeatureVectors();
    Y = new FeatureVectors[lsh.getNumPartitions()];
    for (int i = 0; i < Y.length; i++) {
      Y[i] = new FeatureVectors();
    }
    yPartitionMap = HashObjIntMaps.newMutableMap();
    yPartitionMapLock = new AutoReadWriteLock();

    knownItems = HashObjObjMaps.newMutableMap();
    knownItemsLock = new AutoReadWriteLock();

    this.features = features;
    this.implicit = implicit;
    this.rescorerProvider = rescorerProvider;
  }

  public int getFeatures() {
    return features;
  }

  public boolean isImplicit() {
    return implicit;
  }

  public RescorerProvider getRescorerProvider() {
    return rescorerProvider;
  }

  public float[] getUserVector(String user) {
    return X.getVector(user);
  }

  public float[] getItemVector(String item) {
    int partition;
    try (AutoLock al = yPartitionMapLock.autoReadLock()) {
      partition = yPartitionMap.getOrDefault(item, Integer.MIN_VALUE);
    }
    if (partition < 0) {
      return null;
    }
    return Y[partition].getVector(item);
  }

  void setUserVector(String user, float[] vector) {
    Preconditions.checkArgument(vector.length == features);
    X.setVector(user, vector);
  }

  void setItemVector(String item, float[] vector) {
    Preconditions.checkArgument(vector.length == features);
    int newPartition = lsh.getIndexFor(vector);
    // Exclusive update to mapping -- careful since other locks are acquired inside here
    try (AutoLock al = yPartitionMapLock.autoWriteLock()) {
      int existingPartition = yPartitionMap.getOrDefault(item, Integer.MIN_VALUE);
      if (existingPartition >= 0 && existingPartition != newPartition) {
        // Move from one to the other partition, so first remove old entry
        Y[existingPartition].removeVector(item);
        // Note that it's conceivable that a recommendation call sees *no* copy of this
        // item here in this brief window
      }
      // Then regardless put in new partition
      Y[newPartition].setVector(item, vector);
      yPartitionMap.put(item, newPartition);
    }
  }

  /**
   * @param user user to get known items for
   * @return set of known items for the user. Note that this object is not thread-safe and
   *  access must be {@code synchronized}
   */
  public Collection<String> getKnownItems(String user) {
    return doGetKnownItems(user);
  }

  private ObjSet<String> doGetKnownItems(String user) {
    try (AutoLock al = knownItemsLock.autoReadLock()) {
      return knownItems.get(user);
    }
  }

  /**
   * @return mapping of user IDs to count of items the user has interacted with
   */
  public Map<String,Integer> getUserCounts() {
    ObjIntMap<String> counts = HashObjIntMaps.newUpdatableMap();
    try (AutoLock al = knownItemsLock.autoReadLock()) {
      for (Map.Entry<String,ObjSet<String>> entry : knownItems.entrySet()) {
        String userID = entry.getKey();
        Collection<?> ids = entry.getValue();
        int numItems;
        synchronized (ids) {
          numItems = ids.size();
        }
        counts.addValue(userID, numItems);
      }
    }
    return counts;
  }

  /**
   * @return mapping of item IDs to count of users that have interacted with that item
   */
  public Map<String,Integer> getItemCounts() {
    ObjIntMap<String> counts = HashObjIntMaps.newUpdatableMap();
    try (AutoLock al = knownItemsLock.autoReadLock()) {
      for (Collection<String> ids : knownItems.values()) {
        synchronized (ids) {
          for (String id : ids) {
            counts.addValue(id, 1);
          }
        }
      }
    }
    return counts;
  }

  void addKnownItems(String user, Collection<String> items) {
    ObjSet<String> knownItemsForUser = doGetKnownItems(user);

    if (knownItemsForUser == null) {
      try (AutoLock al = knownItemsLock.autoWriteLock()) {
        // Check again
        knownItemsForUser = knownItems.get(user);
        if (knownItemsForUser == null) {
          knownItemsForUser = HashObjSets.newMutableSet();
          knownItems.put(user, knownItemsForUser);
        }
      }
    }

    synchronized (knownItemsForUser) {
      knownItemsForUser.addAll(items);
    }
  }

  /**
   * @param user user to get known item vectors for
   * @return {@code null} if the user is not known to the model, or if there are no known items for the user
   */
  public List<Pair<String,float[]>> getKnownItemVectorsForUser(String user) {
    float[] userVector = getUserVector(user);
    if (userVector == null) {
      return null;
    }
    Collection<String> knownItems = getKnownItems(user);
    if (knownItems == null) {
      return null;
    }
    synchronized (knownItems) {
      int size = knownItems.size();
      if (size == 0) {
        return null;
      }
      List<Pair<String,float[]>> idVectors = new ArrayList<>(size);
      for (String itemID : knownItems) {
        float[] vector = getItemVector(itemID);
        if (vector != null) {
          idVectors.add(new Pair<>(itemID, vector));
        }
      }
      return idVectors.isEmpty() ? null : idVectors;
    }
  }

  public List<Pair<String,Double>> topN(
      final CosineDistanceSensitiveFunction scoreFn,
      final ObjDoubleToDoubleFunction<String> rescoreFn,
      final int howMany,
      final Predicate<String> allowedPredicate) {

    int[] candidateIndices = lsh.getCandidateIndices(scoreFn.getTargetVector());
    List<Callable<Iterable<Pair<String,Double>>>> tasks = new ArrayList<>(candidateIndices.length);
    for (int partition : candidateIndices) {
      final FeatureVectors yPartition = Y[partition];
      if (yPartition.size() > 0) {
        tasks.add(new LoggingCallable<Iterable<Pair<String,Double>>>() {
          @Override
          public Iterable<Pair<String,Double>> doCall() {
            Queue<Pair<String,Double>> topN =
                new PriorityQueue<>(howMany + 1, PairComparators.<Double>bySecond());
            yPartition.forEach(new TopNConsumer(topN, howMany, scoreFn, rescoreFn, allowedPredicate));
            // Ordering and excess items don't matter; will be merged and finally sorted later
            return topN;
          }
        });
      }
    }

    int numTasks = tasks.size();
    if (numTasks == 0) {
      return Collections.emptyList();
    }

    Ordering<Pair<?,Double>> ordering = Ordering.from(PairComparators.<Double>bySecond());
    if (numTasks == 1) {
      Iterable<Pair<String,Double>> iterable;
      try {
        iterable = tasks.get(0).call();
      } catch (Exception e) {
        throw new IllegalStateException(e);
      }
      return ordering.greatestOf(iterable, howMany);
    }

    List<Iterable<Pair<String,Double>>> iterables = new ArrayList<>(numTasks);
    try {
      for (Future<Iterable<Pair<String, Double>>> future : executor.invokeAll(tasks)) {
        iterables.add(future.get());
      }
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    } catch (ExecutionException e) {
      throw new IllegalStateException(e.getCause());
    }
    return ordering.greatestOf(Iterables.concat(iterables), howMany);
  }

  /**
   * @return all user IDs in the model
   */
  public Collection<String> getAllUserIDs() {
    Collection<String> allUserIDs = HashObjSets.newMutableSet();
    X.addAllIDsTo(allUserIDs);
    return allUserIDs;
  }

  /**
   * @return all item IDs in the model
   */
  public Collection<String> getAllItemIDs() {
    Collection<String> allItemIDs = HashObjSets.newMutableSet();
    for (FeatureVectors yPartition : Y) {
      yPartition.addAllIDsTo(allItemIDs);
    }
    return allItemIDs;
  }

  public Solver getYTYSolver() {
    RealMatrix YTY = null;
    for (FeatureVectors yPartition : Y) {
      RealMatrix YTYpartial = yPartition.getVTV();
      if (YTYpartial != null) {
        YTY = YTY == null ? YTYpartial : YTY.add(YTYpartial);
      }
    }
    return LinearSystemSolver.getSolver(YTY);
  }

  /**
   * Prunes the set of users in the model, by retaining only users that are expected to appear
   * in the upcoming model updates, or, that have arrived recently. This also clears the
   * recent known users data structure.
   *
   * @param users users that should be retained, which are coming in the new model updates
   */
  void pruneX(Collection<String> users) {
    X.prune(users);
  }

  /**
   * Prunes the set of items in the model, by retaining only items that are expected to appear
   * in the upcoming model updates, or, that have arrived recently. This also clears the
   * recent known items data structure.
   *
   * @param items items that should be retained, which are coming in the new model updates
   */
  void pruneY(Collection<String> items) {
    for (FeatureVectors yPartition : Y) {
      yPartition.prune(items);
    }
  }

  /**
   * Like {@link #pruneX(Collection)} and {@link #pruneY(Collection)} but prunes the
   * known-items data structure.
   */
  void pruneKnownItems(Collection<String> users, final Collection<String> items) {
    // Keep all users in the new model, or, that have been added since last model
    Collection<String> recentUserIDs = HashObjSets.newMutableSet();
    X.addAllRecentTo(recentUserIDs);
    try (AutoLock al = knownItemsLock.autoWriteLock()) {
      knownItems.removeIf(new KeyOnlyBiPredicate<>(Predicates.and(
          new NotContainsPredicate<>(users), new NotContainsPredicate<>(recentUserIDs))));
    }

    // This will be easier to quickly copy the whole (smallish) set rather than
    // deal with locks below
    final Collection<String> allRecentKnownItems = HashObjSets.newMutableSet();
    for (FeatureVectors yPartition : Y) {
      yPartition.addAllRecentTo(allRecentKnownItems);
    }

    Predicate<String> notKeptOrRecent = new Predicate<String>() {
      @Override
      public boolean test(String value) {
        return !items.contains(value) && !allRecentKnownItems.contains(value);
      }
    };
    try (AutoLock al = knownItemsLock.autoReadLock()) {
      for (ObjSet<String> knownItemsForUser : knownItems.values()) {
        synchronized (knownItemsForUser) {
          knownItemsForUser.removeIf(notKeptOrRecent);
        }
      }
    }
  }

  /**
   * @return number of users in the model
   */
  public int getNumUsers() {
    return X.size();
  }

  /**
   * @return number of items in the model
   */
  public int getNumItems() {
    int total = 0;
    for (FeatureVectors yPartition : Y) {
      total += yPartition.size();
    }
    return total;
  }

  @Override
  public String toString() {
    int maxSize = 128;
    List<String> partitionSizes = new ArrayList<>(maxSize);
    for (int i = 0; i < Y.length; i++) {
      int size = Y[i].size();
      if (size > 0) {
        partitionSizes.add(i + ":" + size);
        if (partitionSizes.size() == maxSize) {
          partitionSizes.add("...");
          break;
        }
      }
    }
    return "ALSServingModel[features:" + features + ", implicit:" + implicit +
        ", X:(" + getNumUsers() + " users), Y:(" + getNumItems() + " items, partitions: " +
        partitionSizes + "...)]";
  }

}


text:
package sample.helloworld.api;

import static com.lightbend.lagom.javadsl.api.Service.named;
import static com.lightbend.lagom.javadsl.api.Service.pathCall;

import akka.Done;
import akka.NotUsed;
import com.lightbend.lagom.javadsl.api.Descriptor;
import com.lightbend.lagom.javadsl.api.Service;
import com.lightbend.lagom.javadsl.api.ServiceCall;

/**
 * The hello service interface.
 * <p>
 * This describes everything that Lagom needs to know about how to serve and
 * consume the HelloService.
 */
public interface HelloService extends Service {

  /**
   * Example: curl http://localhost:9000/api/hello/Alice
   */
  ServiceCall<NotUsed, String> hello(String id);

  /**
   * Example: curl -H "Content-Type: application/json" -X POST -d '{"message":
   * "Hi"}' http://localhost:9000/api/hello/Alice
   */
  ServiceCall<GreetingMessage, Done> useGreeting(String id);

  @Override
  default Descriptor descriptor() {
    // @formatter:off
    return named("helloservice").withCalls(
        pathCall("/api/hello/:id",  this::hello),
        pathCall("/api/hello/:id", this::useGreeting)
      )
      .withAutoAcl(true);
    // @formatter:on
  }
}


text:
require 'yaml'

res = YAML::load(open("spec/config/mongoid.yml"))
puts res.inspect


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

#include "media/cast/transport/rtcp/rtcp_builder.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/big_endian.h"
#include "base/logging.h"
#include "media/cast/transport/cast_transport_defines.h"
#include "media/cast/transport/pacing/paced_sender.h"

namespace media {
namespace cast {
namespace transport {

RtcpBuilder::RtcpBuilder(PacedSender* const outgoing_transport)
    : transport_(outgoing_transport),
      ssrc_(0) {
}

RtcpBuilder::~RtcpBuilder() {}

void RtcpBuilder::SendRtcpFromRtpSender(
    uint32 packet_type_flags,
    const RtcpSenderInfo& sender_info,
    const RtcpDlrrReportBlock& dlrr,
    uint32 sending_ssrc,
    const std::string& c_name) {
  if (packet_type_flags & kRtcpRr ||
      packet_type_flags & kRtcpPli ||
      packet_type_flags & kRtcpRrtr ||
      packet_type_flags & kRtcpCast ||
      packet_type_flags & kRtcpReceiverLog ||
      packet_type_flags & kRtcpRpsi ||
      packet_type_flags & kRtcpRemb ||
      packet_type_flags & kRtcpNack) {
    NOTREACHED() << "Invalid argument";
  }
  ssrc_ = sending_ssrc;
  c_name_ = c_name;
  PacketRef packet(new base::RefCountedData<Packet>);
  packet->data.reserve(kMaxIpPacketSize);
  if (packet_type_flags & kRtcpSr) {
    if (!BuildSR(sender_info, &packet->data)) return;
    if (!BuildSdec(&packet->data)) return;
  }
  if (packet_type_flags & kRtcpBye) {
    if (!BuildBye(&packet->data)) return;
  }
  if (packet_type_flags & kRtcpDlrr) {
    if (!BuildDlrrRb(dlrr, &packet->data)) return;
  }
  if (packet->data.empty())
    return;  // Sanity - don't send empty packets.

  transport_->SendRtcpPacket(ssrc_, packet);
}

bool RtcpBuilder::BuildSR(const RtcpSenderInfo& sender_info,
                          Packet* packet) const {
  // Sender report.
  size_t start_size = packet->size();
  if (start_size + 52 > kMaxIpPacketSize) {
    DLOG(FATAL) << "Not enough buffer space";
    return false;
  }

  uint16 number_of_rows = 6;
  packet->resize(start_size + 28);

  base::BigEndianWriter big_endian_writer(
      reinterpret_cast<char*>(&((*packet)[start_size])), 28);
  big_endian_writer.WriteU8(0x80);
  big_endian_writer.WriteU8(kPacketTypeSenderReport);
  big_endian_writer.WriteU16(number_of_rows);
  big_endian_writer.WriteU32(ssrc_);
  big_endian_writer.WriteU32(sender_info.ntp_seconds);
  big_endian_writer.WriteU32(sender_info.ntp_fraction);
  big_endian_writer.WriteU32(sender_info.rtp_timestamp);
  big_endian_writer.WriteU32(sender_info.send_packet_count);
  big_endian_writer.WriteU32(static_cast<uint32>(sender_info.send_octet_count));
  return true;
}

bool RtcpBuilder::BuildSdec(Packet* packet) const {
  size_t start_size = packet->size();
  if (start_size + 12 + c_name_.length() > kMaxIpPacketSize) {
    DLOG(FATAL) << "Not enough buffer space";
    return false;
  }

  // SDES Source Description.
  packet->resize(start_size + 10);

  base::BigEndianWriter big_endian_writer(
      reinterpret_cast<char*>(&((*packet)[start_size])), 10);
  // We always need to add one SDES CNAME.
  big_endian_writer.WriteU8(0x80 + 1);
  big_endian_writer.WriteU8(kPacketTypeSdes);

  // Handle SDES length later on.
  uint32 sdes_length_position = static_cast<uint32>(start_size) + 3;
  big_endian_writer.WriteU16(0);
  big_endian_writer.WriteU32(ssrc_);  // Add our own SSRC.
  big_endian_writer.WriteU8(1);  // CNAME = 1
  big_endian_writer.WriteU8(static_cast<uint8>(c_name_.length()));

  size_t sdes_length = 10 + c_name_.length();
  packet->insert(packet->end(), c_name_.c_str(),
                 c_name_.c_str() + c_name_.length());

  size_t padding = 0;

  // We must have a zero field even if we have an even multiple of 4 bytes.
  if ((packet->size() % 4) == 0) {
    padding++;
    packet->push_back(0);
  }
  while ((packet->size() % 4) != 0) {
    padding++;
    packet->push_back(0);
  }
  sdes_length += padding;

  // In 32-bit words minus one and we don't count the header.
  uint8 buffer_length = static_cast<uint8>((sdes_length / 4) - 1);
  (*packet)[sdes_length_position] = buffer_length;
  return true;
}

bool RtcpBuilder::BuildBye(Packet* packet) const {
  size_t start_size = packet->size();
  if (start_size + 8 > kMaxIpPacketSize) {
    DLOG(FATAL) << "Not enough buffer space";
    return false;
  }

  packet->resize(start_size + 8);

  base::BigEndianWriter big_endian_writer(
      reinterpret_cast<char*>(&((*packet)[start_size])), 8);
  big_endian_writer.WriteU8(0x80 + 1);
  big_endian_writer.WriteU8(kPacketTypeBye);
  big_endian_writer.WriteU16(1);  // Length.
  big_endian_writer.WriteU32(ssrc_);  // Add our own SSRC.
  return true;
}

/*
   0                   1                   2                   3
   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |V=2|P|reserved |   PT=XR=207   |             length            |
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |                              SSRC                             |
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |     BT=5      |   reserved    |         block length          |
  +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
  |                 SSRC_1 (SSRC of first receiver)               | sub-
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ block
  |                         last RR (LRR)                         |   1
  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  |                   delay since last RR (DLRR)                  |
  +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*/
bool RtcpBuilder::BuildDlrrRb(const RtcpDlrrReportBlock& dlrr,
                              Packet* packet) const {
  size_t start_size = packet->size();
  if (start_size + 24 > kMaxIpPacketSize) {
    DLOG(FATAL) << "Not enough buffer space";
    return false;
  }

  packet->resize(start_size + 24);

  base::BigEndianWriter big_endian_writer(
      reinterpret_cast<char*>(&((*packet)[start_size])), 24);
  big_endian_writer.WriteU8(0x80);
  big_endian_writer.WriteU8(kPacketTypeXr);
  big_endian_writer.WriteU16(5);  // Length.
  big_endian_writer.WriteU32(ssrc_);  // Add our own SSRC.
  big_endian_writer.WriteU8(5);  // Add block type.
  big_endian_writer.WriteU8(0);  // Add reserved.
  big_endian_writer.WriteU16(3);  // Block length.
  big_endian_writer.WriteU32(ssrc_);  // Add the media (received RTP) SSRC.
  big_endian_writer.WriteU32(dlrr.last_rr);
  big_endian_writer.WriteU32(dlrr.delay_since_last_rr);
  return true;
}

}  // namespace transport
}  // namespace cast
}  // namespace media


text:
import { Injectable } from '@angular/core';

export interface IconAble {
  iconName?: string;
  iconSource?: string;
}

@Injectable({
  providedIn: 'root',
})
export class IconService {
  constructor() {}

  load(item: IconAble): string {
    if (!item.iconName || item.iconName === '') {
      return '';
    }

    // tslint:disable:no-string-literal
    const clarityIcons = window['ClarityIcons'];

    if (!clarityIcons.has(item.iconName)) {
      clarityIcons.add({ [item.iconName]: item.iconSource });
    }

    return item.iconName;
  }
}


text:
"""
The compute resource backend for OpenStack.
"""

#pylint: disable=W0232,R0201

from occi_os_api.extensions import os_mixins
from occi_os_api.extensions import os_addon
from occi_os_api.nova_glue import vm

from occi.backend import KindBackend, ActionBackend
from occi.extensions import infrastructure

class ComputeBackend(KindBackend, ActionBackend):
    """
    The compute backend.
    """

    def create(self, entity, extras):
        """
        Create a VM.
        """
        # ignore some attributes - done via templating
        if 'occi.compute.cores' in entity.attributes or \
           'occi.compute.speed' in entity.attributes or \
           'occi.compute.memory' in entity.attributes or \
           'occi.compute.architecture' in entity.attributes:
            raise AttributeError('There are unsupported attributes in the '
                                 'request.')

        # create the VM
        context = extras['nova_ctx']
        instance = vm.create_vm(entity, context)
        uid = instance['uuid']
        entity.identifier = '/compute/' + uid

        # set some attributes
        entity.attributes['occi.compute.hostname'] = instance['hostname']
        entity.attributes['occi.compute.architecture'] = 'x86'
        entity.attributes['occi.compute.cores'] = str(instance['vcpus'])
        entity.attributes['occi.compute.speed'] = str(0.0)  # N/A in instance
        value = str(float(instance['memory_mb']) / 1024)
        entity.attributes['occi.compute.memory'] = value
        entity.attributes['occi.compute.state'] = 'inactive'

        # set valid actions
        entity.actions = [infrastructure.STOP,
                          infrastructure.SUSPEND,
                          infrastructure.RESTART]

        # Tell the world that is is an VM in OpenStack...
        entity.mixins.append(os_addon.OS_VM)

    def retrieve(self, entity, extras):
        """
        Retrieve a VM.
        """
        uid = entity.attributes['occi.core.id']
        context = extras['nova_ctx']
        instance = vm.get_vm(uid, context)

        # set state and applicable actions!
        # TODO: map to OCCI state!
        state, actions = vm.get_vm_state(uid, context)
        entity.attributes['occi.compute.state'] = state
        entity.actions = actions

        # set up to date attributes
        entity.attributes['occi.compute.hostname'] = instance['hostname']
        # TODO: check to get arch from OS!
        entity.attributes['occi.compute.architecture'] = 'x86'
        entity.attributes['occi.compute.cores'] = str(instance['vcpus'])
        entity.attributes['occi.compute.speed'] = str(0.0)  # N/A in instance
        value = str(float(instance['memory_mb']) / 1024)
        entity.attributes['occi.compute.memory'] = value

    def update(self, old, new, extras):
        """
        Update an VM.
        """
        context = extras['nova_ctx']
        uid = old.attributes['occi.core.id']

        # for now we will only handle one mixin change per request
        if len(new.mixins) != 1:
            raise AttributeError('Only updates with one mixin in request are'
                                 ' currently supported')

        mixin = new.mixins[0]
        if isinstance(mixin, os_mixins.ResourceTemplate):
            flavor_id = mixin.res_id
            vm.resize_vm(uid, flavor_id, context)
            old.attributes['occi.compute.state'] = 'inactive'
            # now update the mixin info
            old.mixins.append(mixin)
        elif isinstance(mixin, os_mixins.OsTemplate):
            image_href = mixin.os_id
            vm.rebuild_vm(uid, image_href, context)
            old.attributes['occi.compute.state'] = 'inactive'
            # now update the mixin info
            old.mixins.append(mixin)
        else:
            msg = 'Unrecognized mixin. %s' % str(mixin)
            raise AttributeError(msg)

    def replace(self, old, new, extras):
        """
        XXX:not doing anything - full updates are hard :-)
        """
        pass

    def delete(self, entity, extras):
        """
        Remove a VM.
        """
        context = extras['nova_ctx']
        uid = entity.attributes['occi.core.id']

        vm.delete_vm(uid, context)

    def action(self, entity, action, attributes, extras):
        """
        Perform an action.
        """
        # As there is no callback mechanism to update the state
        # of computes known by occi, a call to get the latest representation
        # must be made.
        context = extras['nova_ctx']
        uid = entity.attributes['occi.core.id']

        # set state and applicable actions - so even if the user hasn't done
        # a GET het can still the most applicable action now...
        state, actions = vm.get_vm_state(uid, context)
        entity.attributes['occi.compute.state'] = state
        entity.actions = actions

        if action not in entity.actions:
            raise AttributeError("This action is currently not applicable.")
        elif action == infrastructure.START:
            vm.start_vm(uid, context)
        elif action == infrastructure.STOP:
            vm.stop_vm(uid, context)
        elif action == infrastructure.RESTART:
            if not 'method' in attributes:
                raise AttributeError('Please provide a method!')
            method = attributes['method']
            vm.restart_vm(uid, method, context)
        elif action == infrastructure.SUSPEND:
            vm.suspend_vm(uid, context)


text:
/*
 * Program:	Windows/TOPS-20 newline routines
 *
 * Author:	Mark Crispin
 *		Networks and Distributed Computing
 *		Computing & Communications
 *		University of Washington
 *		Administration Building, AG-44
 *		Seattle, WA  98195
 *		Internet: MRC@CAC.Washington.EDU
 *
 * Date:	1 August 1988
 * Last Edited:	30 August 2006
 */

/* Copy string with CRLF newlines
 * Accepts: destination string
 *	    pointer to size of destination string buffer
 *	    source string
 *	    length of source string
 * Returns: length of copied string
 */

unsigned long strcrlfcpy (unsigned char **dst,unsigned long *dstl,
			  unsigned char *src,unsigned long srcl)
{
				/* flush destination buffer if too small */
  if (*dst && (srcl > *dstl)) fs_give ((void **) dst);
  if (!*dst) {			/* make a new buffer if needed */
    *dst = (char *) fs_get ((size_t) (*dstl = srcl) + 1);
    if (dstl) *dstl = srcl;	/* return new buffer length to main program */
  }
				/* copy strings */
  if (srcl) memcpy (*dst,src,(size_t) srcl);
  *(*dst + srcl) = '\0';	/* tie off destination */
  return srcl;			/* return length */
}

/* Length of string after strcrlfcpy applied
 * Accepts: source string
 * Returns: length of string
 */

unsigned long strcrlflen (STRING *s)
{
  return SIZE (s);		/* no-brainer on DOS! */
}


text:
layout: post
title: Bush Leagues
date: '2003-07-24 14:15:01 -0700'
mt_id: 378
blog_id: 1
post_id: 378
basename: bush-leagues
---

Hate Bush and his presidency? Too Stupid To Be President.com is the site for you. The lists are pretty funny and so are the Flash movies.


text:
package model.user;

import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import org.hibernate.envers.Audited;

@Entity
@Audited
public class Role {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(nullable=false, updatable=false, insertable=false)
  private Long id;

  @Column(length=50)
  private String name;

  @ManyToMany(mappedBy="roles")
  private List<User> users;

  @ManyToMany(mappedBy="roles", fetch=FetchType.EAGER)
  private Set<Permission> permissions;

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public List<User> getUsers() {
    return users;
  }

  public void setUsers(List<User> users) {
    this.users = users;
  }

  public Set<Permission> getPermissions() {
    return permissions;
  }

  public void setPermissions(Set<Permission> permissions) {
    this.permissions = permissions;
  }
}


text:
package client

import (
	"context"
	"time"

	"github.com/docker/distribution/reference"

	"github.com/grafeas/voucher"
)

const timeout = 120 * time.Second

// SignImage takes an image URL (which includes the registry and the image
// digest) as well as the check to be performed and makes a call to Voucher
// to run the specified checks. It returns an error, or nil if no errors
// occur and the check was successful.
func SignImage(hostname string, image reference.Canonical, check string) (voucher.Response, error) {
	client, err := NewClient(hostname)
	if nil != err {
		return voucher.Response{}, err
	}

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	checkResp, err := client.Check(ctx, check, image)
	if nil != err {
		return voucher.Response{}, err
	}
	return checkResp, nil
}


text:
class WXDLLIMPEXP_CORE wxDataObject : public wxDataObjectBase
{
public:
    virtual ~wxDataObject();
};

#endif //_WX_MOTIF_DATAOBJ_H_


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

namespace Squidex.Infrastructure.Commands;

public sealed class CustomCommandMiddlewareRunner : ICommandMiddleware
{
    private readonly IEnumerable<ICustomCommandMiddleware> extensions;

    public CustomCommandMiddlewareRunner(IEnumerable<ICustomCommandMiddleware> extensions)
    {
        this.extensions = extensions.Reverse().ToList();
    }

    public async Task HandleAsync(CommandContext context, NextDelegate next,
        CancellationToken ct)
    {
        foreach (var handler in extensions)
        {
            next = Join(handler, next);
        }

        await next(context, ct);
    }

    private static NextDelegate Join(ICommandMiddleware handler, NextDelegate next)
    {
        return (context, ct) => handler.HandleAsync(context, next, ct);
    }
}


text:
import {
  Component,
  ElementRef,
  EventEmitter,
  HostBinding,
  HostListener,
  Input,
  OnDestroy,
  OnInit,
  Output,
  Renderer2,
} from '@angular/core';

import { NbStatusService } from '../../services/status.service';
import { NbIconConfig } from '../icon/icon.component';
import { NbToast } from './model';

/**
 * The `NbToastComponent` is responsible for rendering each toast with appropriate styles.
 *
 * @styles
 *
 * toastr-border-style:
 * toastr-border-width:
 * toastr-border-radius:
 * toastr-padding:
 * toastr-shadow:
 * toastr-text-font-family:
 * toastr-text-font-size:
 * toastr-text-font-weight:
 * toastr-text-line-height:
 * toastr-title-text-font-family:
 * toastr-title-text-font-size:
 * toastr-title-text-font-weight:
 * toastr-title-text-line-height:
 * toastr-basic-background-color:
 * toastr-basic-border-color:
 * toastr-basic-text-color:
 * toastr-icon-basic-background-color:
 * toastr-icon-basic-color:
 * toastr-destroyable-basic-hover-background-color:
 * toastr-destroyable-basic-hover-border-color:
 * toastr-primary-background-color:
 * toastr-primary-border-color:
 * toastr-primary-text-color:
 * toastr-icon-primary-background-color:
 * toastr-icon-primary-color:
 * toastr-destroyable-primary-hover-background-color:
 * toastr-destroyable-primary-hover-border-color:
 * toastr-success-background-color:
 * toastr-success-border-color:
 * toastr-success-text-color:
 * toastr-icon-success-background-color:
 * toastr-icon-success-color:
 * toastr-destroyable-success-hover-background-color:
 * toastr-destroyable-success-hover-border-color:
 * toastr-info-background-color:
 * toastr-info-border-color:
 * toastr-info-text-color:
 * toastr-icon-info-background-color:
 * toastr-icon-info-color:
 * toastr-destroyable-info-hover-background-color:
 * toastr-destroyable-info-hover-border-color:
 * toastr-warning-background-color:
 * toastr-warning-border-color:
 * toastr-warning-text-color:
 * toastr-icon-warning-background-color:
 * toastr-icon-warning-color:
 * toastr-destroyable-warning-hover-background-color:
 * toastr-destroyable-warning-hover-border-color:
 * toastr-danger-background-color:
 * toastr-danger-border-color:
 * toastr-danger-text-color:
 * toastr-icon-danger-background-color:
 * toastr-icon-danger-color:
 * toastr-destroyable-danger-hover-background-color:
 * toastr-destroyable-danger-hover-border-color:
 * toastr-control-background-color:
 * toastr-control-border-color:
 * toastr-control-text-color:
 * toastr-icon-control-background-color:
 * toastr-icon-control-color:
 * toastr-destroyable-control-hover-background-color:
 * toastr-destroyable-control-hover-border-color:
 * */
@Component({
  selector: 'nb-toast',
  styleUrls: ['./toast.component.scss'],
  templateUrl: './toast.component.html',
})
export class NbToastComponent implements OnInit, OnDestroy {
  @Input()
  toast: NbToast;

  @Output() destroy: EventEmitter<void> = new EventEmitter();
  @Output() toastClick: EventEmitter<void> = new EventEmitter();

  @HostBinding('class.status-success')
  get success(): boolean {
    return this.toast.config.status === 'success';
  }

  @HostBinding('class.status-info')
  get info(): boolean {
    return this.toast.config.status === 'info';
  }

  @HostBinding('class.status-warning')
  get warning(): boolean {
    return this.toast.config.status === 'warning';
  }

  @HostBinding('class.status-primary')
  get primary(): boolean {
    return this.toast.config.status === 'primary';
  }

  @HostBinding('class.status-danger')
  get danger(): boolean {
    return this.toast.config.status === 'danger';
  }

  @HostBinding('class.status-basic')
  get basic(): boolean {
    return this.toast.config.status === 'basic';
  }

  @HostBinding('class.status-control')
  get control(): boolean {
    return this.toast.config.status === 'control';
  }

  @HostBinding('class.destroy-by-click')
  get destroyByClick(): boolean {
    return this.toast.config.destroyByClick;
  }

  @HostBinding('class.has-icon')
  get hasIcon(): boolean {
    const { icon } = this.toast.config;
    if (typeof icon === 'string') {
      return true;
    }

    return !!(icon && (icon as NbIconConfig).icon);
  }

  @HostBinding('class.custom-icon')
  get customIcon(): boolean {
    return !!this.icon;
  }

  get icon(): string | NbIconConfig {
    return this.toast.config.icon;
  }

  @HostBinding('class')
  get additionalClasses(): string[] {
    if (this.statusService.isCustomStatus(this.toast.config.status)) {
      return [this.statusService.getStatusClass(this.toast.config.status)];
    }
    return [];
  }

  @HostListener('click')
  onClick() {
    this.toastClick.emit();
  }

  constructor(
    protected renderer: Renderer2,
    protected elementRef: ElementRef,
    protected statusService: NbStatusService,
  ) {}

  ngOnInit() {
    if (this.toast.config.toastClass) {
      this.renderer.addClass(this.elementRef.nativeElement, this.toast.config.toastClass);
    }
  }

  ngOnDestroy() {
    this.destroy.emit();
  }
}


text:
package dotty.tools
package dotc
package core

import scala.language.unsafeNulls

import ast.{ untpd, tpd }
import Symbols._, Contexts._
import util.{SourceFile, ReadOnlyMap}
import util.Spans._
import util.CommentParsing._
import util.Property.Key
import parsing.Parsers.Parser
import reporting.ProperDefinitionNotFound

object Comments {
  val ContextDoc: Key[ContextDocstrings] = new Key[ContextDocstrings]

  /** Decorator for getting docbase out of context */
  given CommentsContext: AnyRef with
    extension (c: Context) def docCtx: Option[ContextDocstrings] = c.property(ContextDoc)

  /** Context for Docstrings, contains basic functionality for getting
    * docstrings via `Symbol` and expanding templates
    */
  class ContextDocstrings {

    private val _docstrings: MutableSymbolMap[Comment] = MutableSymbolMap[Comment](512) // FIXME: 2nd [Comment] needed or "not a class type"

    val templateExpander: CommentExpander = new CommentExpander

    def docstrings: ReadOnlyMap[Symbol, Comment] = _docstrings

    def docstring(sym: Symbol): Option[Comment] = _docstrings.get(sym)

    def addDocstring(sym: Symbol, doc: Option[Comment]): Unit =
      doc.foreach(d => _docstrings.update(sym, d))
  }

  /**
   * A `Comment` contains the unformatted docstring, it's position and potentially more
   * information that is populated when the comment is "cooked".
   *
   * @param span     The position span of this `Comment`.
   * @param raw      The raw comment, as seen in the source code, without any expansion.
   * @param expanded If this comment has been expanded, it's expansion, otherwise `None`.
   * @param usecases The usecases for this comment.
   */
  final case class Comment(
    span: Span,
    raw: String,
    expanded: Option[String],
    usecases: List[UseCase],
    variables: Map[String, String],
  ) {

    /** Has this comment been cooked or expanded? */
    def isExpanded: Boolean = expanded.isDefined

    /** The body of this comment, without the `@usecase` and `@define` sections, after expansion. */
    lazy val expandedBody: Option[String] =
      expanded.map(removeSections(_, "@usecase", "@define"))

    val isDocComment: Boolean = Comment.isDocComment(raw)

    /**
     * Expands this comment by giving its content to `f`, and then parsing the `@usecase` sections.
     * Typically, `f` will take care of expanding the variables.
     *
     * @param f The expansion function.
     * @return The expanded comment, with the `usecases` populated.
     */
    def expand(f: String => String)(using Context): Comment = {
      val expandedComment = f(raw)
      val useCases = Comment.parseUsecases(expandedComment, span)
      Comment(span, raw, Some(expandedComment), useCases, Map.empty)
    }
  }

  object Comment {

    def isDocComment(comment: String): Boolean = comment.startsWith("/**")

    def apply(span: Span, raw: String): Comment =
      Comment(span, raw, None, Nil, Map.empty)

    private def parseUsecases(expandedComment: String, span: Span)(using Context): List[UseCase] =
      if (!isDocComment(expandedComment))
        Nil
      else
        tagIndex(expandedComment)
          .filter { startsWithTag(expandedComment, _, "@usecase") }
          .map { case (start, end) => decomposeUseCase(expandedComment, span, start, end) }

    /** Turns a usecase section into a UseCase, with code changed to:
     *  {{{
     *  // From:
     *  def foo: A
     *  // To:
     *  def foo: A = ???
     *  }}}
     */
    private def decomposeUseCase(body: String, span: Span, start: Int, end: Int)(using Context): UseCase = {
      def subPos(start: Int, end: Int) =
        if (span == NoSpan) NoSpan
        else {
          val start1 = span.start + start
          val end1 = span.end + end
          span withStart start1 withPoint start1 withEnd end1
        }

      val codeStart = skipWhitespace(body, start + "@usecase".length)
      val codeEnd   = skipToEol(body, codeStart)
      val code      = body.substring(codeStart, codeEnd) + " = ???"
      val codePos   = subPos(codeStart, codeEnd)

      UseCase(code, codePos)
    }
  }

  final case class UseCase(code: String, codePos: Span, untpdCode: untpd.Tree, tpdCode: Option[tpd.DefDef]) {
    def typed(tpdCode: tpd.DefDef): UseCase = copy(tpdCode = Some(tpdCode))
  }

  object UseCase {
    def apply(code: String, codePos: Span)(using Context): UseCase = {
      val tree = {
        val tree = new Parser(SourceFile.virtual("<usecase>", code)).localDef(codePos.start)
        tree match {
          case tree: untpd.DefDef =>
            val newName = ctx.compilationUnit.freshNames.newName(tree.name, NameKinds.DocArtifactName)
            untpd.cpy.DefDef(tree)(name = newName)
          case _ =>
            report.error(ProperDefinitionNotFound(), ctx.source.atSpan(codePos))
            tree
        }
      }
      UseCase(code, codePos, tree, None)
    }
  }

  /**
   * Port of DocComment.scala from nsc
   * @author Martin Odersky
   * @author Felix Mulder
   */
  class CommentExpander {
    import dotc.config.Printers.scaladoc
    import scala.collection.mutable

    def expand(sym: Symbol, site: Symbol)(using Context): String = {
      val parent = if (site != NoSymbol) site else sym
      defineVariables(parent)
      expandedDocComment(sym, parent)
    }

    /** The cooked doc comment of symbol `sym` after variable expansion, or "" if missing.
     *
     *  @param sym  The symbol for which doc comment is returned
     *  @param site The class for which doc comments are generated
     *  @throws ExpansionLimitExceeded  when more than 10 successive expansions
     *                                  of the same string are done, which is
     *                                  interpreted as a recursive variable definition.
     */
    def expandedDocComment(sym: Symbol, site: Symbol, docStr: String = "")(using Context): String = {
      // when parsing a top level class or module, use the (module-)class itself to look up variable definitions
      val parent = if ((sym.is(Flags.Module) || sym.isClass) && site.is(Flags.Package)) sym
                   else site
      expandVariables(cookedDocComment(sym, docStr), sym, parent)
    }

    private def template(raw: String): String =
      removeSections(raw, "@define")

    private def defines(raw: String): List[String] = {
      val sections = tagIndex(raw)
      val defines = sections filter { startsWithTag(raw, _, "@define") }
      val usecases = sections filter { startsWithTag(raw, _, "@usecase") }
      val end = startTag(raw, (defines ::: usecases).sortBy(_._1))

      defines map { case (start, end) => raw.substring(start, end) }
    }

    private def replaceInheritDocToInheritdoc(docStr: String): String  =
      docStr.replaceAll("""\{@inheritDoc\p{Zs}*\}""", "@inheritdoc")

    /** The cooked doc comment of an overridden symbol */
    protected def superComment(sym: Symbol)(using Context): Option[String] =
      allInheritedOverriddenSymbols(sym).iterator map (x => cookedDocComment(x)) find (_ != "")

    private val cookedDocComments = MutableSymbolMap[String]()

    /** The raw doc comment of symbol `sym`, minus usecase and define sections, augmented by
     *  missing sections of an inherited doc comment.
     *  If a symbol does not have a doc comment but some overridden version of it does,
     *  the doc comment of the overridden version is copied instead.
     */
    def cookedDocComment(sym: Symbol, docStr: String = "")(using Context): String = cookedDocComments.getOrElseUpdate(sym, {
      var ownComment =
        if (docStr.length == 0) ctx.docCtx.flatMap(_.docstring(sym).map(c => template(c.raw))).getOrElse("")
        else template(docStr)
      ownComment = replaceInheritDocToInheritdoc(ownComment)

      superComment(sym) match {
        case None =>
          // SI-8210 - The warning would be false negative when this symbol is a setter
          if (ownComment.indexOf("@inheritdoc") != -1 && ! sym.isSetter)
            scaladoc.println(s"${sym.span}: the comment for ${sym} contains @inheritdoc, but no parent comment is available to inherit from.")
          ownComment.replace("@inheritdoc", "<invalid inheritdoc annotation>")
        case Some(sc) =>
          if (ownComment == "") sc
          else expandInheritdoc(sc, merge(sc, ownComment, sym), sym)
      }
    })

    private def isMovable(str: String, sec: (Int, Int)): Boolean =
      startsWithTag(str, sec, "@param") ||
      startsWithTag(str, sec, "@tparam") ||
      startsWithTag(str, sec, "@return")

    def merge(src: String, dst: String, sym: Symbol, copyFirstPara: Boolean = false): String = {
      val srcSections  = tagIndex(src)
      val dstSections  = tagIndex(dst)
      val srcParams    = paramDocs(src, "@param", srcSections)
      val dstParams    = paramDocs(dst, "@param", dstSections)
      val srcTParams   = paramDocs(src, "@tparam", srcSections)
      val dstTParams   = paramDocs(dst, "@tparam", dstSections)
      val out          = new StringBuilder
      var copied       = 0
      var tocopy       = startTag(dst, dstSections dropWhile (!isMovable(dst, _)))

      if (copyFirstPara) {
        val eop = // end of comment body (first para), which is delimited by blank line, or tag, or end of comment
          (findNext(src, 0)(src.charAt(_) == '\n')) min startTag(src, srcSections)
        out append src.substring(0, eop).trim
        copied = 3
        tocopy = 3
      }

      def mergeSection(srcSec: Option[(Int, Int)], dstSec: Option[(Int, Int)]) = dstSec match {
        case Some((start, end)) =>
          if (end > tocopy) tocopy = end
        case None =>
          srcSec match {
            case Some((start1, end1)) =>
              out append dst.substring(copied, tocopy).trim
              out append "\n"
              copied = tocopy
              out append src.substring(start1, end1).trim
            case None =>
          }
      }

      //TODO: enable this once you know how to get `sym.paramss`
      /*
      for (params <- sym.paramss; param <- params)
        mergeSection(srcParams get param.name.toString, dstParams get param.name.toString)
      for (tparam <- sym.typeParams)
        mergeSection(srcTParams get tparam.name.toString, dstTParams get tparam.name.toString)

      mergeSection(returnDoc(src, srcSections), returnDoc(dst, dstSections))
      mergeSection(groupDoc(src, srcSections), groupDoc(dst, dstSections))
      */

      if (out.length == 0) dst
      else {
        out append dst.substring(copied)
        out.toString
      }
    }

    /**
     * Expand inheritdoc tags
     *  - for the main comment we transform the inheritdoc into the super variable,
     *  and the variable expansion can expand it further
     *  - for the param, tparam and throws sections we must replace comments on the spot
     *
     * This is done separately, for two reasons:
     * 1. It takes longer to run compared to merge
     * 2. The inheritdoc annotation should not be used very often, as building the comment from pieces severely
     * impacts performance
     *
     * @param parent The source (or parent) comment
     * @param child  The child (overriding member or usecase) comment
     * @param sym    The child symbol
     * @return       The child comment with the inheritdoc sections expanded
     */
    def expandInheritdoc(parent: String, child: String, sym: Symbol): String =
      if (child.indexOf("@inheritdoc") == -1)
        child
      else {
        val parentSections    = tagIndex(parent)
        val childSections     = tagIndex(child)
        val parentTagMap      = sectionTagMap(parent, parentSections)
        val parentNamedParams = Map() +
          ("@param"  -> paramDocs(parent, "@param", parentSections)) +
          ("@tparam" -> paramDocs(parent, "@tparam", parentSections)) +
          ("@throws" -> paramDocs(parent, "@throws", parentSections))

        val out         = new StringBuilder

        def replaceInheritdoc(childSection: String, parentSection: => String) =
          if (childSection.indexOf("@inheritdoc") == -1)
            childSection
          else
            childSection.replace("@inheritdoc", parentSection)

        def getParentSection(section: (Int, Int)): String = {

          def getSectionHeader = extractSectionTag(child, section) match {
            case param@("@param"|"@tparam"|"@throws")  => param + " "  + extractSectionParam(child, section)
            case other     => other
          }

          def sectionString(param: String, paramMap: Map[String, (Int, Int)]): String =
            paramMap.get(param) match {
              case Some(section) =>
                // Cleanup the section tag and parameter
                val sectionTextBounds = extractSectionText(parent, section)
                cleanupSectionText(parent.substring(sectionTextBounds._1, sectionTextBounds._2))
              case None =>
                scaladoc.println(s"""${sym.span}: the """" + getSectionHeader + "\" annotation of the " + sym +
                    " comment contains @inheritdoc, but the corresponding section in the parent is not defined.")
                "<invalid inheritdoc annotation>"
            }

          child.substring(section._1, section._1 + 7) match {
            case param@("@param "|"@tparam"|"@throws") =>
              sectionString(extractSectionParam(child, section), parentNamedParams(param.trim))
            case _                                     =>
              sectionString(extractSectionTag(child, section), parentTagMap)
          }
        }

        def mainComment(str: String, sections: List[(Int, Int)]): String =
          if (str.trim.length > 3)
            str.trim.substring(3, startTag(str, sections))
          else
            ""

        // Append main comment
        out.append("/**")
        out.append(replaceInheritdoc(mainComment(child, childSections), mainComment(parent, parentSections)))

        // Append sections
        for (section <- childSections)
          out.append(replaceInheritdoc(child.substring(section._1, section._2), getParentSection(section)))

        out.append("*/")
        out.toString
      }

    protected def expandVariables(initialStr: String, sym: Symbol, site: Symbol)(using Context): String = {
      val expandLimit = 10

      def expandInternal(str: String, depth: Int): String = {
        if (depth >= expandLimit)
          throw new ExpansionLimitExceeded(str)

        val out         = new StringBuilder
        var copied, idx = 0
        // excluding variables written as \$foo so we can use them when
        // necessary to document things like Symbol#decode
        def isEscaped = idx > 0 && str.charAt(idx - 1) == '\\'
        while (idx < str.length)
          if ((str charAt idx) != '$' || isEscaped)
            idx += 1
          else {
            val vstart = idx
            idx = skipVariable(str, idx + 1)
            def replaceWith(repl: String) = {
              out append str.substring(copied, vstart)
              out append repl
              copied = idx
            }
            variableName(str.substring(vstart + 1, idx)) match {
              case "super"    =>
                superComment(sym) foreach { sc =>
                  val superSections = tagIndex(sc)
                  replaceWith(sc.substring(3, startTag(sc, superSections)))
                  for (sec @ (start, end) <- superSections)
                    if (!isMovable(sc, sec)) out append sc.substring(start, end)
                }
              case "" => idx += 1
              case vname  =>
                lookupVariable(vname, site) match {
                  case Some(replacement) => replaceWith(replacement)
                  case None              =>
                    scaladoc.println(s"Variable $vname undefined in comment for $sym in $site")
                }
            }
          }
        if (out.length == 0) str
        else {
          out append str.substring(copied)
          expandInternal(out.toString, depth + 1)
        }
      }

      // We suppressed expanding \$ throughout the recursion, and now we
      // need to replace \$ with $ so it looks as intended.
      expandInternal(initialStr, 0).replace("""\$""", "$")
    }

    def defineVariables(sym: Symbol)(using Context): Unit = {
      val Trim = "(?s)^[\\s&&[^\n\r]]*(.*?)\\s*$".r

      val raw = ctx.docCtx.flatMap(_.docstring(sym).map(_.raw)).getOrElse("")
      defs(sym) ++= defines(raw).map {
        str => {
          val start = skipWhitespace(str, "@define".length)
          val (key, value) = str.splitAt(skipVariable(str, start))
          key.drop(start) -> value
        }
      } map {
        case (key, Trim(value)) =>
          variableName(key) -> value.replaceAll("\\s+\\*+$", "")
      }
    }

    /** Maps symbols to the variable -> replacement maps that are defined
     *  in their doc comments
     */
    private val defs = mutable.HashMap[Symbol, Map[String, String]]() withDefaultValue Map()

    /** Lookup definition of variable.
     *
     *  @param vble  The variable for which a definition is searched
     *  @param site  The class for which doc comments are generated
     */
    def lookupVariable(vble: String, site: Symbol)(using Context): Option[String] = site match {
      case NoSymbol => None
      case _        =>
        val searchList =
          if (site.flags.is(Flags.Module)) site :: site.info.baseClasses
          else site.info.baseClasses

        searchList collectFirst { case x if defs(x) contains vble => defs(x)(vble) } match {
          case Some(str) if str startsWith "$" => lookupVariable(str.tail, site)
          case res                             => res orElse lookupVariable(vble, site.owner)
        }
    }

    /** The position of the raw doc comment of symbol `sym`, or NoPosition if missing
     *  If a symbol does not have a doc comment but some overridden version of it does,
     *  the position of the doc comment of the overridden version is returned instead.
     */
    def docCommentPos(sym: Symbol)(using Context): Span =
      ctx.docCtx.flatMap(_.docstring(sym).map(_.span)).getOrElse(NoSpan)

    /** A version which doesn't consider self types, as a temporary measure:
     *  an infinite loop has broken out between superComment and cookedDocComment
     *  since r23926.
     */
    private def allInheritedOverriddenSymbols(sym: Symbol)(using Context): List[Symbol] =
      if (!sym.owner.isClass) Nil
      else sym.allOverriddenSymbols.toList.filter(_ != NoSymbol) //TODO: could also be `sym.owner.allOverrid..`
      //else sym.owner.ancestors map (sym overriddenSymbol _) filter (_ != NoSymbol)

    class ExpansionLimitExceeded(str: String) extends Exception
  }
}


text:
Another use case for the progress components is to show the current progress
for:

- downloading files
- uploading files
- progress of finishing a task
- etc

Since most of these items have a set range to operate on, we can make these
deterministic and manually set what the current progress is.

To create a deterministic progress component, all that is needed is to provide a
`value` prop that is between the `min` and `max` prop values to calculate a
percentage.


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="colorControlNormal">@android:color/darker_gray</item>
        <item name="colorControlActivated">@color/colorPrimaryDark</item>
        <item name="colorControlHighlight">@color/colorPrimaryDark</item>
    </style>

    <style name="AppTheme.ActionBar" parent="AppTheme.Dark">
        <item name="windowActionBar">true</item>
        <item name="windowNoTitle">false</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


text:
#include <stdexcept>
#include <typeinfo>

#include <boost/make_shared.hpp>
#include <boost/ptr_container/ptr_set.hpp>
#include <boost/test/unit_test.hpp>

#include <Eigen/Core>

#include <TudatCore/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h>
#include <TudatCore/Basics/testMacros.h>

#include <Tudat/Mathematics/BasicMathematics/linearAlgebraTypes.h>

#include <Assist/Basics/operatorOverloadFunctions.h>

#include "Stomi/Database/testParticleKick.h"

namespace stomi
{
namespace unit_tests
{

using namespace tudat::basic_astrodynamics::orbital_element_conversions;
using tudat::basic_mathematics::Vector6d;

//! Test fixture used to test the TestParticleKick struct.
struct TestParticleKickFixture
{
public:

    //! Constructor initializing valid parameters.
    TestParticleKickFixture( )
        : testParticleKickId( 1 ),
          testParticleSimulationId( 1 ),
          conjunctionEpoch( 1.23e4 ),
          conjunctionDistance( 2.0e7 ),
          preConjunctionEpoch( 5.67e2 ),
          preConjunctionDistance( 789.54e8 ),
          preConjunctionStateInKeplerianElements(
           ( Eigen::VectorXd( 6 ) << 112233.44, 0.456, 1.234, 2.345, 3.456, 4.567 ).finished( ) ),
          postConjunctionEpoch( 9.87e5 ),
          postConjunctionDistance( 987.65e8 ),
          postConjunctionStateInKeplerianElements(
           ( Eigen::VectorXd( 6 ) << 112244.55, 0.567, 1.345, 5.432, 6.543, 1.654 ).finished( ) )
    { }

    //! Declare parameters of test particle kick.

    //! Unique ID for test particle kick in database.
    int testParticleKickId;

    //! Test particle simulation ID.
    int testParticleSimulationId;

    //! Conjunction epoch [s].
    double conjunctionEpoch;

    //! Conjunction distance [m].
    double conjunctionDistance;

    //! Pre-Conjunction (opposition) epoch [s].
    double preConjunctionEpoch;

    //! Pre-Conjunction (opposition) distance [m].
    double preConjunctionDistance;

    //! Pre-Conjunction state of test particle in Keplerian elements.
    Vector6d preConjunctionStateInKeplerianElements;

    //! Post-Conjunction (opposition) epoch [s].
    double postConjunctionEpoch;

    //! Post-Conjunction (opposition) distance [m].
    double postConjunctionDistance;

    //! Post-Conjunction state of test particle in Keplerian elements.
    Vector6d postConjunctionStateInKeplerianElements;

    //! Get test particle kick created from specified parameters.
    database::TestParticleKickPointer getTestParticleKick( )
    {
        return boost::make_shared< database::TestParticleKick >(
                    database::TestParticleKick(
                        testParticleKickId, testParticleSimulationId,
                        conjunctionEpoch, conjunctionDistance,
                        preConjunctionEpoch, preConjunctionDistance,
                        preConjunctionStateInKeplerianElements,
                        postConjunctionEpoch, postConjunctionDistance,
                        postConjunctionStateInKeplerianElements ) );
    }

protected:

private:
};

BOOST_FIXTURE_TEST_SUITE( test_test_particle_kick, TestParticleKickFixture )

//! Test definition of typedef for test particle kick database struct.
BOOST_AUTO_TEST_CASE( testTestParticleKickTypedef )
{
    BOOST_CHECK( typeid( database::TestParticleKickTable )
                 == typeid( boost::ptr_set< database::TestParticleKick > ) );
}

//! Test correct construction of test particle kick.
BOOST_AUTO_TEST_CASE( testTestParticleKickStructContruction )
{
    // Create test particle kick.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );

    // Check that the test particle kick created contains all the data as required.
    BOOST_CHECK_EQUAL( testParticleKick->testParticleKickId, testParticleKickId );
    BOOST_CHECK_EQUAL( testParticleKick->testParticleSimulationId, testParticleSimulationId );
    BOOST_CHECK_EQUAL( testParticleKick->conjunctionEpoch, conjunctionEpoch );
    BOOST_CHECK_EQUAL( testParticleKick->conjunctionDistance, conjunctionDistance );
    BOOST_CHECK_EQUAL( testParticleKick->preConjunctionEpoch, preConjunctionEpoch );
    BOOST_CHECK_EQUAL( testParticleKick->preConjunctionDistance, preConjunctionDistance );
    {
        TUDAT_CHECK_MATRIX_BASE( testParticleKick->preConjunctionStateInKeplerianElements,
                                 preConjunctionStateInKeplerianElements )
                BOOST_CHECK_EQUAL(
                    testParticleKick->preConjunctionStateInKeplerianElements.coeff( row, col ),
                    preConjunctionStateInKeplerianElements.coeff( row, col ) );
    }
    BOOST_CHECK_EQUAL( testParticleKick->postConjunctionEpoch, postConjunctionEpoch );
    BOOST_CHECK_EQUAL( testParticleKick->postConjunctionDistance, postConjunctionDistance );
    {
        TUDAT_CHECK_MATRIX_BASE( testParticleKick->postConjunctionStateInKeplerianElements,
                                 postConjunctionStateInKeplerianElements )
                BOOST_CHECK_EQUAL(
                    testParticleKick->postConjunctionStateInKeplerianElements.coeff( row, col ),
                    postConjunctionStateInKeplerianElements.coeff( row, col ) );
    }
}

//! Test initialization of test particle kick with non-positive test particle kick ID.
BOOST_AUTO_TEST_CASE( testTestParticleKickNonPositiveTestParticleKickIdError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set test particle kick ID to invalid (non-positive) number.
    testParticleKickId = -1;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with non-positive simulation ID.
BOOST_AUTO_TEST_CASE( testTestParticleKickNonPositiveTestParticleSimulationIdError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set simulation ID to invalid (non-positive) number.
    testParticleSimulationId = -1;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative conjunction epoch.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativeConjunctionEpochError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set conjunction epoch to invalid (negative) number.
    conjunctionEpoch = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative conjunction distance.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativeConjunctionDistanceError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set conjunction distance to invalid (negative) number.
    conjunctionDistance = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with pre-conjunction epoch after conjunction epoch.
BOOST_AUTO_TEST_CASE( testTestParticleKickPreConjunctionAfterConjunctionEpochError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction epoch to value after conjunction epoch.
    preConjunctionEpoch = 2.34e5;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative pre-conjunction distance.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePreConjunctionDistanceError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction distance to invalid (negative) number.
    preConjunctionDistance = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with pre-conjunction distance less than conjunction
//! distance.
BOOST_AUTO_TEST_CASE( testTestParticleKickPreConjunctionLessThanConjunctionDistanceError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction distance to value less than conjunction distance.
    preConjunctionDistance = 1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative pre-conjunction semi-major axis.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePreConjunctionSemiMajorAxisError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction semi-major axis to invalid (negative) number.
    preConjunctionStateInKeplerianElements( semiMajorAxisIndex ) = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative pre-conjunction eccentricity.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePreConjunctionEccentricityError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction eccentricity to invalid (negative) number.
    preConjunctionStateInKeplerianElements( eccentricityIndex ) = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with >1.0 pre-conjunction eccentricity.
BOOST_AUTO_TEST_CASE( testTestParticleKickGreaterThanOnePreConjunctionEccentricityError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction eccentricity to invalid (greater than 1.0) number.
    preConjunctionStateInKeplerianElements( eccentricityIndex ) = 1.1;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative pre-conjunction inclination.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePreConjunctionInclinationError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set pre-conjunction eccentricity to invalid (negative) number.
    preConjunctionStateInKeplerianElements( inclinationIndex ) = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with conjunction epoch after post-conjunction epoch.
BOOST_AUTO_TEST_CASE( testTestParticleKickConjunctionAfterPostConjunctionEpochError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction epoch to value before conjunction epoch.
    postConjunctionEpoch = 0.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with post-conjunction distance less than conjunction
//! distance.
BOOST_AUTO_TEST_CASE( testTestParticleKickPostConjunctionLessThanConjunctionDistanceError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction distance to value less than conjunction distance.
    postConjunctionDistance = 1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative post-conjunction distance.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePostConjunctionDistanceError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction distance to invalid (negative) number.
    postConjunctionDistance = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative post-conjunction semi-major axis.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePostConjunctionSemiMajorAxisError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction semi-major axis to invalid (negative) number.
    postConjunctionStateInKeplerianElements( semiMajorAxisIndex ) = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative post-conjunction eccentricity.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePostConjunctionEccentricityError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction eccentricity to invalid (negative) number.
    postConjunctionStateInKeplerianElements( eccentricityIndex ) = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with >1.0 post-conjunction eccentricity.
BOOST_AUTO_TEST_CASE( testTestParticleKickGreaterThanOnePostConjunctionEccentricityError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction eccentricity to invalid (greater than 1.0) number.
    postConjunctionStateInKeplerianElements( eccentricityIndex ) = 1.1;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test initialization of test particle kick with negative post-conjunction inclination.
BOOST_AUTO_TEST_CASE( testTestParticleKickNegativePostConjunctionInclinationError )
{
    // Set flag to indicate if error is thrown to false.
    bool isError = false;

    // Set post-conjunction eccentricity to invalid (negative) number.
    postConjunctionStateInKeplerianElements( inclinationIndex ) = -1.0;

    // Try to create test particle kick.
    try { database::TestParticleKickPointer testParticleKick = getTestParticleKick( ); }

    // Catch expected run-time error.
    catch ( std::runtime_error& error ) { isError = true; }

    // Check that construction of test particle kick failed.
    BOOST_CHECK( isError );
}

//! Test comparison of TestParticleKick pointers using overloaded == operator.
BOOST_AUTO_TEST_CASE( testTestParticleKickEqualComparison )
{
    // Create TestParticleKick pointers.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );
    database::TestParticleKickPointer testParticleKick2 = getTestParticleKick( );

    // Check that operator is overloaded correctly.
    BOOST_CHECK( *testParticleKick == *testParticleKick2 );
}

//! Test comparison of TestParticleKick pointers using overloaded != operator.
BOOST_AUTO_TEST_CASE( testTestParticleKickNonEqualComparison )
{
    using namespace assist::basics::operator_overload_functions;

    // Create TestParticleKick pointers.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );

    testParticleSimulationId = 2;
    database::TestParticleKickPointer testParticleKick2 = getTestParticleKick( );

    // Check that operator is overloaded correctly.
    BOOST_CHECK( *testParticleKick != *testParticleKick2 );
}

//! Test comparison of TestParticleKick pointers using overloaded < operator.
BOOST_AUTO_TEST_CASE( testTestParticleKickLessThanComparison )
{
    // Create TestParticleKick pointers.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );

    conjunctionEpoch = 1.24e4;
    database::TestParticleKickPointer testParticleKick2 = getTestParticleKick( );

    // Check that operator is overloaded correctly.
    BOOST_CHECK( *testParticleKick < *testParticleKick2 );
}

//! Test comparison of TestParticleKick pointers using overloaded > operator.
BOOST_AUTO_TEST_CASE( testTestParticleKickGreaterThanComparison )
{
    using namespace assist::basics::operator_overload_functions;

    // Create TestParticleKick pointers.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );

    conjunctionEpoch = 1.24e4;
    database::TestParticleKickPointer testParticleKick2 = getTestParticleKick( );

    // Check that operator is overloaded correctly.
    BOOST_CHECK( *testParticleKick2 > *testParticleKick );
}

//! Test comparison of TestParticleKick pointers using overloaded <= operator.
BOOST_AUTO_TEST_CASE( testTestParticleKickLessThanOrEqualComparison )
{
    using namespace assist::basics::operator_overload_functions;

    // Create TestParticleKick pointers.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );

    conjunctionEpoch = 1.24e4;
    database::TestParticleKickPointer testParticleKick2 = getTestParticleKick( );

    // Check that operator is overloaded correctly.
    BOOST_CHECK( *testParticleKick <= *testParticleKick2 );
}

//! Test comparison of TestParticleKick pointers using overloaded >= operator.
BOOST_AUTO_TEST_CASE( testTestParticleKickGreaterThanOrEqualComparison )
{
    using namespace assist::basics::operator_overload_functions;

    // Create TestParticleKick pointers.
    database::TestParticleKickPointer testParticleKick = getTestParticleKick( );

    conjunctionEpoch = 1.24e4;
    database::TestParticleKickPointer testParticleKick2 = getTestParticleKick( );

    // Check that operator is overloaded correctly.
    BOOST_CHECK( *testParticleKick2 >= *testParticleKick );
}

//! Test sorting of TestParticleKickTable.
BOOST_AUTO_TEST_CASE( testTestParticleKickTableSorting )
{
    // Add TestParticleKick objects to table.
    database::TestParticleKickTable kickTable;

    // Insert kick with conjunction epoch = 1.23e4. Set test particle kick ID.
    testParticleKickId = 2;
    kickTable.insert( new database::TestParticleKick( *getTestParticleKick( ) ) );

    // Insert kick with later conjunction epoch. Set test particle kick ID.
    testParticleKickId = 3;
    conjunctionEpoch = 1.24e4;
    kickTable.insert( new database::TestParticleKick( *getTestParticleKick( ) ) );

    // Insert kick with earlier conjunction epoch. Set test particle kick ID.
    testParticleKickId = 1;
    conjunctionEpoch = 1.2e3;
    kickTable.insert( new database::TestParticleKick( *getTestParticleKick( ) ) );

    // Check that the table is sorted according to conjunction epoch.
    database::TestParticleKickTable::iterator iteratorKickTable = kickTable.begin( );
    BOOST_CHECK_EQUAL( iteratorKickTable->testParticleKickId, 1 );
    BOOST_CHECK_EQUAL( iteratorKickTable->conjunctionEpoch, 1.2e3 );

    iteratorKickTable++;
    BOOST_CHECK_EQUAL( iteratorKickTable->testParticleKickId, 2 );
    BOOST_CHECK_EQUAL( iteratorKickTable->conjunctionEpoch, 1.23e4 );

    iteratorKickTable++;
    BOOST_CHECK_EQUAL( iteratorKickTable->testParticleKickId, 3 );
    BOOST_CHECK_EQUAL( iteratorKickTable->conjunctionEpoch, 1.24e4 );
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace stomi