text:
// Copyright (C) 2022 ETH Zurich
// Copyright (C) 2022 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Norbert Podhorszki (pnorbert@ornl.gov)
//         Peter Doak (doakpw@ornl.gov)
//
// ADIOS2 writer.

#ifndef DCA_IO_ADIOS2_ADIOS2_WRITER_HPP
#define DCA_IO_ADIOS2_ADIOS2_WRITER_HPP

#include <cstring>  // std::memcpy
#include <complex>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>

#include "adios2.h"

#include "dca/function/domains.hpp"
#include "dca/io/buffer.hpp"
#include "dca/function/function.hpp"
#include "dca/linalg/matrix.hpp"
#include "dca/linalg/vector.hpp"

#include "dca/config/haves_defines.hpp"
#include "dca/parallel/no_concurrency/no_concurrency.hpp"
#ifdef DCA_HAVE_MPI
#include "dca/parallel/mpi_concurrency/mpi_concurrency.hpp"
#endif

namespace dca {
namespace io {
// dca::io
template <class CT>
class ADIOS2Writer {
public:
  typedef adios2::ADIOS file_type;

public:
  ADIOS2Writer() = delete;
  // In: verbose. If true, the writer outputs a short log whenever it is executed.
  ADIOS2Writer(adios2::ADIOS& adios, const CT* concurrency, bool verbose = false);
  ~ADIOS2Writer();

  constexpr bool is_reader() {
    return false;
  }
  constexpr bool is_writer() {
    return true;
  }

  void open_file(const std::string& file_name_ref, bool overwrite = true);
  void close_file();

  bool open_group(const std::string& new_path);
  void close_group();

  void begin_step();
  void end_step();

  std::string get_path(const std::string& name = "");

  template <typename arbitrary_struct_t>
  static void to_file(adios2::ADIOS& adios, const arbitrary_struct_t& arbitrary_struct,
                      const std::string& file_name);

  void erase(const std::string& name);

  bool execute(const std::string& name, bool value);
  template <typename Scalar>
  bool execute(const std::string& name, Scalar value);

  template <typename Scalar>
  bool execute(const std::string& name, const std::pair<Scalar, Scalar>& value);

  /** Adios has the concept of a rank local variable we can use this for sample.
   */
  template <typename Scalar>
  bool execute(const std::string& name, const std::vector<Scalar>& value, bool local = false);

  bool execute(const std::string& name, const std::string& value);

  bool execute(const std::string& name, const std::vector<std::string>& value);

  template <typename Scalar, std::size_t n>
  bool execute(const std::string& name, const std::vector<std::array<Scalar, n>>& value);

  template <typename Scalar>
  bool execute(const std::string& name, const std::vector<std::vector<Scalar>>& value);

  template <typename domain_type>
  bool execute(const std::string& name, const func::dmn_0<domain_type>& dmn);

  template <typename Scalar, typename domain_type, DistType DT>
  bool execute(const func::function<Scalar, domain_type, DT>& f);

  /** experimental distributed function interface
   */
  template <typename Scalar, typename domain_type, DistType DT>
  bool execute(const func::function<Scalar, domain_type, DT>& f, uint64_t start, uint64_t end);

  template <typename Scalar, typename domain_type, DistType DT>
  bool execute(const func::function<Scalar, domain_type, DT>& f, const std::vector<size_t>& start,
               const std::vector<size_t>& end);

  template <typename Scalar, typename domain_type, DistType DT>
  bool execute(const std::string& name, const func::function<Scalar, domain_type, DT>& f);

  /** experimental distributed function interface
   */
  template <typename Scalar, typename domain_type, DistType DT>
  bool execute(const std::string& name, const func::function<Scalar, domain_type, DT>& f,
               uint64_t start, uint64_t end);

  template <typename Scalar, typename domain_type, DistType DT>
  bool execute(const std::string& name, const func::function<Scalar, domain_type, DT>& f,
               const std::vector<size_t>& start, const std::vector<size_t>& end);

  template <typename Scalar>
  bool execute(const std::string& name, const dca::linalg::Vector<Scalar, dca::linalg::CPU>& A);

  template <typename Scalar>
  bool execute(const std::string& name, const dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A);

  template <typename Scalar>
  bool execute(const dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) {
    return execute(A.get_name(), A);
  }

  template <class T>
  bool execute(const std::string& name, const std::unique_ptr<T>& obj);

  template <class T>
  bool execute(const std::unique_ptr<T>& obj);

  bool execute(const std::string& name, const io::Buffer& buffer) {
    return execute(name, static_cast<io::Buffer::Container>(buffer));
  }

  void flush() {
    file_.PerformPuts();
  };

  operator bool() const {
    return (file_ ? true : false);
    // return static_cast<bool>(file_);
  }

  void lock() {
    mutex_.lock();
  }

  void unlock() {
    mutex_.unlock();
  }

  void set_verbose(bool verbose) {
    verbose_ = verbose;
  }

private:
  adios2::ADIOS& adios_;
  bool verbose_;
  const CT* concurrency_;

  /** For the case of sample it is necessary to explicitly write a rank "local" variable
   *  of this type.
   *  If this capability is required for other types add it on a case by case basis
   */
  template <typename Scalar>
  void write(const std::string& name, const std::vector<size_t>& size, const Scalar* data,
             bool local = false);

  void write(const std::string& name, const std::string& data);

  /** Write a distributed N-dimensional array with distribution info */
  template <typename Scalar>
  void write(const std::string& name, const std::vector<size_t>& size, const Scalar* data,
             const std::vector<size_t>& start, const std::vector<size_t>& count);

  template <typename T, typename... Args>
  void getVariable(const std::string& name, adios2::Variable<T>& var, const Args&... args);

  template <typename Scalar>
  void addAttribute(const std::string& set, const std::string& name,
                    const std::vector<size_t>& size, const Scalar* data);

  void addAttribute(const std::string& set, const std::string& name, const std::string& value);

  template <class T>
  std::string VectorToString(const std::vector<T>& v);

  adios2::IO io_;
  std::string io_name_;
  std::string file_name_;
  adios2::Engine file_;

  std::vector<std::string> my_paths_;
  std::mutex mutex_;
  std::vector<size_t> size_check_;
};

template <class CT>
template <typename T, typename... Args>
void ADIOS2Writer<CT>::getVariable(const std::string& name, adios2::Variable<T>& var,
                                   const Args&... args) {
  adios2::Variable<T> var_temp = io_.InquireVariable<T>(name);
  if (static_cast<bool>(var_temp) == false)
    var = io_.DefineVariable<T>(name, args...);
  else
    var = var_temp;
}

template <class CT>
template <typename arbitrary_struct_t>
void ADIOS2Writer<CT>::to_file(adios2::ADIOS& adios, const arbitrary_struct_t& arbitrary_struct,
                               const std::string& file_name) {
  ADIOS2Writer wr_obj(adios);
  wr_obj.open_file(file_name);
  arbitrary_struct.read_write(wr_obj);
  wr_obj.close_file();
}

template <class CT>
template <typename Scalar>
bool ADIOS2Writer<CT>::execute(const std::string& name, Scalar value) {
  const std::string full_name = get_path(name);
  std::vector<size_t> dims{1};
  write<Scalar>(full_name, dims, &value);
  return true;
}

template <class CT>
bool ADIOS2Writer<CT>::execute(const std::string& name, bool value) {
  const std::string full_name = get_path(name);
  std::vector<size_t> dims{1};
  int int_value = value;
  write<int>(full_name, dims, &int_value);
  return true;
}

template <class CT>
template <typename Scalar>
bool ADIOS2Writer<CT>::execute(const std::string& name, const std::pair<Scalar, Scalar>& value) {
  std::string full_name = get_path(name);
  std::vector<size_t> dims{2};
  write<Scalar>(full_name, dims, &value.first);
  return true;
}

template <class CT>
template <typename Scalar>
bool ADIOS2Writer<CT>::execute(const std::string& name, const std::vector<Scalar>& value,
                               const bool local) {
  if (value.size() > 0) {
    std::string full_name = get_path(name);
    std::vector<size_t> dims{value.size()};
    write<Scalar>(full_name, dims, value.data(), local);
  }
  return true;
}

template <class CT>
template <typename Scalar>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const std::vector<std::vector<Scalar>>& value) {
  std::string full_name = get_path(name);
  const size_t n = value.size();

  if (verbose_) {
    std::cout << "\t ADIOS2Writer: Write Vector of " << n << " vectors " << full_name << " sizes = (";
  }

  std::vector<size_t> sizes(n);
  size_t nTotal = 0;
  for (int i = 0; i < n; ++i) {
    sizes[i] = value[i].size();
    nTotal += sizes[i];
    if (verbose_) {
      std::cout << sizes[i];
      if (i < n - 1) {
        std::cout << ", ";
      }
    }
  }

  if (verbose_) {
    std::cout << ")\n";
  }

  adios2::Dims dims{nTotal};
  adios2::Variable<Scalar> vVecs;
  adios2::Dims start{0};
  getVariable<Scalar>(full_name, vVecs, dims, start, dims);

  typename adios2::Variable<Scalar>::Span span = file_.Put(vVecs);
  size_t pos = 0;
  for (const auto& a : value) {
    std::memcpy(span.data() + pos, a.data(), a.size() * sizeof(Scalar));
    pos += a.size();
  }

  io_.DefineAttribute<size_t>("_vector_sizes", sizes.data(), n, full_name);
  return true;
}

template <class CT>
template <typename Scalar, std::size_t n>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const std::vector<std::array<Scalar, n>>& value) {
  std::string full_name = get_path(name);

  if (verbose_) {
    std::cout << "\t ADIOS2Writer: Write Vector of Array " << full_name << " size {" << value.size()
              << ", " << n << "}\n";
  }

  adios2::Dims dims{value.size(), n};
  adios2::Variable<Scalar> v;
  adios2::Dims start{0, 0};
  getVariable(full_name, v, dims, start, dims);

  typename adios2::Variable<Scalar>::Span span = file_.Put(v);

  /*
    std::cout << "\t ADIOS2Writer: Vector of Array " << full_name << " size {" << value.size()
              << ", " << n << "} -> ADIOS2 Span size = " << span.size()
              << " ptr = " << static_cast<const void*>(span.data()) << "\n";
  */

  size_t pos = 0;
  for (const auto& a : value) {
    std::memcpy(span.data() + pos, a.data(), a.size() * sizeof(Scalar));
    pos += a.size();
  }
  return true;
}

template <class CT>
template <typename domain_type>
bool ADIOS2Writer<CT>::execute(const std::string& name, const func::dmn_0<domain_type>& dmn) {
  if (open_group(name)) {
    bool result = (execute("name", dmn.get_name()) && execute("elements", dmn.get_elements()));
    close_group();
    return result;
  }
  return false;
}

template <class CT>
template <typename Scalar, typename domain_type, DistType DT>
bool ADIOS2Writer<CT>::execute(const func::function<Scalar, domain_type, DT>& f) {
  if (f.size() == 0)
    return false;
  return execute(f.get_name(), f);
}

template <class CT>
template <typename Scalar, typename domain_type, DistType DT>
bool ADIOS2Writer<CT>::execute(const func::function<Scalar, domain_type, DT>& f, uint64_t start,
                               uint64_t end) {
  if (f.size() == 0)
    return false;
  return execute(f.get_name(), f, start, end);
}

template <class CT>
template <typename Scalar, typename domain_type, DistType DT>
bool ADIOS2Writer<CT>::execute(const func::function<Scalar, domain_type, DT>& f,
                               const std::vector<size_t>& start, const std::vector<size_t>& end) {
  if (f.size() == 0)
    return false;
  return execute(f.get_name(), f, start, end);
}

template <class CT>
template <typename Scalar, typename domain_type, DistType DT>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const func::function<Scalar, domain_type, DT>& f) {
  if (f.size() == 0)
    return false;

  const std::string full_name = get_path(name);

  std::vector<size_t> dims;
  for (int l = 0; l < f.signature(); ++l)
    dims.push_back(f.get_domain().get_subdomain_size(l));

  // be careful --> ADIOS2 is by default row-major, while the function-class is column-major !
  std::reverse(dims.begin(), dims.end());

  if constexpr (DT == dca::DistType::BLOCKED) {
    execute(name, f, f.get_start_subindex(), f.get_end_subindex());
  }
  else {
    write<Scalar>(full_name, dims, f.values());

    std::reverse(dims.begin(), dims.end());
    addAttribute(full_name, "name", f.get_name());
    addAttribute<size_t>(full_name, "domain-sizes", std::vector<size_t>{dims.size()}, dims.data());
  }
  return true;
}

template <class CT>
template <typename Scalar, typename domain_type, DistType DT>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const func::function<Scalar, domain_type, DT>& f, uint64_t start,
                               uint64_t end) {
  if (f.size() == 0)
    return true;

  const std::string full_name = get_path(name);

  std::vector<size_t> dims;
  for (int l = 0; l < f.signature(); ++l)
    dims.push_back(f.get_domain().get_subdomain_size(l));

  // be careful --> ADIOS2 is by default row-major, while the function-class is column-major !
  std::reverse(dims.begin(), dims.end());

  // see test/integration/parallel/func_distribution/function_distribution_test.cpp for
  // how to get the subindices spanned on this rank.

  if (verbose_) {
    std::cout << "\t ADIOS2Writer: Write function : " << f.get_name()
              << " in linear distributed manner, rank = " << concurrency_->id()
              << " shape = " << VectorToString(dims) << " start = " << start << " end = " << end
              << "\n";
  }

  // ADIOS2 needs start/count not start/end, and size_t type
  // Write this function as 1D array since we only have distribution in linearized space
  size_t nelems = 1;
  for (const auto d : dims) {
    nelems *= d;
  }
  std::vector<size_t> shape = {nelems};
  std::vector<size_t> s = {start};
  std::vector<size_t> count = {(end - start) + 1};

  /* TODO: must pass the correct data pointer here, not f.values() */
  write<Scalar>(full_name, shape, f.values(), s, count);

  std::reverse(dims.begin(), dims.end());
  addAttribute(full_name, "name", f.get_name());
  addAttribute<size_t>(full_name, "domain-sizes", std::vector<size_t>{dims.size()}, dims.data());
  return true;
}

template <class CT>
template <typename Scalar, typename domain_type, DistType DT>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const func::function<Scalar, domain_type, DT>& f,
                               const std::vector<size_t>& start, const std::vector<size_t>& end) {
  if (f.size() == 0)
    return true;

  const std::string full_name = get_path(name);

  std::vector<size_t> dims;
  for (int l = 0; l < f.signature(); ++l) {
    // working around totally broken function operator[] on ranks > 0
    dims.push_back(f.get_domain().get_subdomain_size(l));
  }

  int ndim = dims.size();

  // be careful --> ADIOS2 is by default row-major, while the function-class is column-major !
  std::reverse(dims.begin(), dims.end());

  // see test/integration/parallel/func_distribution/function_distribution_test.cpp for
  // how to get the subindices spanned on this rank.

  if (start.size() != ndim || end.size() != ndim) {
    std::cerr << "ADIOS2Writer<CT>::execute(,,,vector,vector): the size of start/end vectors"
              << " must equal to the number of dimensions of the function. "
              << " Here they were: dims = " << std::to_string(ndim)
              << " start size = " << std::to_string(start.size())
              << " end size = " << std::to_string(end.size()) << std::endl;
    // \todo we should be able to throw an exception now with the LINEAR and BLOCKED dist templates.
    return false;
  }

  // ADIOS2 takes size_t vector of start and count
  // reverse it here in the loop
  std::vector<size_t> s(ndim);
  std::vector<size_t> c(ndim);

  for (int i = 0; i < ndim; ++i) {
    s[ndim - i - 1] = static_cast<size_t>(start[i]);
    // parantheses are important because size_t is unsigned
    c[ndim - i - 1] = static_cast<size_t>((end[i] - start[i]) + 1);
  }

  if (verbose_) {
    std::cout << "\t ADIOS2Writer: Write function : " << f.get_name()
              << " in distributed manner, rank = " << concurrency_->id() << '\n'
              << "start:" << VectorToString(start) << '\n'
              << "end  :" << VectorToString(end) << '\n'
              << " shape = " << VectorToString(dims) << " start = " << VectorToString(s)
              << " count = " << VectorToString(c) << std::endl;
  }

  /* TODO: must pass the correct data pointer here, not f.values() */
  write<Scalar>(full_name, dims, f.data(), s, c);

  std::reverse(dims.begin(), dims.end());
  addAttribute(full_name, "name", f.get_name());
  addAttribute<size_t>(full_name, "domain-sizes", std::vector<size_t>{dims.size()}, dims.data());
  return true;
}

template <class CT>
template <typename Scalar>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const dca::linalg::Vector<Scalar, dca::linalg::CPU>& V) {
  std::string full_name = get_path(name);
  write<Scalar>(full_name, std::vector<size_t>{V.size()}, V.ptr());
  addAttribute(full_name, "name", V.get_name());
  return true;
}

template <class CT>
template <typename Scalar>
bool ADIOS2Writer<CT>::execute(const std::string& name,
                               const dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) {
  std::vector<size_t> dims{size_t(A.nrRows()), size_t(A.nrCols())};
  std::vector<Scalar> linearized(dims[0] * dims[1]);

  int linindex = 0;
  // Note: Matrices are row major, while ADIOS2 is column major
  for (int i = 0; i < A.nrRows(); ++i)
    for (int j = 0; j < A.nrCols(); ++j)
      linearized[linindex++] = A(i, j);

  std::string full_name = get_path(name);
  write<Scalar>(full_name, dims, linearized.data());

  addAttribute(full_name, "name", A.get_name());
  return true;
}

template <class CT>
template <class T>
bool ADIOS2Writer<CT>::execute(const std::string& name, const std::unique_ptr<T>& obj) {
  if (obj)
    return execute(name, *obj);
  return true;
}

template <class CT>
template <class T>
bool ADIOS2Writer<CT>::execute(const std::unique_ptr<T>& obj) {
  if (obj)
    return execute(*obj);
  return true;
}

template <class CT>
template <typename Scalar>
void ADIOS2Writer<CT>::write(const std::string& name, const std::vector<size_t>& size,
                             const Scalar* data, const bool local) {
  size_t ndim = size.size();
  adios2::Variable<Scalar> v;
  if (ndim == 0) {
    if (local) {
      std::vector<size_t> local{adios2::LocalValueDim};
      getVariable<Scalar>(name, v, local);
    }
    else {
      getVariable<Scalar>(name, v);
    }
  }
  else {
    if (local) {
      std::vector<size_t> empty;
      std::vector<size_t> start(ndim, 0);
      getVariable<Scalar>(name, v, empty, empty, size);
    }
    else {
      std::vector<size_t> start(ndim, 0);
      getVariable<Scalar>(name, v, size, start, size);
    }
  }
  file_.Put(v, data, adios2::Mode::Sync);
}

template <class CT>
template <typename Scalar>
void ADIOS2Writer<CT>::write(const std::string& name, const std::vector<size_t>& size,
                             const Scalar* data, const std::vector<size_t>& start,
                             const std::vector<size_t>& count) {
  size_t ndim = size.size();
  adios2::Variable<Scalar> v;
  if (ndim == 0) {
    getVariable<Scalar>(name, v);
  }
  else {
    getVariable<Scalar>(name, v, size, start, count);
  }
  file_.Put(v, data, adios2::Mode::Sync);
}

template <class CT>
template <typename Scalar>
void ADIOS2Writer<CT>::addAttribute(const std::string& set, const std::string& name,
                                    const std::vector<size_t>& size, const Scalar* data) {
  size_t ndim = size.size();
  if (ndim == 0) {
    io_.DefineAttribute(name, data, 1, set);
  }
  else if (ndim == 1) {
    io_.DefineAttribute(name, data, size[0], set);
  }
  else {
    throw(std::logic_error("ADIOS does not support multi-dimensional Attributes name = " + name +
                           " ndim = " + std::to_string(ndim) + "(" + __FUNCTION__ + ")"));
  }
}

template <class CT>
template <class T>
std::string ADIOS2Writer<CT>::VectorToString(const std::vector<T>& v) {
  std::stringstream ss;
  ss << "[";
  for (size_t i = 0; i < v.size(); ++i) {
    if (i != 0)
      ss << ",";
    ss << v[i];
  }
  ss << "]";
  return ss.str();
}

extern template class ADIOS2Writer<dca::parallel::NoConcurrency>;
#ifdef DCA_HAVE_MPI
extern template class ADIOS2Writer<dca::parallel::MPIConcurrency>;
#endif
}  // namespace io
}  // namespace dca

#endif  // DCA_IO_ADIOS2_ADIOS2_WRITER_HPP

repository: CompFUSE/DCA

repo_name: CompFUSE/DCA

extension: hpp


text:
// Copyright (c) 2021-2023 cions
// Licensed under the MIT License. See LICENSE for details

package leveldbcli

import (
	"testing"
)

func TestLevelDBFilenamePattern(t *testing.T) {
	matches := []string{
		"LOCK",
		"LOG",
		"LOG.old",
		"CURRENT",
		"CURRENT.bak",
		"CURRENT.000042",
		"MANIFEST-000042",
		"000042.ldb",
		"000042.log",
		"000042.sst",
		"000042.tmp",
	}

	for _, filename := range matches {
		if !leveldbFilenamePattern.MatchString(filename) {
			t.Errorf("%q should match", filename)
		}
	}

	dontMatches := []string{
		"LOCK2",
		"LOG old",
		"LOG.bak",
		"CURRENT.",
		"CURRENT.orig",
		"CURRENT.-000042",
		"CURRENT.000042a",
		"MANIFEST-",
		"MANIFEST--000042",
		"MANIFEST-000042a",
		".ldb",
		".log",
		".sst",
		".tmp",
		"42ldb",
		"-000042.log",
		"000042a.sst",
		"000042.tmp.gz",
	}

	for _, filename := range dontMatches {
		if leveldbFilenamePattern.MatchString(filename) {
			t.Errorf("%q should not match", filename)
		}
	}
}

license: MIT

repository: cions/leveldb-cli

license_type: permissive

repo_name: cions/leveldb-cli

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: Go

extension: go


text:
#include "userinterface.h"
#include "ui_userinterface.h"
#include "huffcompressor.h"

UserInterface::UserInterface(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::UserInterface)
{
    ui->setupUi(this);
    this->setWindowTitle("Huffman");

    dirModel = new QFileSystemModel(this);
}

UserInterface::~UserInterface()
{
    delete ui;
}

void UserInterface::on_compressRadio_clicked()
{
    dirModel = new QFileSystemModel();
    dirModel->setFilter(QDir::Files | QDir::AllDirs);
    dirModel->setRootPath("/");

    ui->actionButton->setText("Comprimir");
    ui->filesTree->setModel(dirModel);
}

void UserInterface::on_uncompressRadio_clicked()
{

    dirModel = new QFileSystemModel(this);
    dirModel->setFilter(QDir::Files | QDir::AllDirs);
    dirModel->setRootPath("/");
    QStringList filter;
    filter << "*.huff";

    dirModel->setNameFilters(filter);
    dirModel->setNameFilterDisables(false);

    ui->actionButton->setText("Descomprimir");
    ui->filesTree->setModel(dirModel);
}

void UserInterface::on_filesTree_clicked(const QModelIndex &index)
{
    QString option = ui->actionButton->text();

    if(option=="Comprimir")
    {
        QString selectedPath = dirModel->fileInfo(index).absoluteFilePath();
        QString compactedPath = selectedPath;
        compactedPath.remove(compactedPath.lastIndexOf('.'),compactedPath.size()-compactedPath.lastIndexOf('.'));
        compactedPath.append(".huff");
        ui->resourcePathLine->setText(selectedPath);
        ui->destinyPathLine->setText(compactedPath);

    }

    if(option=="Descomprimir")
    {
        QString selectedPath = dirModel->fileInfo(index).absoluteFilePath();
        QString destinyPath = selectedPath;
        destinyPath.remove(destinyPath.lastIndexOf('/')+1,destinyPath.size()-destinyPath.lastIndexOf('/'));

        ui->resourcePathLine->setText(selectedPath);
        ui->destinyPathLine->setText(destinyPath);
    }

//    HuffCompressor * compressor = new HuffCompressor();
//    compressor->compress(selectedPath, compactedPath);
//    compressor->uncompress("/home/paulinha/Desktop/tela.huff", "/home/paulinha/Desktop/tela.png");

}

void UserInterface::on_actionButton_clicked()
{

    QString option = ui->actionButton->text();

    if(option=="Comprimir")
    {
        QString selectedPath = ui->resourcePathLine->text();
        QString destinyPath = ui->destinyPathLine->text();
        HuffCompressor * compressor = new HuffCompressor();
        compressor->compress(selectedPath, destinyPath);

    }

    if(option=="Descomprimir")
    {
        QString selectedPath = ui->resourcePathLine->text();
        QString destinyPath = ui->destinyPathLine->text();
        HuffCompressor * compressor = new HuffCompressor();
        compressor->uncompress(selectedPath, destinyPath);

    }

}

repository: helivelton/huffman

repo_name: helivelton/huffman

extension: cpp


text:
package blackjack

import "testing"
import "github.com/stretchr/testify/assert"

func TestHiLoRunningCounter(t *testing.T) {
	c, l := NewHiLoRunningCounter()
	assert.Equal(t, 0, c.RunningCount())
	l(newCardUnchecked(Ace))
	assert.Equal(t, -1, c.RunningCount())
	l(newCardUnchecked(King))
	assert.Equal(t, -2, c.RunningCount())
	l(newCardUnchecked(Queen))
	assert.Equal(t, -3, c.RunningCount())
	l(newCardUnchecked(Jack))
	assert.Equal(t, -4, c.RunningCount())
	l(newCardUnchecked(Ten))
	assert.Equal(t, -5, c.RunningCount())
	l(newCardUnchecked(Nine))
	assert.Equal(t, -5, c.RunningCount())
	l(newCardUnchecked(Eight))
	assert.Equal(t, -5, c.RunningCount())
	l(newCardUnchecked(Seven))
	assert.Equal(t, -5, c.RunningCount())
	l(newCardUnchecked(Six))
	assert.Equal(t, -4, c.RunningCount())
	l(newCardUnchecked(Five))
	assert.Equal(t, -3, c.RunningCount())

	c.Reset()
	assert.Equal(t, 0, c.RunningCount())

	l(newCardUnchecked(Four))
	assert.Equal(t, 1, c.RunningCount())
	l(newCardUnchecked(Three))
	assert.Equal(t, 2, c.RunningCount())
	l(newCardUnchecked(Two))
	assert.Equal(t, 3, c.RunningCount())
}

func TestCSMCounter(t *testing.T) {
	c, cl, sl := NewCSMCounter()
	assert.Equal(t, 0, c.RunningCount())
	cl(newCardUnchecked(Ace))
	assert.Equal(t, -1, c.RunningCount())
	cl(newCardUnchecked(King))
	assert.Equal(t, -2, c.RunningCount())
	sl()
	assert.Equal(t, -2, c.RunningCount())
	cl(newCardUnchecked(Five))
	assert.Equal(t, -1, c.RunningCount())
	cl(newCardUnchecked(Five))
	assert.Equal(t, 0, c.RunningCount())
	cl(newCardUnchecked(Six))
	assert.Equal(t, 1, c.RunningCount())
	cl(newCardUnchecked(Seven))
	assert.Equal(t, 1, c.RunningCount())
	sl()
	assert.Equal(t, 1, c.RunningCount())
	sl()
	assert.Equal(t, 3, c.RunningCount())

	c.Reset()
	assert.Equal(t, 0, c.RunningCount())
}

repository: xushichangdesmond/blackjack

repo_name: xushichangdesmond/blackjack


text:
package scopes

import (
	"fmt"
	"strings"
)

// Scope represents a set of requested scopes
// https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/scopes/
type Scope uint64

const (
	// UserProfileRead allow the app to view the user's profile
	UserProfileRead = Scope(1 << iota)

	// UserRead allows the app to view the user's profile
	UserRead

	// UserWrite allow the app to write to the user's profile
	UserWrite

	// ViewablesRead View your viewable data
	ViewablesRead

	// DataRead view your data
	DataRead

	// DataWrite manage your data
	DataWrite

	// DataCreate write your data
	DataCreate

	// DataSearch search across your data
	DataSearch

	// BucketCreate creates new buckets
	BucketCreate

	// BucketRead view your buckets
	BucketRead

	// BucketUpdate update your buckets
	BucketUpdate

	// BucketDelete delete your buckets
	BucketDelete

	// CodeAll author or execute your code
	CodeAll

	// AccountRead view your product and service account
	AccountRead

	// AccountWrite manage your product and service accounts
	AccountWrite

	scopeEnd // should be last element
)

var scopes = [...]string{
	"user-profile:read",
	"user:read",
	"user:write",
	"viewables:read",
	"data:read",
	"data:write",
	"data:create",
	"data:search",
	"bucket:create",
	"bucket:read",
	"bucket:update",
	"bucket:delete",
	"code:all",
	"account:read",
	"account:write",
}

var invalidMask Scope

func init() {
	if 1<<len(scopes) != scopeEnd {
		panic(
			fmt.Sprintf(
				"More Scopes(%v) defined then in scopes array(%v)",
				uint64(scopeEnd),
				1<<len(scopes),
			),
		)
	}
	// setup invalidMask
	invalidMask = ^invalidMask
	for i := 0; i < len(scopes); i++ {
		invalidMask &= ^Scope(1 << i)
	}
}

// For takes a space seprated list of scopes and returns the Scope
// set for it.
func For(val string) Scope {
	var scope Scope
	scps := strings.Split(" ", strings.ToLower(val))
	if len(scps) == 0 {
		return scope
	}
	for i := range scps {
		s := strings.TrimSpace(scps[i])
		for j, scp := range scopes {
			if scp != s {
				continue
			}
			scope |= Scope(1 << j)
			break
		}
	}
	return scope

}

// Allows checks to see if s allows for all scopes in s1
func (s Scope) Allows(s1 Scope) bool { return s&s1 == s1 }

// IsValid checks to see if at least one known scope is encoded
func (s Scope) IsValid() bool { return s != 0 && s&invalidMask == 0 }

// String will return the string version of the set of scopes
func (s Scope) String() string {
	if s == 0 {
		// no scopes defined
		return ""
	}
	var str strings.Builder
	var first = true
	for i := 0; i < len(scopes); i++ {
		if ((1 << i) & s) == 0 {
			continue
		}
		if !first {
			str.WriteRune(' ')
		}
		str.WriteString(scopes[i])
		first = false
	}
	return str.String()
}

repository: gdey/forge-api-go-client

repo_name: gdey/forge-api-go-client


text:
#include <hpx/kokkos.hpp>

#include <hpx/kokkos/detail/polling_helper.hpp>
#include <hkr/executor/returning-executor.hpp>
#include <hkr/hpx-kokkos-resiliency-executor.hpp>
#include <hkr/hpx-kokkos-resiliency.hpp>

#include <random>

int test_func(int random_arg)
{
    return 42;
}

bool validate(int unused_arg)
{
    return true;
}

bool false_validate(int unused_arg)
{
    std::cout << "here" << std::endl;
    return false;
}

int main(int argc, char* argv[])
{
    Kokkos::initialize(argc, argv);

    {
        hpx::kokkos::detail::polling_helper helper;

        hpx::kokkos::returning_executor exec_;
        hpx::kokkos::returning_host_executor host_exec_;

        // Bulk aync facility
        auto exec =
            hpx::kokkos::resiliency::make_replay_executor(exec_, 3, validate);
        hpx::for_loop(hpx::execution::par.on(exec), 0, 100, test_func);

        auto host_exec = hpx::kokkos::resiliency::make_replay_executor(
            host_exec_, 3, false_validate);

        try
        {
            hpx::for_loop(hpx::execution::par.on(host_exec), 0, 100, test_func);
        }
        catch (...)
        {
            std::cout << "Error captured!" << std::endl;
        }

        std::cout << "Program ran correctly!" << std::endl;
    }

    Kokkos::finalize();

    return 0;
}

repository: NK-Nikunj/hpx-kokkos-resilience

repo_name: NK-Nikunj/hpx-kokkos-resilience

branch_name: refs/heads/main


text:
---
---
@article{Vallejos2017,
  abbr = {NatMet},
  title = {Normalizing single-cell RNA sequencing data: challenges and opportunities},
  author = {Catalina A Vallejos and Davide Risso and Antonio Scialdone and Sandrine Dudoit and John C Marioni},
  date = {2017/06/01},
  date-added = {2022-02-26 11:24:03 +0000},
  date-modified = {2022-02-26 11:24:03 +0000},
  doi = {10.1038/nmeth.4292},
  isbn = {1548-7105},
  journal = {Nature Methods},
  number = {6},
  pages = {565--571},
  abstract = {Single-cell transcriptomics is becoming an important component of the molecular biologist's toolkit. A critical step when analyzing data generated using this technology is normalization. However, normalization is typically performed using methods developed for bulk RNA sequencing or even microarray data, and the suitability of these methods for single-cell transcriptomics has not been assessed. We here discuss commonly used normalization approaches and illustrate how these can produce misleading results. Finally, we present alternative approaches and provide recommendations for single-cell RNA sequencing users.},
  url = {https://doi.org/10.1038/nmeth.4292},
  volume = {14},
  year = {2017}
}

@article{Vallejos2015,
  abbr = {PLOS},
  doi = {10.1371/journal.pcbi.1004333},
  author = {Vallejos Catalina A AND Marioni John C AND Richardson Sylvia},
  journal = {PLOS Computational Biology},
  publisher = {Public Library of Science},
  title = {BASiCS: Bayesian Analysis of Single-Cell Sequencing Data},
  year = {2015},
  month = {06},
  volume = {11},
  url = {https://doi.org/10.1371/journal.pcbi.1004333},
  pages = {1-18},
  selected = {false},
  abstract = {Single-cell mRNA sequencing can uncover novel cell-to-cell heterogeneity in gene expression levels in seemingly homogeneous populations of cells. However, these experiments are prone to high levels of unexplained technical noise, creating new challenges for identifying genes that show genuine heterogeneous expression within the population of cells under study. BASiCS (Bayesian Analysis of Single-Cell Sequencing data) is an integrated Bayesian hierarchical model where: (i) cell-specific normalisation constants are estimated as part of the model parameters, (ii) technical variability is quantified based on spike-in genes that are artificially introduced to each analysed cell’s lysate and (iii) the total variability of the expression counts is decomposed into technical and biological components. BASiCS also provides an intuitive detection criterion for highly (or lowly) variable genes within the population of cells under study. This is formalised by means of tail posterior probabilities associated to high (or low) biological cell-to-cell variance contributions, quantities that can be easily interpreted by users. We demonstrate our method using gene expression measurements from mouse Embryonic Stem Cells. Cross-validation and meaningful enrichment of gene ontology categories within genes classified as highly (or lowly) variable supports the efficacy of our approach.},
  number = {6}
}

@article{Eling2018,
  abbr = {CellSys},
  title = {Correcting the Mean-Variance Dependency for Differential Variability Testing Using Single-Cell RNA Sequencing Data},
  journal = {Cell Systems},
  volume = {7},
  number = {3},
  pages = {284-294.e12},
  year = {2018},
  issn = {2405-4712},
  doi = {https://doi.org/10.1016/j.cels.2018.06.011},
  url = {https://www.sciencedirect.com/science/article/pii/S2405471218302783},
  author = {Nils Eling and Arianne C Richard and Sylvia Richardson and John C Marioni and Catalina A Vallejos},
  keywords = {single-cell RNA sequencing, transcriptional noise, variability, immune activation, statistics, Bayesian},
  abstract = {Cell-to-cell transcriptional variability in otherwise homogeneous cell populations plays an important role in tissue function and development. Single-cell RNA sequencing can characterize this variability in a transcriptome-wide manner. However, technical variation and the confounding between variability and mean expression estimates hinder meaningful comparison of expression variability between cell populations. To address this problem, we introduce an analysis approach that extends the BASiCS statistical framework to derive a residual measure of variability that is not confounded by mean expression. This includes a robust procedure for quantifying technical noise in experiments where technical spike-in molecules are not available. We illustrate how our method provides biological insight into the dynamics of cell-to-cell expression variability, highlighting a synchronization of biosynthetic machinery components in immune cells upon activation. In contrast to the uniform up-regulation of the biosynthetic machinery, CD4+ T cells show heterogeneous up-regulation of immune-related and lineage-defining genes during activation and differentiation.}
}

@article{Vallejos2015,
  abbr = {JASS},
  author = {Catalina A Vallejos and Mark FJ Steel},
  title = {Objective Bayesian Survival Analysis Using Shape Mixtures of Log-Normal Distributions},
  journal = {Journal of the American Statistical Association},
  volume = {110},
  number = {510},
  pages = {697-710},
  year  = {2015},
  publisher = {Taylor & Francis},
  doi = {10.1080/01621459.2014.923316},
  URL = {https://doi.org/10.1080/01621459.2014.923316},
  eprint = {https://doi.org/10.1080/01621459.2014.923316},
  abstract = {Survival models such as the Weibull or log-normal lead to inference that is not robust to the presence of outliers. They also assume that all heterogeneity between individuals can be modeled through covariates. This article considers the use of infinite mixtures of lifetime distributions as a solution for these two issues. This can be interpreted as the introduction of a random effect in the survival distribution. We introduce the family of shape mixtures of log-normal distributions, which covers a wide range of density and hazard functions. Bayesian inference under nonsubjective priors based on the Jeffreys’ rule is examined and conditions for posterior propriety are established. The existence of the posterior distribution on the basis of a sample of point observations is not always guaranteed and a solution through set observations is implemented. In addition, we propose a method for outlier detection based on the mixture structure. A simulation study illustrates the performance of our methods under different scenarios and an application to a real dataset is provided. Supplementary materials for the article, which include R code, are available online.}
}

@article{Kapourani2021,
  abbr = {GenBio},
  abstract = {High-throughput single-cell measurements of DNA methylomes can quantify methylation heterogeneity and uncover its role in gene regulation. However, technical limitations and sparse coverage can preclude this task. scMET is a hierarchical Bayesian model which overcomes sparsity, sharing information across cells and genomic features to robustly quantify genuine biological heterogeneity. scMET can identify highly variable features that drive epigenetic heterogeneity, and perform differential methylation and variability analyses. We illustrate how scMET facilitates the characterization of epigenetically distinct cell populations and how it enables the formulation of novel hypotheses on the epigenetic regulation of gene expression. scMET is available at https://github.com/andreaskapou/scMET.},
  author = {Kapourani, Chantriolnt-Andreas and Argelaguet, Ricard and Sanguinetti, Guido and Vallejos, Catalina A},
  date = {2021/04/20},
  date-added = {2022-02-26 12:43:46 +0000},
  date-modified = {2022-02-26 12:43:46 +0000},
  doi = {10.1186/s13059-021-02329-8},
  id = {Kapourani2021},
  isbn = {1474-760X},
  journal = {Genome Biology},
  number = {1},
  pages = {114},
  title = {scMET: Bayesian modeling of DNA methylation heterogeneity at single-cell resolution},
  url = {https://doi.org/10.1186/s13059-021-02329-8},
  volume = {22},
  year = {2021},
  bdsk-url-1 = {https://doi.org/10.1186/s13059-021-02329-8},
  selected = {true}
}

@article {Cheng2021,
  author = {Cheng, Yipeng and Gadd, Danni A and Gieger, Christian and Monterrubio-Gómez, Karla and Zhang, Yufei and Berta, Imrich and Stam, Michael J and Szlachetka, Natalia and Lobzaev, Evgenii and Campbell, Archie and Nangle, Cliff and Walker, Rosie M and Fawns-Ritchie, Chloe and Peters, Annette and Rathmann, Wolfgang and Porteous, David J and Evans, Kathryn L and McIntosh, Andrew M and Cannings, Timothy I and Waldenberger, Melanie and Ganna, Andrea and McCartney, Daniel L and Vallejos, Catalina A and Marioni, Riccardo E},
  title = {DNA Methylation scores augment 10-year risk prediction of diabetes},
  elocation-id = {2021.11.19.21266469},
  year = {2021},
  doi = {10.1101/2021.11.19.21266469},
  publisher = {Cold Spring Harbor Laboratory Press},
  abstract = {Type 2 diabetes mellitus (T2D) is one of the most prevalent diseases in the world and presents a major health and economic burden, a notable proportion of which could be alleviated with improved early prediction and intervention. While standard risk factors including age, obesity, and hypertension have shown good predictive performance, we show that the use of CpG DNA methylation information leads to a significant improvement in the prediction of 10-year T2D incidence risk. Whilst previous studies have been largely constrained by linear assumptions and the use of CpGs one-at-the-time, we have adopted a more flexible approach based on a range of linear and tree-ensemble models for classification and time-to-event prediction. Using the Generation Scotland cohort (n=9,537) our best performing model (Area Under the Curve (AUC)=0.880, Precision Recall AUC (PRAUC)=0.539, McFadden’s R2=0.316) used a LASSO Cox proportional-hazards predictor and showed notable improvement in onset prediction, above and beyond standard risk factors (AUC=0.860, PRAUC=0.444 R2=0.261). Replication of the main finding was observed in an external test dataset (the German-based KORA study, p=3.7x10-4). Tree-ensemble methods provided comparable performance and future improvements to these models are discussed. Finally, we introduce MethylPipeR, an R package with accompanying user interface, for systematic and reproducible development of complex trait and incident disease predictors. While MethylPipeR was applied to incident T2D prediction with DNA methylation in our experiments, the package is designed for generalised development of predictive models and is applicable to a wide range of omics data and target traits.},
  url = {https://www.medrxiv.org/content/early/2021/11/21/2021.11.19.21266469},
  journal = {medRxiv},
  abbr = {medRxiv},
  pdf = {cheng2021.pdf},
  selected = {true}
}

@article{liley2021,
  title = {Model updating after interventions paradoxically introduces bias},
  pdf = {liley2021.pdf},
  journal = {arXiv},
  author={James Liley and Samuel R Emerson and Bilal A Mateen and Catalina A Vallejos and Louis J M Aslett and Sebastian J Vollmer},
  year={2021},
  arxiv={2010.11530},
  abbr={arXiv},
  primaryClass={stat.ML},
  selected = {true},
  abstract = {Machine learning is increasingly being used to generate prediction models for use in a number of real-world settings, from credit risk assessment to clinical decision support. Recent discussions have highlighted potential problems in the updating of a predictive score for a binary outcome when an existing predictive score forms part of the standard workflow, driving interventions. In this setting, the existing score induces an additional causative pathway which leads to miscalibration when the original score is replaced. We propose a general causal framework to describe and address this problem, and demonstrate an equivalent formulation as a partially observed Markov decision process. We use this model to demonstrate the impact of such `naive updating' when performed repeatedly. Namely, we show that successive predictive scores may converge to a point where they predict their own effect, or may eventually tend toward a stable oscillation between two values, and we argue that neither outcome is desirable. Furthermore, we demonstrate that even if model-fitting procedures improve, actual performance may worsen. We complement these findings with a discussion of several potential routes to overcome these issues.}
}

@article{Richter2021,
  abbr = {NatCom},
  abstract = {Single-cell RNA-seq reveals the role of pathogenic cell populations in development and progression of chronic diseases. In order to expand our knowledge on cellular heterogeneity, we have developed a single-nucleus RNA-seq2 method tailored for the comprehensive analysis of the nuclear transcriptome from frozen tissues, allowing the dissection of all cell types present in the liver, regardless of cell size or cellular fragility. We use this approach to characterize the transcriptional profile of individual hepatocytes with different levels of ploidy, and have discovered that ploidy states are associated with different metabolic potential, and gene expression in tetraploid mononucleated hepatocytes is conditioned by their position within the hepatic lobule. Our work reveals a remarkable crosstalk between gene dosage and spatial distribution of hepatocytes.},
  author = {Richter, M. L. and Deligiannis, I. K. and Yin, K. and Danese, A. and Lleshi, E. and Coupland, P. and Vallejos, C. A. and Matchett, K. P. and Henderson, N. C. and Colome-Tatche, M. and Martinez-Jimenez, C. P.},
  date = {2021/07/12},
  doi = {10.1038/s41467-021-24543-5},
  id = {Richter2021},
  isbn = {2041-1723},
  journal = {Nature Communications},
  number = {1},
  pages = {4264},
  title = {Single-nucleus RNA-seq2 reveals functional crosstalk between liver zonation and ploidy},
  url = {https://doi.org/10.1038/s41467-021-24543-5},
  volume = {12},
  year = {2021},
  }

@article {Liley2021.08.06.21261593,
  abbr = {medRxiv},
  author = {Liley, James and Bohner, Gergo and Emerson, Samuel R. and Mateen, Bilal A. and Borland, Katie and Carr, David and Heald, Scott and Oduro, Samuel D. and Ireland, Jill and Moffat, Keith and Porteous, Rachel and Riddell, Stephen and Cunningham, Nathan and Holmes, Chris and Payne, Katrina and Vollmer, Sebastian J. and Vallejos, Catalina A. and Aslett, Louis J. M.},
  title = {Development and assessment of a machine learning tool for predicting emergency admission in Scotland},
  elocation-id = {2021.08.06.21261593},
  year = {2021},
  doi = {10.1101/2021.08.06.21261593},
  publisher = {Cold Spring Harbor Laboratory Press},
  abstract = {Avoiding emergency hospital admission (EA) is advantageous to individual health and the healthcare system. We develop a statistical model estimating risk of EA for most of the Scottish population (\> 4.8M individuals) using electronic health records, such as hospital episodes and prescribing activity. We demonstrate good predictive accuracy (AUROC 0.80), calibration and temporal stability. We find strong prediction of respiratory and metabolic EA, show a substantial risk contribution from socioeconomic decile, and highlight an important problem in model updating. Our work constitutes a rare example of a population-scale machine learning score to be deployed in a healthcare setting.Competing Interest StatementThe authors have declared no competing interest.Funding StatementJL, CAV and LJMA were partially supported by Wave 1 of The UKRI Strategic Priorities Fund under the EPSRC Grant EP/T001569/1, particularly the "Health" theme within that grant and The Alan Turing Institute; JL, BAM, CAV, LJMA and SJV were partially supported by Health Data Research UK, an initiative funded by UK Research and Innovation, Department of Health and Social Care (England), the devolved administrations, and leading medical research charities; SJV, NC and GB were partially supported by the University of Warwick Impact Fund. SRE is funded by the EPSRC doctoral training partnership (DTP) at Durham University, grant reference EP/R513039/1; LJMA was partially supported by a Health Programme Fellowship at The Alan Turing Institute; CAV was supported by a Chancellor{\textquoteright}s Fellowship provided by the University of Edinburgh.Author DeclarationsI confirm all relevant ethical guidelines have been followed, and any necessary IRB and/or ethics committee approvals have been obtained.YesThe details of the IRB/oversight body that provided approval or exemption for the research described are given below:This study and the use of NHS data was approved by the Public Benefit and Privacy Panel for Health and Social Care (study number 1718-0370; approval evidenced in application outcome minutes for 2018/19 at https://www.informationgovernance.scot.nhs.uk/pbpphsc/application-outcomes/ ). In addition, accessing data was approved by the Public Health Scotland National Safe Haven, through the the electronic Data Research and Innovation Service (eDRIS) and the Public Benefit and Privacy Panel (PBPP) (study number 1718-0370). All studies have been conducted in accordance with information governance standards; data had no patient identifiers available to the researchers. This work was conducted in accordance with UK data governance regulations under PBPP application number eDRIS 1718-0370 All necessary patient/participant consent has been obtained and the appropriate institutional forms have been archived.YesI understand that all clinical trials and any other prospective interventional studies must be registered with an ICMJE-approved registry, such as ClinicalTrials.gov. I confirm that any such study reported in the manuscript has been registered and the trial registration ID is provided (note: if posting a prospective study registered retrospectively, please provide a statement in the trial ID field explaining why the study was not registered in advance).YesI have followed all appropriate research reporting guidelines and uploaded the relevant EQUATOR Network research reporting checklist(s) and other pertinent material as supplementary files, if applicable.YesRaw data for this project are patient-level NHS Scotland health records, and are confidential. Due to the confidential nature of the data used, all analysis took place on remote {\textquoteright}safe havens{\textquoteright}, without access to internet, software updates or unpublished software. Information Governance training was required for all researchers accessing the analysis environment. Moreover, to avoid the risk of accidental disclosure of sensitive information, an independent team carried out statistical disclosure control checks to all data exports, including the outputs presented in this manuscript. All analysis code and co-ordinates required to reproduce our Figures are available in github.com/jamesliley/SPARRAv4 https://github.com/jamesliley/SPARRAv4},
  url = {https://www.medrxiv.org/content/early/2021/08/10/2021.08.06.21261593},
  eprint = {https://www.medrxiv.org/content/early/2021/08/10/2021.08.06.21261593.full.pdf},
  journal = {medRxiv},
  selected = {true}
}

@article {Maniatis2021.05.13.443959,
  abbr={bioRxiv},
  author = {Maniatis, Christos and Vallejos, Catalina A and Sanguinetti, Guido},
  title = {SCRaPL: hierarchical Bayesian modelling of associations in single cell multi-omics data},
  elocation-id = {2021.05.13.443959},
  year = {2021},
  doi = {10.1101/2021.05.13.443959},
  publisher = {Cold Spring Harbor Laboratory},
  abstract = {Single-cell multi-omics assays offer unprecedented opportunities to explore gene regulation at cellular level. However, high levels of technical noise and data sparsity frequently lead to a lack of statistical power in correlative analyses, identifying very few, if any, significant associations between different molecular layers. Here we propose SCRaPL, a novel computational tool that increases power by carefully modelling noise in the experimental systems. We show on real and simulated multi-omics single-cell data sets that SCRaPL achieves higher sensitivity and better robustness in identifying correlations, while maintaining a similar level of false positives as standard analyses based on Pearson correlation.Competing Interest StatementThe authors have declared no competing interest.},
  url = {https://www.biorxiv.org/content/early/2021/05/14/2021.05.13.443959},
  eprint = {https://www.biorxiv.org/content/early/2021/05/14/2021.05.13.443959.full.pdf},
  journal = {bioRxiv}
}

@article{Lahnemann2020,
abbr = {GenBio},
  abstract = {The recent boom in microfluidics and combinatorial indexing strategies, combined with low sequencing costs, has empowered single-cell sequencing technology. Thousands---or even millions---of cells analyzed in a single experiment amount to a data revolution in single-cell biology and pose unique data science problems. Here, we outline eleven challenges that will be central to bringing this emerging field of single-cell data science forward. For each challenge, we highlight motivating research questions, review prior work, and formulate open problems. This compendium is for established researchers, newcomers, and students alike, highlighting interesting and rewarding problems for the coming years.},
  author = {L{\"a}hnemann, David and K{\"o}ster, Johannes and Szczurek, Ewa and McCarthy, Davis J. and Hicks, Stephanie C. and Robinson, Mark D. and Vallejos, Catalina A. and Campbell, Kieran R. and Beerenwinkel, Niko and Mahfouz, Ahmed and Pinello, Luca and Skums, Pavel and Stamatakis, Alexandros and Attolini, Camille Stephan-Otto and Aparicio, Samuel and Baaijens, Jasmijn and Balvert, Marleen and Barbanson, Buys de and Cappuccio, Antonio and Corleone, Giacomo and Dutilh, Bas E. and Florescu, Maria and Guryev, Victor and Holmer, Rens and Jahn, Katharina and Lobo, Thamar Jessurun and Keizer, Emma M. and Khatri, Indu and Kielbasa, Szymon M. and Korbel, Jan O. and Kozlov, Alexey M. and Kuo, Tzu-Hao and Lelieveldt, Boudewijn P. F. and Mandoiu, Ion I. and Marioni, John C. and Marschall, Tobias and M{\"o}lder, Felix and Niknejad, Amir and Raczkowski, Lukasz and Reinders, Marcel and Ridder, Jeroen de and Saliba, Antoine-Emmanuel and Somarakis, Antonios and Stegle, Oliver and Theis, Fabian J. and Yang, Huan and Zelikovsky, Alex and McHardy, Alice C. and Raphael, Benjamin J. and Shah, Sohrab P. and Sch{\"o}nhuth, Alexander},
  date = {2020/02/07},
  doi = {10.1186/s13059-020-1926-6},
  id = {L{\"a}hnemann2020},
  isbn = {1474-760X},
  journal = {Genome Biology},
  number = {1},
  pages = {31},
  title = {Eleven grand challenges in single-cell data science},
  url = {https://doi.org/10.1186/s13059-020-1926-6},
  volume = {21},
  year = {2020},
  bdsk-url-1 = {https://doi.org/10.1186/s13059-020-1926-6}
}

@article{doi:10.1161/CIRCULATIONAHA.119.042960,
  abbr = {Circ},
  author = {Andrew R. Chapman  and Philip D. Adamson  and Anoop S.V. Shah  and Atul Anand  and Fiona E. Strachan  and Amy V. Ferry  and Kuan Ken Lee  and Colin Berry  and Iain Findlay  and Anne Cruikshank  and Alan Reid  and Alasdair Gray  and Paul O. Collinson  and Fred Apple  and David A. McAllister  and Donogh Maguire  and Keith A.A. Fox  and Catalina A. Vallejos  and Catriona Keerie  and Christopher J. Weir  and David E. Newby  and Nicholas L. Mills  and Christopher Tuck  and Anda Bularga  and Ryan Wereski  and Dennis Sandeman  and Catherine L. Stables  and Athanasios Tsanasis  and Lucy Marshall  and Stacey D. Stewart  and Takeshi Fujisawa  and Mischa Hautvast  and Jean McPherson  and Lynn McKinlay  and Simon Walker  and Ian Ford  and Simon Walker  and Shannon Amoils  and Jennifer Stevens  and John Norrie  and Jack Andrews  and Phil Adamson  and Alastair Moss  and Mohamed Anwar  and John Hung  and Simon Walker  and Jonathan Malo  and Colin Fischbacher  and Bernard Croal  and Stephen J. Leslie  and Richard Parker  and Allan Walker  and Ronnie Harkess  and Chris Tuck  and Tony Wackett  and Roma Armstrong  and Marion Flood  and Laura Stirling  and Claire MacDonald  and Imran Sadat  and Frank Finlay  and Heather Charles  and Pamela Linksted  and Stephen Young  and Bill Alexander  and Chris Duncan },
  title = {High-Sensitivity Cardiac Troponin and the Universal Definition of Myocardial Infarction},
  journal = {Circulation},
  volume = {141},
  number = {3},
  pages = {161-171},
  year = {2020},
  doi = {10.1161/CIRCULATIONAHA.119.042960},
  abstract = {Background: The introduction of more sensitive cardiac troponin assays has led to increased recognition of myocardial injury in acute illnesses other than acute coronary syndrome. The Universal Definition of Myocardial Infarction recommends high-sensitivity cardiac troponin testing and classification of patients with myocardial injury based on pathogenesis, but the clinical implications of implementing this guideline are not well understood.
    Methods: In a stepped-wedge cluster randomized, controlled trial, we implemented a high-sensitivity cardiac troponin assay and the recommendations of the Universal Definition in 48 282 consecutive patients with suspected acute coronary syndrome. In a prespecified secondary analysis, we compared the primary outcome of myocardial infarction or cardiovascular death and secondary outcome of noncardiovascular death at 1 year across diagnostic categories.
	Results: Implementation increased the diagnosis of type 1 myocardial infarction by 11% (510/4471), type 2 myocardial infarction by 22% (205/916), and acute and chronic myocardial injury by 36% (443/1233) and 43% (389/898), respectively. Compared with those without myocardial injury, the rate of the primary outcome was highest in those with type 1 myocardial infarction (cause-specific hazard ratio [HR] 5.64 [95% CI, 5.12–6.22]), but was similar across diagnostic categories, whereas noncardiovascular deaths were highest in those with acute myocardial injury (cause specific HR 2.65 [95% CI, 2.33–3.01]). Despite modest increases in antiplatelet therapy and coronary revascularization after implementation in patients with type 1 myocardial infarction, the primary outcome was unchanged (cause specific HR 1.00 [95% CI, 0.82–1.21]). Increased recognition of type 2 myocardial infarction and myocardial injury did not lead to changes in investigation, treatment or outcomes.
    Conclusions: Implementation of high-sensitivity cardiac troponin assays and the recommendations of the Universal Definition of Myocardial Infarction identified patients at high-risk of cardiovascular and noncardiovascular events but was not associated with consistent increases in treatment or improved outcomes. Trials of secondary prevention are urgently required to determine whether this risk is modifiable in patients without type 1 myocardial infarction.},
  URL = {https://www.ahajournals.org/doi/abs/10.1161/CIRCULATIONAHA.119.042960},
  eprint = {https://www.ahajournals.org/doi/pdf/10.1161/CIRCULATIONAHA.119.042960}
}

@article{SHAH2018919,
  abbr = {Lancet},
  title = {High-sensitivity troponin in the evaluation of patients with suspected acute coronary syndrome: a stepped-wedge, cluster-randomised controlled trial},
  journal = {The Lancet},
  volume = {392},
  number = {10151},
  pages = {919-928},
  year = {2018},
  issn = {0140-6736},
  doi = {https://doi.org/10.1016/S0140-6736(18)31923-8},
  url = {https://www.sciencedirect.com/science/article/pii/S0140673618319238},
  author = {Anoop S V Shah and Atul Anand and Fiona E Strachan and Amy V Ferry and Kuan Ken Lee and Andrew R Chapman and Dennis Sandeman and Catherine L Stables and Philip D Adamson and Jack P M Andrews and Mohamed S Anwar and John Hung and Alistair J Moss and Rachel O'Brien and Colin Berry and Iain Findlay and Simon Walker and Anne Cruickshank and Alan Reid and Alasdair Gray and Paul O Collinson and Fred S Apple and David A McAllister and Donogh Maguire and Keith A A Fox and David E Newby and Christopher Tuck and Ronald Harkess and Richard A Parker and Catriona Keerie and Christopher J Weir and Nicholas L Mills and Lucy Marshall and Stacey D Stewart and Takeshi Fujisawa and Catalina A Vallejos and Athanasios Tsanas and Mischa Hautvast and Jean McPherson and Lynn McKinlay and Jonathan Malo and Colin M Fischbacher and Bernard L Croal and Stephen J Leslie and Allan Walker and Tony Wackett and Roma Armstrong and Laura Stirling and Claire MacDonald and Imran Sadat and Frank Finlay and Heather Charles and Pamela Linksted and Stephen Young and Bill Alexander and Chris Duncan},
  abstract = {Background: High-sensitivity cardiac troponin assays permit use of lower thresholds for the diagnosis of myocardial infarction, but whether this improves clinical outcomes is unknown. We aimed to determine whether the introduction of a high-sensitivity cardiac troponin I (hs-cTnI) assay with a sex-specific 99th centile diagnostic threshold would reduce subsequent myocardial infarction or cardiovascular death in patients with suspected acute coronary syndrome.
    Methods: In this stepped-wedge, cluster-randomised controlled trial across ten secondary or tertiary care hospitals in Scotland, we evaluated the implementation of an hs-cTnI assay in consecutive patients who had been admitted to the hospitals' emergency departments with suspected acute coronary syndrome. Patients were eligible for inclusion if they presented with suspected acute coronary syndrome and had paired cardiac troponin measurements from the standard care and trial assays. During a validation phase of 6–12 months, results from the hs-cTnI assay were concealed from the attending clinician, and a contemporary cardiac troponin I (cTnI) assay was used to guide care. Hospitals were randomly allocated to early (n=5 hospitals) or late (n=5 hospitals) implementation, in which the high-sensitivity assay and sex-specific 99th centile diagnostic threshold was introduced immediately after the 6-month validation phase or was deferred for a further 6 months. Patients reclassified by the high-sensitivity assay were defined as those with an increased hs-cTnI concentration in whom cTnI concentrations were below the diagnostic threshold on the contemporary assay. The primary outcome was subsequent myocardial infarction or death from cardiovascular causes at 1 year after initial presentation. Outcomes were compared in patients reclassified by the high-sensitivity assay before and after its implementation by use of an adjusted generalised linear mixed model. This trial is registered with ClinicalTrials.gov, number NCT01852123.
    Findings: Between June 10, 2013, and March 3, 2016, we enrolled 48 282 consecutive patients (61 [SD 17] years, 47% women) of whom 10 360 (21%) patients had cTnI concentrations greater than those of the 99th centile of the normal range of values, who were identified by the contemporary assay or the high-sensitivity assay. The high-sensitivity assay reclassified 1771 (17%) of 10 360 patients with myocardial injury or infarction who were not identified by the contemporary assay. In those reclassified, subsequent myocardial infarction or cardiovascular death within 1 year occurred in 105 (15%) of 720 patients in the validation phase and 131 (12%) of 1051 patients in the implementation phase (adjusted odds ratio for implementation vs validation phase 1·10, 95% CI 0·75 to 1·61; p=0·620).
    Interpretation: Use of a high-sensitivity assay prompted reclassification of 1771 (17%) of 10 360 patients with myocardial injury or infarction, but was not associated with a lower subsequent incidence of myocardial infarction or cardiovascular death at 1 year. Our findings question whether the diagnostic threshold for myocardial infarction should be based on the 99th centile derived from a normal reference population.}
}

@article{VALLEJOS201773,
  abbr = {EconStat},
  title = {Incorporating unobserved heterogeneity in Weibull survival models: A Bayesian approach},
  journal = {Econometrics and Statistics},
  volume = {3},
  pages = {73-88},
  year = {2017},
  issn = {2452-3062},
  doi = {https://doi.org/10.1016/j.ecosta.2017.01.005},
  url = {https://www.sciencedirect.com/science/article/pii/S2452306217300072},
  author = {Catalina A. Vallejos and Mark F.J. Steel},
  keywords = {Survival analysis, Frailty model, Robust modelling, Outlier detection, Posterior existence},
  abstract = {Outlying observations and other forms of unobserved heterogeneity can distort inference for survival datasets. The family of Rate Mixtures of Weibull distributions includes subject-level frailty terms as a solution to this issue. With a parametric mixing distribution assigned to the frailties, this family generates flexible hazard functions. Covariates are introduced via an Accelerated Failure Time specification for which the interpretation of the regression coefficients does not depend on the choice of mixing distribution. A weakly informative prior is proposed by combining the structure of the Jeffreys prior with a proper prior on some model parameters. This improper prior is shown to lead to a proper posterior distribution under easily satisfied conditions. By eliciting the proper component of the prior through the coefficient of variation of the survival times, prior information is matched for different mixing distributions. Posterior inference on subject-level frailty terms is exploited as a tool for outlier detection. Finally, the proposed methodology is illustrated using two real datasets, one concerning bone marrow transplants and another on cerebral palsy.}
}

@article{doi10.1126/science.aah4115,
  abbr = {Science},
  author = {Celia Pilar Martinez-Jimenez  and Nils Eling  and Hung-Chang Chen  and Catalina A. Vallejos  and Aleksandra A. Kolodziejczyk  and Frances Connor  and Lovorka Stojic  and Timothy F. Rayner  and Michael J. T. Stubbington  and Sarah A. Teichmann  and Maike de la Roche  and John C. Marioni  and Duncan T. Odom },
  title = {Aging increases cell-to-cell transcriptional variability upon immune stimulation},
  journal = {Science},
  volume = {355},
  number = {6332},
  pages = {1433-1436},
  year = {2017},
  doi = {10.1126/science.aah4115},
  url = {https://www.science.org/doi/abs/10.1126/science.aah4115},
  eprint = {https://www.science.org/doi/pdf/10.1126/science.aah4115},
  abstract = {Single-cell sequencing of mouse immune cells reveals how aging destabilizes a conserved transcriptional activation program. How and why the immune system becomes less effective with age are not well understood. Martinez-Jimenez et al. performed single-cell sequencing of CD4+ T cells in old and young mice of two species. In young mice, the gene expression program of early immune activation was tightly regulated and conserved between species. However, as mice aged, the expression of genes involved in pathways responding to immune cell stimulation was not as robust and exhibited increased cell-to-cell variability. Science, this issue p. 1433 Aging is characterized by progressive loss of physiological and cellular functions, but the molecular basis of this decline remains unclear. We explored how aging affects transcriptional dynamics using single-cell RNA sequencing of unstimulated and stimulated naïve and effector memory CD4+ T cells from young and old mice from two divergent species. In young animals, immunological activation drives a conserved transcriptomic switch, resulting in tightly controlled gene expression characterized by a strong up-regulation of a core activation program, coupled with a decrease in cell-to-cell variability. Aging perturbed the activation of this core program and increased expression heterogeneity across populations of cells in both species. These discoveries suggest that increased cell-to-cell transcriptional variability will be a hallmark feature of aging across most, if not all, mammalian tissues.}
}

@Article{Vallejos_2016,
  abbr = {RSS A},
  author    = {Catalina A. Vallejos and Mark F. J. Steel},
  journal   = {Journal of the Royal Statistical Society: Series A (Statistics in Society)},
  title     = {Bayesian survival modelling of university outcomes},
  year      = {2016},
  month     = {jul},
  number    = {2},
  pages     = {613--631},
  volume    = {180},
  abstract  = { Dropouts and delayed graduations are critical issues in higher education systems world wide. A key task in this context is to identify risk factors associated with these events, providing potential targets for mitigating policies. For this, we employ a discrete time competing risks survival model, dealing simultaneously with university outcomes and its associated temporal component. We define survival times as the duration of the student's enrolment at university and possible outcomes as graduation or two types of dropout (voluntary and involuntary), exploring the information recorded at admission time (e.g. educational level of the parents) as potential predictors. Although similar strategies have been previously implemented, we extend the previous methods by handling covariate selection within a Bayesian variable selection framework, where model uncertainty is formally addressed through Bayesian model averaging. Our methodology is general; however, here we focus on undergraduate students enrolled in three selected degree programmes of the Pontificia Universidad Católica de Chile during the period 2000–2011. Our analysis reveals interesting insights, highlighting the main covariates that influence students’ risk of dropout and delayed graduation.},
  doi       = {10.1111/rssa.12211},
  url = {https://doi.org/10.1111/rssa.12211},
  publisher = {Wiley},
}

@article{Vallejos2016,
  abbr = {GenBio},
  abstract = {Traditional differential expression tools are limited to detecting changes in overall expression, and fail to uncover the rich information provided by single-cell level data sets. We present a Bayesian hierarchical model that builds upon BASiCS to study changes that lie beyond comparisons of means, incorporating built-in normalization and quantifying technical artifacts by borrowing information from spike-in genes. Using a probabilistic approach, we highlight genes undergoing changes in cell-to-cell heterogeneity but whose overall expression remains unchanged. Control experiments validate our method's performance and a case study suggests that novel biological insights can be revealed. Our method is implemented in R and available at https://github.com/catavallejos/BASiCS.},
  author = {Vallejos, Catalina A. and Richardson, Sylvia and Marioni, John C.},
  date = {2016/04/15},
  doi = {10.1186/s13059-016-0930-3},
  id = {Vallejos2016},
  isbn = {1474-760X},
  journal = {Genome Biology},
  number = {1},
  pages = {70},
  title = {Beyond comparisons of means: understanding changes in gene expression at the single-cell level},
  url = {https://doi.org/10.1186/s13059-016-0930-3},
  volume = {17},
  year = {2016},
  bdsk-url-1 = {https://doi.org/10.1186/s13059-016-0930-3}
}

@article{Constantine-Cooke2023,
  abbr = {CGH},
  bibtex_show={true},
  selected={true},
  pdf = {Constantine-Cooke2023.pdf},
  title = {Longitudinal Fecal Calprotectin Profiles Characterize Disease Course Heterogeneity in {{Crohn}}'s Disease},
  author = {{Constantine-Cooke}, Nathan and {Monterrubio-G{\'o}mez}, Karla and Plevris, Nikolas and Derikx, Lauranne A.A.P. and Gros, Beatriz and Jones, Gareth-Rhys and Marioni, Riccardo E. and Lees, Charlie W. and Vallejos, Catalina A.},
  journal = {Clinical Gastroenterology and Hepatology},
  publisher = {{Elsevier}},
  issn = {1542-3565},
  doi = {10.1016/j.cgh.2023.03.026},
  urldate = {2023-05-24},
  selected = {true},
  year = {2023},
  abstract = {Background and Aims:
    The progressive nature of Crohn's disease is highly variable and hard to predict. In addition, symptoms correlate poorly with mucosal inflammation. There is therefore an urgent need to better characterize the heterogeneity of disease trajectories in Crohn's disease by utilizing objective markers of inflammation. We aimed to better understand this heterogeneity by clustering Crohn's disease patients with similar longitudinal fecal calprotectin profiles.

    Methods:
    We performed a retrospective cohort study at the Edinburgh IBD Unit, a tertiary referral center, and used latent class mixed models to cluster Crohn's disease subjects using fecal calprotectin observed within 5 years of diagnosis. Information criteria, alluvial plots, and cluster trajectories were used to decide the optimal number of clusters. Chi-square test, Fisher's exact test, and analysis of variance were used to test for associations with variables commonly assessed at diagnosis.

    Results:
    Our study cohort comprised 356 patients with newly diagnosed Crohn's disease and 2856 fecal calprotectin measurements taken within 5 years of diagnosis (median 7 per subject). Four distinct clusters were identified by characteristic calprotectin profiles: a cluster with consistently high fecal calprotectin and 3 clusters characterized by different downward longitudinal trends. Cluster membership was significantly associated with smoking (P = .015), upper gastrointestinal involvement (P < .001), and early biologic therapy (P < .001).

    Conclusions:
    Our analysis demonstrates a novel approach to characterizing the heterogeneity of Crohn's disease by using fecal calprotectin. The group profiles do not simply reflect different treatment regimens and do not mirror classical disease progression endpoints.}
}

@Article{Monterrubio2020,
  author    = {Monterrubio-G{\'o}mez, Karla and Constantine-Cooke, Nathan and Vallejos, Catalina A},
  title = {A review on competing risks methods for survival analysis},
  journal = {arXiv},
  abbr = {arXiv},
  doi = {10.48550/ARXIV.2212.05157},
  url = {https://arxiv.org/abs/2212.05157},
  selected = {true},
  year      = {2022},
  month     = {dec},
  abstract = {When modelling competing risks survival data, several techniques have been proposed in both the statistical and machine learning literature. State-of-the-art methods have extended classical approaches with more flexible assumptions that can improve predictive performance, allow high dimensional data and missing values, among others. Despite this, modern approaches have not been widely employed in applied settings. This article aims to aid the uptake of such methods by providing a condensed compendium of competing risks survival methods with a unified notation and interpretation across approaches. We highlight available software and, when possible, demonstrate their usage via reproducible R vignettes. Moreover, we discuss two major concerns that can affect benchmark studies in this context: the choice of performance metrics and reproducibility.}
  }

  @article{doi:10.1016/j.jacc.2022.10.025,
	author = {Caelan Taggart  and Karla Monterrubio-Gómez  and Andreas Roos  and Jasper Boeddinghaus  and Dorien M. Kimenai  and Erik Kadesjo  and Anda Bularga  and Ryan Wereski  and Amy Ferry  and Matthew Lowry  and Atul Anand  and Kuan Ken Lee  and Dimitrios Doudesis  and Ioanna Manolopoulou  and Thomas Nestelberger  and Luca Koechlin  and Pedro Lopez-Ayala  and Christian Mueller  and Nicholas L. Mills  and Catalina A. Vallejos  and Andrew R. Chapman },
	title = {Improving Risk Stratification for Patients With Type 2 Myocardial Infarction},
	journal = {Journal of the American College of Cardiology},
  abbr = {JACC},
	volume = {81},
	number = {2},
	pages = {156-168},
	year = {2023},
  month = {jan},
	doi = {10.1016/j.jacc.2022.10.025},
	URL = {https://www.jacc.org/doi/abs/10.1016/j.jacc.2022.10.025},
	eprint = {https://www.jacc.org/doi/pdf/10.1016/j.jacc.2022.10.025},
  abstract = {Background: Despite poor cardiovascular outcomes, there are no dedicated, validated risk stratification tools to guide investigation or treatment in type 2 myocardial infarction.
              Objectives: The goal of this study was to derive and validate a risk stratification tool for the prediction of death or future myocardial infarction in patients with type 2 myocardial infarction.
              Methods: The T2-risk score was developed in a prospective multicenter cohort of consecutive patients with type 2 myocardial infarction. Cox proportional hazards models were constructed for the primary outcome of myocardial infarction or death at 1 year using variables selected a priori based on clinical importance. Discrimination was assessed by area under the receiving-operating characteristic curve (AUC). Calibration was investigated graphically. The tool was validated in a single-center cohort of consecutive patients and in a multicenter cohort study from sites across Europe.
              Results:
              There were 1,121, 250, and 253 patients in the derivation, single-center, and multicenter validation cohorts, with the primary outcome occurring in 27% (297 of 1,121), 26% (66 of 250), and 14% (35 of 253) of patients, respectively. The T2-risk score incorporating age, ischemic heart disease, heart failure, diabetes mellitus, myocardial ischemia on electrocardiogram, heart rate, anemia, estimated glomerular filtration rate, and maximal cardiac troponin concentration had good discrimination (AUC: 0.76; 95% CI: 0.73-0.79) for the primary outcome and was well calibrated. Discrimination was similar in the consecutive patient (AUC: 0.83; 95% CI: 0.77-0.88) and multicenter (AUC: 0.74; 95% CI: 0.64-0.83) cohorts. T2-risk provided improved discrimination over the Global Registry of Acute Coronary Events 2.0 risk score in all cohorts.
              Conclusions:
              The T2-risk score performed well in different health care settings and could help clinicians to prognosticate, as well as target investigation and preventative therapies more effectively. (High-Sensitivity Troponin in the Evaluation of Patients With Suspected Acute Coronary Syndrome [High-STEACS]; NCT01852123)}
}

gha_language: JavaScript

extension: bib


text:
package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"github.com/suykerbuyk/irqmgr"
	"log"
	"net/http"
	//	"os"
)

func homePage(w http.ResponseWriter, r *http.Request) {
	staticHome := `
IrqMgr

John Suykerbuyk

From here you can:

View Every All IRQ Info

View just the IRQ Tallies

`
	fmt.Println("Endpoint Hit: homepage")
	fmt.Fprintf(w, staticHome)
}
func serveAllIrqTallies(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Endpoint Hit: serveIrqTallies")
	irqTallies, err := irqmgr.FetchIrqs()
	if err != nil {
		log.Fatal(err)
	}
	json.NewEncoder(w).Encode(irqTallies)
}
func setIrqAffinity(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Endpoint Hit: setIrqAffinity")
	var affinityReq irqmgr.SetSmpAffinityData
	err := json.NewDecoder(r.Body).Decode(&affinityReq)
	if err != nil {
		log.Fatal(err)
	}
	irqmgr.SetIrqAffinity(affinityReq.Irq, affinityReq.Affinity)
}

func serveJustIrqTallies(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Endpoint Hit: serveIrqTallies")
	irqTallies, err := irqmgr.FetchIrqs()
	if err != nil {
		log.Fatal(err)
	}
	json.NewEncoder(w).Encode(irqTallies.IrqsServicedByCPU)
}

func handleRequest() {
	fmt.Println("Entering handle request")
	irqMgrRouter := mux.NewRouter().StrictSlash(true)
	irqMgrRouter.HandleFunc("/", homePage)
	irqMgrRouter.HandleFunc("/all", serveAllIrqTallies)
	irqMgrRouter.HandleFunc("/just", serveJustIrqTallies)
	irqMgrRouter.HandleFunc("/set", setIrqAffinity).Methods("POST")
	log.Fatal(http.ListenAndServe(":10000", irqMgrRouter))
}

func main() {
	irqTallies, err := irqmgr.FetchIrqs()
	out, err := json.Marshal(irqTallies)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(out))
	handleRequest()
}

//affinity_hint  effective_affinity  effective_affinity_list  node  smp_affinity  smp_affinity_list  spurious

repository: suykerbuyk/irqmgr

repo_name: suykerbuyk/irqmgr


text:
package requests

import (
	"github.com/tuotoo/zhima/interfaces"
)

type ZhimaCreditEpContactPhoneGetRequest struct {
	phone         string // 电话号码
	productCode   string // 产品码
	transactionId string // 商户传入的业务流水号。此字段由商户生成，需确保唯一性，用于定位每一次请求，后续按此流水进行对帐。生成规则: 固定30位数字串，前17位为精确到毫秒的时间yyyyMMddhhmmssSSS，后13位为自增数字。

	interfaces.ZhimaRequestParams
}

func (m *ZhimaCreditEpContactPhoneGetRequest) InitBizParams(phone, productCode, transactionId string) {
	m.ApiParams = &map[string]string{}
	m.FileParams = &map[string]string{}

	(*m.ApiParams)["phone"] = phone
	m.phone = phone

	(*m.ApiParams)["product_code"] = productCode
	m.productCode = productCode

	(*m.ApiParams)["transaction_id"] = transactionId
	m.transactionId = transactionId
}

func (*ZhimaCreditEpContactPhoneGetRequest) GetApiMethodName() string {
	return "zhima.credit.ep.contact.phone.get"
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetApiParams() *map[string]string {
	return m.ApiParams
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetFileParams() *map[string]string {
	return m.FileParams
}

func (m *ZhimaCreditEpContactPhoneGetRequest) SetApiVersion(ApiVersion string) {
	m.ApiVersion = ApiVersion
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetApiVersion() string {
	return m.ApiVersion
}

func (m *ZhimaCreditEpContactPhoneGetRequest) SetScene(Scene string) {
	m.Scene = Scene
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetScene() string {
	return m.Scene
}

func (m *ZhimaCreditEpContactPhoneGetRequest) SetChannel(Channel string) {
	m.Channel = Channel
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetChannel() string {
	return m.Channel
}

func (m *ZhimaCreditEpContactPhoneGetRequest) SetPlatform(Platform string) {
	m.Platform = Platform
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetPlatform() string {
	return m.Platform
}

func (m *ZhimaCreditEpContactPhoneGetRequest) SetExtParams(ExtParams string) {
	m.ExtParams = ExtParams
}

func (m *ZhimaCreditEpContactPhoneGetRequest) GetExtParams() string {
	return m.ExtParams
}

repository: tuotoo/zhima

repo_name: tuotoo/zhima


text:
package main

import (
	"fmt"
	"strconv"

	"github.com/gdamore/tcell"
)

var (
	screen tcell.Screen
	x      = 0
	y      = 1
)

func main() {
	var err error
	screen, err = tcell.NewScreen()
	if err != nil {
		fmt.Println("NewScreen error:", err)
	}
	err = screen.Init()
	if err != nil {
		fmt.Println("screen Init error:", err)
	}

	screen.Clear()

	for i := 0; i < 379; i++ {
		printNum(i)
		style := tcell.StyleDefault.Foreground(tcell.Color(i)).Background(tcell.Color(i)).Dim(true)
		screen.SetContent(x, y, '▄', nil, style)
		x++
		screen.SetContent(x, y, '▄', nil, style)
		x += 2
		if x > 80 {
			x = 0
			y += 2
		}
		if i == 15 {
			i = 255
		}
	}

	screen.Show()
}

func printNum(num int) {
	word := strconv.FormatInt(int64(num), 10) + ":"
	if num < 10 {
		word = "  " + word
	} else if num < 100 {
		word = " " + word
	}
	if len(word)+x+2 > 80 {
		x = 0
		y += 2
	}
	style := tcell.StyleDefault.Foreground(tcell.ColorLightGray).Background(tcell.ColorBlack)
	for _, char := range word {
		screen.SetContent(x, y, char, nil, style)
		x++
	}

}

gha_license_id: NOASSERTION


text:
package simplereplication

import (
	"log"
	"sync"
	"time"

	"github.com/iaroslavscript/cacheman/lib/config"
	"github.com/iaroslavscript/cacheman/lib/sdk"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

const metricsSubsystem = "repl"
const binlogTypeOld = "old"
const QueueFullTimeoutMs = 100

type SimpleReplication struct {
	done  chan bool
	m     sync.RWMutex
	timer *time.Ticker

	activeData chan sdk.ReplItem

	CurrLog sdk.ReplLog
	NextLog sdk.ReplLog
	OldLog  sdk.ReplLog

	opsApiRequestsTotal   prometheus.Counter
	opsBinLogsTotal       prometheus.Counter
	opsBinLogRecordsTotal *prometheus.CounterVec
	opsBinLogBytes        *prometheus.CounterVec
}

func NewSimpleReplication(cfg *config.Config) *SimpleReplication {

	d := time.Duration(cfg.ReplicationRotateEveryMs) * time.Millisecond
	repl := SimpleReplication{
		done:       make(chan bool),
		activeData: make(chan sdk.ReplItem, cfg.ReplicationActiveQuequeSize),

		opsApiRequestsTotal: promauto.NewCounter(prometheus.CounterOpts{
			Namespace: sdk.MetricsNamespace,
			Subsystem: metricsSubsystem,
			Name:      "api_requests_total",
			Help:      "The total number of requests to replication API",
		}),

		opsBinLogsTotal: promauto.NewCounter(
			prometheus.CounterOpts{
				Namespace: sdk.MetricsNamespace,
				Subsystem: metricsSubsystem,
				Name:      "binlogs_total",
				Help:      "The total number of binary logs",
			}),

		opsBinLogRecordsTotal: promauto.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: sdk.MetricsNamespace,
				Subsystem: metricsSubsystem,
				Name:      "binlog_records_total",
				Help:      "The total number of records in binary logs grouped by log type",
			},
			[]string{"type"},
		),

		opsBinLogBytes: promauto.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: sdk.MetricsNamespace,
				Subsystem: metricsSubsystem,
				Name:      "binlog_bytes",
				Help:      "The size of binary logs in bytes grouped by log type",
			},
			[]string{"type"},
		),

		timer: time.NewTicker(d),
	}

	repl.NextLog.Info.Id = 2
	repl.CurrLog.Info.Id = 1
	repl.OldLog.Info.Id = 0

	// Init counter
	repl.opsApiRequestsTotal.Add(0.0)
	repl.opsBinLogsTotal.Add(0.0)
	repl.opsBinLogRecordsTotal.WithLabelValues(binlogTypeOld).Add(0.0)
	repl.opsBinLogBytes.WithLabelValues(binlogTypeOld).Add(0.0)

	return &repl
}

// TODO remove unnessasery copy of []bytes here
func (s *SimpleReplication) Add(item sdk.ReplItem) {

	s.opsApiRequestsTotal.Inc()

loop:
	for {
		select {
		case s.activeData <- item: // TODO remove unnessasery copy of []bytes here
			break loop
		default:
			log.Printf("replication ActiveQueque size(%d) full. Locked record id: %d. Sleep for %d milliseconds.",
				cap(s.activeData),
				item.Value.GetRecId(),
				QueueFullTimeoutMs,
			)
			time.Sleep(time.Duration(QueueFullTimeoutMs) * time.Millisecond) // Add waitingCounter Metrics
		}
	}
}

func (s *SimpleReplication) Start() {

	defer s.timer.Stop()

	for {
		select {
		case <-s.timer.C:
			s.tick()
			// TODO add sleep here to avoid busy loop
		case <-s.done:
			return
		}
	}
}

func (s *SimpleReplication) Close() {
	s.done <- true
}

func (s *SimpleReplication) tick() {

	s.m.Lock()
	defer s.m.Unlock()

	latest_id := sdk.LatestRecordId()

loop:
	for {
		// TODO
		// Some threads could be interupted after adding item to cache
		// but before pushing it to replication chan. In that case we
		// will not pull item and it will not be added to the binary log
		// until the next log rotation. So it's mandatory to check recId
		// in replayReplication() to prevent overwriting record by old one.

		select {
		case item := <-s.activeData: // TODO remove unnessasery copy of []bytes here

			s.NextLog.Data = append(s.NextLog.Data, item)

			if item.Value.GetRecId() > latest_id {
				break loop
			}

		default:
			break loop
		}

	}

//	TODO another way just decide how much we'd like to pull
//	Need to test it latelly
// 	n := len(s.activeData)
// loop1:
// 	for i := 0; i < n; i++ { // pull no more than we had a moment ago
// 		select {
// 		case item := <-s.activeData: // TODO remove unnessasery copy of []bytes here

// 			s.NextLog.Data = append(s.NextLog.Data, item)

// 		default:
// 			break loop1
// 		}
// 	}

	nextlog_n := len(s.NextLog.Data)

	if nextlog_n == 0 {
		return
	}

	s.OldLog.Info.Id++
	s.CurrLog.Info.Id++
	s.NextLog.Info.Id++

	currlog_n := len(s.CurrLog.Data)

	s.OldLog.Data = append(s.OldLog.Data, s.CurrLog.Data...)
	s.CurrLog.Data = make([]sdk.ReplItem, len(s.NextLog.Data))
	copy(s.CurrLog.Data, s.NextLog.Data)

	// the next log could be at least as big as it was before
	s.NextLog.Data = make([]sdk.ReplItem, 0, nextlog_n)

	s.opsBinLogRecordsTotal.WithLabelValues(binlogTypeOld).Add(float64(currlog_n))

	// Curently we are not counting bytes
	s.opsBinLogBytes.WithLabelValues(binlogTypeOld).Add(0.0)

	// it's better to unlock here or make a copy of nextlog and unlock
	// because we add only to next not to curr and old
	// but in that case we need two mutex (next_mutex and curr_old_mutex)

	s.opsBinLogsTotal.Inc()
	log.Printf("replication_log:%d buckets_sizes:[%d, %d]",
		s.CurrLog.Info.Id,
		len(s.OldLog.Data),
		len(s.CurrLog.Data),
	)

}

repository: iaroslavscript/cacheman

repo_name: iaroslavscript/cacheman


text:
LICENSE     = "LGPL"
DESCRIPTION = "Implementation of the Stringprep, Punycode and IDNA specifications defined by the IETF Internationalized Domain Names (IDN) working group."
SECTION = "libs"
PRIORITY    = "optional"
PR          = "r0"

inherit pkgconfig autotools

SRC_URI = "${GNU_MIRROR}/${PN}/${P}.tar.gz"

EXTRA_OECONF = " --disable-tld"

do_configure_prepend () {
	autoreconf -f -i -s
}

do_stage () {
	autotools_stage_all
}

repository: demsey/openembedded

repo_name: demsey/openembedded

branch_name: HEAD

extension: bb


text:
package gameserver

import (
	"fmt"

	"github.com/xiaonanln/typeconv"
	"github.com/xiaonanln/vacuum/ext/entity"
)

type GSClientProxy struct {
	GateID   GSGateID
	ClientID GSClientID
}

func newGSClientProxy(gateID GSGateID, clientID GSClientID) *GSClientProxy {
	return &GSClientProxy{
		GateID:   gateID,
		ClientID: clientID,
	}
}

func (cp *GSClientProxy) String() string {
	return fmt.Sprintf("GSClientProxy<%s@%s>", cp.ClientID, cp.GateID)
}

func (cp *GSClientProxy) callClient(entityID GSEntityID, methodName string, args []interface{}) {
	// call the gate
	entity.EntityID(cp.GateID).Call("CallClient", cp.ClientID, entityID, methodName, args)
}

// notify the client to change owner
func (cp *GSClientProxy) notifyChangeOwner(ownerID GSEntityID, otherID GSEntityID, otherKindName string) {
	entity.EntityID(cp.GateID).Call("NotifyClientChangeOwner", cp.ClientID, ownerID, otherID, otherKindName)
}

func (cp *GSClientProxy) getClientProxyData() interface{} {
	if cp != nil {
		return []interface{}{cp.GateID, cp.ClientID}
	} else {
		return nil
	}
}

func (cp *GSClientProxy) setClientProxyData(data interface{}) {
	datalist := data.([]interface{})
	cp.GateID = GSGateID(typeconv.String(datalist[0]))
	cp.ClientID = GSClientID(typeconv.String(datalist[1]))
}

repository: xiaonanln/vacuum

repo_name: xiaonanln/vacuum


text:
DESCRIPTION = "A minimal, zero-config, BSD licensed, readline replacement."
LICENSE = "BSD-2-Clause"
LIC_FILES_CHKSUM = "file://${S}/LICENSE;md5=faa55ac8cbebebcb4a84fe1ea2879578"

SRC_URI = "git://github.com/antirez/linenoise.git;protocol=https"
SRCREV = "4a961c0108720741e2683868eb10495f015ee422"

S = "${WORKDIR}/git"

#INSANE_SKIP_${PN}-dev += "dev-elf"

do_compile(){
    ${CC} -c linenoise.c -o linenoise.o ${LDFLAGS}
 #   ${CC} -shared linenoise.o -o liblinenoise.so ${LDFLAGS}
    ${AR} rcs liblinenoise.a linenoise.o

}

do_install(){
    install -m 0755 -d ${D}${libdir}
    install -m 0755 -d ${D}${includedir}
    install -m 0755 ${S}/liblinenoise.a ${D}${libdir}
    install -m 0644 ${S}/linenoise.h ${D}${includedir}
}


text:
DESCRIPTION = "An icon theme for Gnome"
SECTION = "x11/wm"
LICENSE = "GPL-3.0-only"
HOMEPAGE = "http://code.google.com/p/faenza-icon-theme/"
LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

inherit allarch gtk-icon-cache

S = "${WORKDIR}"

SRC_URI = "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/${BPN}/${BPN}_${PV}.zip"
SRC_URI[sha256sum] = "d4486fda0413f8a81a87e0dd2329f50f2a8a7cb4147b48cf147f0160add8174a"

do_install() {
    install -d ${D}${datadir}/icons
    for theme in `find -name 'Faenza*.tar.gz'`; do
        tar -xf ${theme} -C ${D}${datadir}/icons
    done
    tar -xf emesene-faenza-theme.tar.gz -C ${D}${datadir}
    mv -f ${D}${datadir}/emesene/themes ${D}${datadir}/themes
    rm -rf ${D}${datadir}/emesene
    chown -R root:root ${D}${datadir}
}

FILES:${PN} += "${datadir}/icons ${datadir}/themes"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake


text:
SUMMARY = "SDL2 OpenGL ES Test Applications"
HOMEPAGE = "https://github.com/mer-qa/sdl2-opengles-test"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://main_opengles2.cpp;beginline=1;endline=26;md5=0d08cb5b4a92c955950cc46dbaa3b6f0"

DEPENDS += "libsdl2"

inherit webos_filesystem_paths pkgconfig

TARGETS = "sdl2_opengles1_test sdl2_opengles2_test"
TARGETS:rpi = "sdl2_opengles2_test"

PV = "1.0.6+git${SRCPV}"
SRC_URI = "git://github.com/mer-qa/sdl2-opengles-test.git;branch=master;protocol=https \
    file://sdl2_opengles1_test-appinfo.json \
    file://sdl2_opengles2_test-appinfo.json"
S = "${WORKDIR}/git"

SRCREV = "d0a3c8806cb29e3fe9dccc162c66d42dc4ebc40e"

do_compile() {
    oe_runmake TARGETS="${TARGETS}" CXXFLAGS="${CXXFLAGS} ${LDFLAGS}"
}

do_install() {
    for f in ${TARGETS}; do
        install -d ${D}${webos_applicationsdir}/$f
        install -m 0755 ${S}/$f ${D}${webos_applicationsdir}/$f/
        install -m 0644 ${WORKDIR}/$f-appinfo.json ${D}${webos_applicationsdir}/$f/appinfo.json
    done
}

FILES:${PN} += "${webos_applicationsdir}"

repository: webOS-ports/meta-webos-ports

repo_name: webOS-ports/meta-webos-ports

branch_name: refs/heads/kirkstone


text:
file(REMOVE_RECURSE
  "CMakeFiles/TP2.dir/TP2/ex1.cpp.o"
  "CMakeFiles/TP2.dir/TP2/ex2.cpp.o"
  "CMakeFiles/TP2.dir/TP2/ex3.cpp.o"
  "CMakeFiles/TP2.dir/TP2/ex4.cpp.o"
  "CMakeFiles/TP2.dir/main.cpp.o"
  "TP2"
  "TP2.pdb"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/TP2.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

extension: cmake