text:
package contract

import "github.com/firmeve/firmeve/support"

type (
	Container interface {
		Has(name string) bool
		Get(name string, params ...interface{}) interface{}
		Bind(name string, prototype interface{}, options ...support.Option)
		Make(abstract interface{}, params ...interface{}) interface{}
		Remove(name string)
		Flush()
	}
)

repository: firmeve/firmeve

repo_name: firmeve/firmeve

branch_name: refs/heads/develop


text:
@INPROCEEDINGS{ma:19:https-phishing,
 AUTHOR = {Zane Ma and Joshua Reynolds and Joseph Dickinson and Kaishen Wang and Taylor Judd and Joseph D. Barnes and Joshua Mason and Michael Bailey},
 TITLE = {{The Impact of Secure Transport Protocols on Phishing Efficacy}},
 BOOKTITLE = {12th USENIX Workshop on Cyber Security Experimentation and Test ({CSET} '19)},
 ADDRESS = {Santa Clara, CA},
 MONTH = {August},
 DAY = {12},
 YEAR = {2019},
}

license: MIT

repository: zzma/website

license_type: permissive

repo_name: zzma/website

branch_name: refs/heads/master

gha_language: SCSS

extension: bib


text:
@article{long2019low,
  title={Low power millimeter wave radar system for the visually impaired},
  author={Long, Ningbo and Wang, Kaiwei and Cheng, Ruiqi and Hu, Weijian and Yang, Kailun},
  journal={The Journal of Engineering},
  year={2019},
  volume={2019},
  number={19},
  pages={6034-6038}
}


text:
@inproceedings{sarwar2001item,
  title={Item-based collaborative filtering recommendation algorithms},
  author={Sarwar, Badrul and Karypis, George and Konstan, Joseph and Riedl, John},
  booktitle={Proceedings of the 10th international conference on World Wide Web},
  pages={285--295},
  year={2001},
  organization={ACM}
}

@inproceedings{breese1998empirical,
	title={Empirical analysis of predictive algorithms for collaborative filtering},
	author={Breese, John S and Heckerman, David and Kadie, Carl},
	booktitle={Proceedings of the Fourteenth conference on Uncertainty in artificial intelligence},
	pages={43--52},
	year={1998},
	organization={Morgan Kaufmann Publishers Inc.}
}

@article{koren2009bellkor,
	title={The bellkor solution to the netflix grand prize},
	author={Koren, Yehuda},
	journal={Netflix prize documentation},
	volume={81},
	pages={1--10},
	year={2009}
}

@inproceedings{wang2015collaborative,
	title={Collaborative deep learning for recommender systems},
	author={Wang, Hao and Wang, Naiyan and Yeung, Dit-Yan},
	booktitle={Proceedings of the 21th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining},
	pages={1235--1244},
	year={2015},
	organization={ACM}
}


text:
@incollection{gal2014parallel,
title = {Distributed Variational Inference in Sparse {G}aussian Process Regression and Latent Variable Models},
author = {Yarin Gal and Mark van der Wilk and Carl Edward Rasmussen},
booktitle = {Advances in Neural Information Processing Systems 27 (NIPS)},
editor = {Z. Ghahramani and M. Welling and C. Cortes and N. D. Lawrence and K. Q. Weinberger},
pages = {3257--3265},
year = {2014},
publisher = {Curran Associates, Inc.},
url = {http://papers.nips.cc/paper/5593-distributed-variational-inference-in-sparse-gaussian-process-regression-and-latent-variable-models.pdf}
}

@misc{galvdw2014tutorial,
Author = {Yarin Gal and Mark van der Wilk},
Title = {Variational Inference in Sparse {G}aussian Process Regression and Latent Variable Models - a Gentle Tutorial},
Year = {2014},
Eprint = {arXiv:1402.1412},
url = {https://arxiv.org/abs/1402.1412},
}

@incollection{vdw2014wplvm,
author = {Mark van der Wilk and Andrew Gordon Wilson and Carl Edward Rasmussen},
title = {Variational Inference for Latent Variable Modelling of Correlation Structure},
booktitle = {NIPS 2014 Workshop of Advances in Variational Inference},
year = {2014},
url = {https://drive.google.com/file/d/0BwY-r_90KHY4Vmd4UzBhbEI0RWM/view?usp=sharing},
}

@incollection{bauer2016understanding,
title = {Understanding Probabilistic Sparse {G}aussian Process Approximations},
author = {Bauer, Matthias and van der Wilk, Mark and Rasmussen, Carl Edward},
booktitle = {Advances in Neural Information Processing Systems 29 (NIPS)},
editor = {D. D. Lee and M. Sugiyama and U. V. Luxburg and I. Guyon and R. Garnett},
pages = {1533--1541},
year = {2016},
publisher = {Curran Associates, Inc.},
url = {http://papers.nips.cc/paper/6477-understanding-probabilistic-sparse-gaussian-process-approximations.pdf}
}

@incollection{mcallister2016exploration,
title = {Data-Efficient Policy Search using {PILCO} and Directed-Exploration},
author = {Rowan McAllister and Mark van der Wilk and Carl Edward Rasmussen},
booktitle = {ICML 2016 Workshop on Data-Efficient Machine Learning},
year = {2016},
url = {https://drive.google.com/open?id=0B0VXvxUNyiVSQ01VUXIzdXQ4MW8},
}

@article{gpflow,
  author  = {Alexander G. de G. Matthews and Mark van der Wilk and Tom Nickson and Keisuke Fujii and Alexis Boukouvalas and Pablo Le{{\'o}}n-Villagr{{\'a}} and Zoubin Ghahramani and James Hensman},
  title   = {{GPflow}: A {G}aussian Process Library using {T}ensor{F}low},
  journal = {Journal of Machine Learning Research},
  year    = {2017},
  volume  = {18},
  number  = {40},
  pages   = {1-6},
  url     = {http://jmlr.org/papers/v18/16-537.html}
}

@incollection{vdw2017convgp,
title = {Convolutional {G}aussian Processes},
author = {van der Wilk, Mark and Rasmussen, Carl Edward and Hensman, James},
booktitle = {Advances in Neural Information Processing Systems 30 (NIPS)},
editor = {I. Guyon and U. V. Luxburg and S. Bengio and H. Wallach and R. Fergus and S. Vishwanathan and R. Garnett},
pages = {2849--2858},
year = {2017},
publisher = {Curran Associates, Inc.},
url = {http://papers.nips.cc/paper/6877-convolutional-gaussian-processes.pdf}
}

@inproceedings{mcallister2017concrete,
  title={Concrete problems for autonomous vehicle safety: advantages of {B}ayesian deep learning},
  author={McAllister, Rowan and Gal, Yarin and Kendall, Alex and van der Wilk, Mark and Shah, Amar and Cipolla, Roberto and Weller, Adrian Vivian},
  year={2017},
  organization={International Joint Conferences on Artificial Intelligence},
  url={https://www.ijcai.org/Proceedings/2017/0661.pdf},
}

@incollection{ialongo2017closed,
title = {Closed-form Inference and Prediction in {G}aussian Process State-Space Models},
author = {Alessandro Davide Ialongo and Mark van der Wilk and Carl Edward Rasmussen},
booktitle = {NIPS 2017 Workshop on Time Series},
year = {2017},
url = {https://arxiv.org/abs/1812.03580},
}

@inproceedings{tran2019layers,
 author = {Tran, Dustin and Dusenberry, Mike and van der Wilk, Mark and Hafner, Danijar},
 booktitle = {Advances in Neural Information Processing Systems 32 (NeurIPS)},
 editor = {H. Wallach and H. Larochelle and A. Beygelzimer and F. d\textquotesingle Alch\'{e}-Buc and E. Fox and R. Garnett},
 pages = {},
 publisher = {Curran Associates, Inc.},
 title = {Bayesian Layers: A Module for Neural Network Uncertainty},
 url = {https://proceedings.neurips.cc/paper/2019/file/154ff8944e6eac05d0675c95b5b8889d-Paper.pdf},
 volume = {32},
 year = {2019}
}

@incollection{vdw2018invgp,
title = {Learning Invariances using the Marginal Likelihood},
author = {van der Wilk, Mark and Bauer, Matthias and John, ST and Hensman, James},
booktitle = {Advances in Neural Information Processing Systems 31 (NeurIPS)},
editor = {S. Bengio and H. Wallach and H. Larochelle and K. Grauman and N. Cesa-Bianchi and R. Garnett},
pages = {9960--9970},
year = {2018},
publisher = {Curran Associates, Inc.},
url = {http://papers.nips.cc/paper/8199-learning-invariances-using-the-marginal-likelihood.pdf}
}

@InProceedings{burt2019rates,
title = {Rates of Convergence for Sparse Variational {G}aussian Process Regression},
author = {Burt, David and Rasmussen, Carl Edward and van der Wilk, Mark},
booktitle = {Proceedings of the 36th International Conference on Machine Learning (ICML)},
pages = {862--871},
year = {2019},
editor = {Kamalika Chaudhuri and Ruslan Salakhutdinov},
volume = {97},
series = {Proceedings of Machine Learning Research},
month = {Jun},
publisher = {PMLR},
pdf = {http://proceedings.mlr.press/v97/burt19a/burt19a.pdf},
url = {http://proceedings.mlr.press/v97/burt19a.html},
abstract = {Excellent variational approximations to Gaussian process posteriors have been developed which avoid the $\mathcal{O}\left(N^3\right)$ scaling with dataset size $N$. They reduce the computational cost to $\mathcal{O}\left(NM^2\right)$, with $M\ll N$ the number of inducing variables, which summarise the process. While the computational cost seems to be linear in $N$, the true complexity of the algorithm depends on how $M$ must increase to ensure a certain quality of approximation. We show that with high probability the KL divergence can be made arbitrarily small by growing $M$ more slowly than $N$. A particular case is that for regression with normally distributed inputs in D-dimensions with the Squared Exponential kernel, $M=\mathcal{O}(\log^D N)$ suffices. Our results show that as datasets grow, Gaussian process posteriors can be approximated cheaply, and provide a concrete rule for how to increase $M$ in continual learning scenarios.}
}

@InProceedings{ialongo2019overcoming,
title = {Overcoming Mean-Field Approximations in Recurrent {G}aussian Process Models},
author = {Ialongo, Alessandro Davide and van der Wilk, Mark and Hensman, James and Rasmussen, Carl Edward},
booktitle = {Proceedings of the 36th International Conference on Machine Learning (ICML)},
pages = {2931--2940},
year = {2019},
editor = {Kamalika Chaudhuri and Ruslan Salakhutdinov},
volume = {97},
series = {Proceedings of Machine Learning Research},
month = {Jun},
publisher = {PMLR},
pdf = {http://proceedings.mlr.press/v97/ialongo19a/ialongo19a.pdf},
url = {http://proceedings.mlr.press/v97/ialongo19a.html},
abstract = {We identify a new variational inference scheme for dynamical systems whose transition function is modelled by a Gaussian process. Inference in this setting has either employed computationally intensive MCMC methods, or relied on factorisations of the variational posterior. As we demonstrate in our experiments, the factorisation between latent system states and transition function can lead to a miscalibrated posterior and to learning unnecessarily large noise terms. We eliminate this factorisation by explicitly modelling the dependence between state trajectories and the low-rank representation of our Gaussian process posterior. Samples of the latent states can then be tractably generated by conditioning on this representation. The method we obtain gives better predictive performance and more calibrated estimates of the transition function, yet maintains the same time and space complexities as mean-field methods.}
}

@phdthesis{vdw2019sparse,
  title={Sparse Gaussian process approximations and applications},
  author={Van der Wilk, Mark},
  year={2019},
  school={University of Cambridge}
}

@inproceedings{heaukulani2019wishart,
 author = {Heaukulani, Creighton and van der Wilk, Mark},
 booktitle = {Advances in Neural Information Processing Systems 32 (NeurIPS)},
 editor = {H. Wallach and H. Larochelle and A. Beygelzimer and F. d\textquotesingle Alch\'{e}-Buc and E. Fox and R. Garnett},
 pages = {},
 publisher = {Curran Associates, Inc.},
 title = {Scalable Bayesian dynamic covariance modeling with variational Wishart and inverse Wishart processes},
 url = {https://proceedings.neurips.cc/paper/2019/file/5b168fdba5ee5ea262cc2d4c0b457697-Paper.pdf},
 volume = {32},
 year = {2019}
}

@InProceedings{vdw2020inv,
title = {Variational Gaussian Process Models without Matrix Inverses},
author = {van der Wilk, Mark and John, ST and Artemev, Artem and Hensman, James},
booktitle = {Proceedings of The 2nd Symposium on Advances in Approximate Bayesian Inference},
pages = {1--9},
year = {2020},
editor = {Zhang, Cheng and Ruiz, Francisco and Bui, Thang and Dieng, Adji Bousso and Liang, Dawen},
volume = {118},
series = {Proceedings of Machine Learning Research},
month = {Jan},
publisher = {PMLR},
pdf = {http://proceedings.mlr.press/v118/wilk20a/wilk20a.pdf},
url = {http://proceedings.mlr.press/v118/wilk20a.html},
abstract = {In this work, we provide a variational lower bound that can be computed without expensive matrix operations like inversion. Our bound can be used as a drop-in replacement to the existing variational method of Hensman et al. (2013, 2015), and can therefore directly be applied in a wide variety of models, such as deep GPs (Damianou and Lawrence, 2013). We focus on the theoretical properties of this new bound, and show some initial experimental results for optimising this bound. We hope to realise the full promise in scalability that this new bound has in future work.}
}

@inproceedings{burt2020understanding,
title={Understanding Variational Inference in Function-Space},
author={David R. Burt and Sebastian W. Ober and Adri{\`a} Garriga-Alonso and Mark van der Wilk},
booktitle={Third Symposium on Advances in Approximate Bayesian Inference},
year={2021},
month={jan},
url = {https://arxiv.org/abs/2011.09421},
}

@misc{sedgwick2020design,
Author = {Ruby Sedgwick and John Goertz and Molly Stevens and Ruth Misener and Mark van der Wilk},
Title = {Design of Experiments for Verifying Biomolecular Networks},
Year = {2020},
Eprint = {arXiv:2011.10575},
url = {https://arxiv.org/abs/2011.10575},
}

@InProceedings{dutordoir2020dcgp,
  title = 	 {Bayesian Image Classification with Deep Convolutional Gaussian Processes},
  author =       {Dutordoir, Vincent and van der Wilk, Mark and Artemev, Artem and Hensman, James},
  booktitle = 	 {Proceedings of the Twenty Third International Conference on Artificial Intelligence and Statistics (AISTATS)},
  pages = 	 {1529--1539},
  year = 	 {2020},
  editor = 	 {Chiappa, Silvia and Calandra, Roberto},
  volume = 	 {108},
  series = 	 {Proceedings of Machine Learning Research},
  month = 	 {Aug},
  publisher =    {PMLR},
  pdf = 	 {http://proceedings.mlr.press/v108/dutordoir20a/dutordoir20a.pdf},
  url = 	 {http://proceedings.mlr.press/v108/dutordoir20a.html},
  abstract = 	 {In decision-making systems, it is important to have classifiers that have calibrated uncertainties, with an optimisation objective that can be used for automated model selection and training. Gaussian processes (GPs) provide uncertainty estimates and a marginal likelihood objective, but their weak inductive biases lead to inferior accuracy. This has limited their applicability in certain tasks (e.g. image classification). We propose a translation insensitive convolutional kernel, which relaxes the translation invariance constraint imposed by previous convolutional GPs. We show how we can use the marginal likelihood to learn the degree of insensitivity. We also reformulate GP image-to-image convolutional mappings as multi-output GPs, leading to deep convolutional GPs. We show experimentally that our new kernel improves performance in both single-layer and deep models. We also demonstrate that our fully Bayesian approach improves on dropout-based Bayesian deep learning methods in terms of uncertainty and marginal likelihood estimates.}
}

@misc{vdw2020framework,
Author = {Mark van der Wilk and Vincent Dutordoir and ST John and Artem Artemev and Vincent Adam and James Hensman},
Title = {A Framework for Interdomain and Multioutput Gaussian Processes},
Year = {2020},
Eprint = {arXiv:2003.01115},
url = {https://arxiv.org/abs/2003.01115},
}

@misc{lyle2020benefits,
Author = {Clare Lyle and Mark van der Wilk and Marta Kwiatkowska and Yarin Gal and Benjamin Bloem-Reddy},
Title = {On the Benefits of Invariance in Neural Networks},
Year = {2020},
Eprint = {arXiv:2005.00178},
url = {https://arxiv.org/abs/2005.00178},
}

@article{burt2020convergence,
  author  = {David R. Burt and Carl Edward Rasmussen and Mark van der Wilk},
  title   = {Convergence of Sparse Variational Inference in Gaussian Processes Regression},
  journal = {Journal of Machine Learning Research},
  year    = {2020},
  volume  = {21},
  number  = {131},
  pages   = {1-63},
  url     = {http://jmlr.org/papers/v21/19-1015.html}
}

@inproceedings{monteiro2020correlated,
 author = {Monteiro, Miguel and Le Folgoc, Loic and Coelho de Castro, Daniel and Pawlowski, Nick and Marques, Bernardo and Kamnitsas, Konstantinos and van der Wilk, Mark and Glocker, Ben},
 booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
 editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},
 pages = {12756--12767},
 publisher = {Curran Associates, Inc.},
 title = {Stochastic Segmentation Networks: Modelling Spatially Correlated Aleatoric Uncertainty},
 url = {https://proceedings.neurips.cc/paper/2020/file/95f8d9901ca8878e291552f001f67692-Paper.pdf},
 volume = {33},
 year = {2020}
}

@misc{ru2020speed,
Author = {Binxin Ru and Clare Lyle and Lisa Schut and Mark van der Wilk and Yarin Gal},
Title = {Revisiting the Train Loss: an Efficient Performance Estimator for Neural Architecture Search},
Year = {2020},
Eprint = {arXiv:2006.04492},
url = {https://arxiv.org/abs/2006.04492},
}

@misc{burt2020vof,
Author = {David R. Burt and Carl Edward Rasmussen and Mark van der Wilk},
Title = {Variational Orthogonal Features},
Year = {2020},
Eprint = {arXiv:2006.13170},
url = {https://arxiv.org/abs/2006.13170},
}

@misc{smith2020capsules,
Author = {Lewis Smith and Lisa Schut and Yarin Gal and Mark van der Wilk},
Title = {Capsule Networks -- A Probabilistic Perspective},
Year = {2020},
Eprint = {arXiv:2004.03553},
url = {https://arxiv.org/abs/2004.03553},
}

@inproceedings{lyle2020trainingspeed,
 author = {Lyle, Clare and Schut, Lisa and Ru, Robin and Gal, Yarin and van der Wilk, Mark},
 booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
 editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},
 pages = {10396--10408},
 publisher = {Curran Associates, Inc.},
 title = {A Bayesian Perspective on Training Speed and Model Selection},
 url = {https://proceedings.neurips.cc/paper/2020/file/75a7c30fc0063c4952d7eb044a3c0897-Paper.pdf},
 volume = {33},
 year = {2020}
}

@misc{fortuin2021priors,
Author = {Vincent Fortuin and Adrià Garriga-Alonso and Florian Wenzel and Gunnar Rätsch and Richard Turner and Mark van der Wilk and Laurence Aitchison},
Title = {Bayesian Neural Network Priors Revisited},
Year = {2021},
Eprint = {arXiv:2102.06571},
url = {https://arxiv.org/abs/2102.06571},
}

@misc{dutordoir2021gpflux,
Author = {Vincent Dutordoir and Hugh Salimbeni and Eric Hambro and John McLeod and Felix Leibfried and Artem Artemev and Mark van der Wilk and James Hensman and Marc P. Deisenroth and ST John},
Title = {GPflux: A Library for Deep Gaussian Processes},
Year = {2021},
Eprint = {arXiv:2104.05674},
url = {https://arxiv.org/abs/2104.05674},
}

@InProceedings{ober2021dkl,
  title = 	 {The Promises and Pitfalls of Deep Kernel Learning},
  author =       {Sebastian W. Ober and Carl E. Rasmussen and Mark van der Wilk},
  booktitle = 	 {Proceedings of the 37th Conference on Uncertainty in Artificial Intelligence (UAI)},
  year = 	 {2021},
  month =        {Jul},
  url = {https://arxiv.org/abs/2102.12108},
}

@InProceedings{garriga-alonso2021correlated,
  title = 	 {Correlated Weights in Infinite Limits of Deep Convolutional Neural Networks},
  author =       {Adri{\`a} Garriga-Alonso and Mark van der Wilk},
  booktitle = 	 {Proceedings of the 37th Conference on Uncertainty in Artificial Intelligence (UAI)},
  year = 	 {2021},
  month =        {Jul},
  url = {https://www.auai.org/uai2021/pdf/uai2021.752.pdf},
}

@InProceedings{artemevburt2021cglb,
  title = 	 {Tighter Bounds on the Log Marginal Likelihood of Gaussian Process Regression Using Conjugate Gradients},
  author =       {Artemev, Artem and Burt, David R. and van der Wilk, Mark},
  booktitle = 	 {Proceedings of the 38th International Conference on Machine Learning (ICML)},
  pages = 	 {362--372},
  year = 	 {2021},
  editor = 	 {Meila, Marina and Zhang, Tong},
  volume = 	 {139},
  series = 	 {Proceedings of Machine Learning Research},
  month = 	 {Jul},
  publisher =    {PMLR},
  pdf = 	 {http://proceedings.mlr.press/v139/artemev21a/artemev21a.pdf},
  url = 	 {https://proceedings.mlr.press/v139/artemev21a.html},
  abstract = 	 {We propose a lower bound on the log marginal likelihood of Gaussian process regression models that can be computed without matrix factorisation of the full kernel matrix. We show that approximate maximum likelihood learning of model parameters by maximising our lower bound retains many benefits of the sparse variational approach while reducing the bias introduced into hyperparameter learning. The basis of our bound is a more careful analysis of the log-determinant term appearing in the log marginal likelihood, as well as using the method of conjugate gradients to derive tight lower bounds on the term involving a quadratic form. Our approach is a step forward in unifying methods relying on lower bound maximisation (e.g. variational methods) and iterative approaches based on conjugate gradients for training Gaussian processes. In experiments, we show improved predictive performance with our model for a comparable amount of training time compared to other conjugate gradient based approaches.}
}

@misc{dutordoir2021relu,
Author = {Vincent Dutordoir and James Hensman and Mark van der Wilk and Carl Henrik Ek and Zoubin Ghahramani and Nicolas Durrande},
Title = {Deep Neural Networks as Point Estimates for Deep Gaussian Processes},
Year = {2021},
Eprint = {arXiv:2105.04504},
url = {https://arxiv.org/abs/2105.04504},
}

@misc{schwoebel2021layer,
      title={Last Layer Marginal Likelihood for Invariance Learning},
      author={Pola Schwöbel and Martin Jørgensen and Sebastian W. Ober and Mark van der Wilk},
      year={2021},
      eprint={2106.07512},
      archivePrefix={arXiv},
      primaryClass={stat.ML},
      url={https://arxiv.org/abs/2106.07512}
}

@misc{nabarro2021data,
      title={Data augmentation in Bayesian neural networks and the cold posterior effect},
      author={Seth Nabarro and Stoil Ganev and Adrià Garriga-Alonso and Vincent Fortuin and Mark van der Wilk and Laurence Aitchison},
      year={2021},
      eprint={2106.05586},
      archivePrefix={arXiv},
      primaryClass={stat.ML},
      url={https://arxiv.org/abs/2106.05586}
}


text:
package quota

/*
#include <linux/fs.h>
#include <linux/dqblk_xfs.h>
#include <linux/quota.h>
#include <sys/ioctl.h>
#include <sys/quota.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>

#ifndef FS_XFLAG_PROJINHERIT
struct fsxattr {
	__u32		fsx_xflags;
	__u32		fsx_extsize;
	__u32		fsx_nextents;
	__u32		fsx_projid;
	unsigned char	fsx_pad[12];
};
#define FS_XFLAG_PROJINHERIT 0x00000200
#endif

#ifndef QIF_DQBLKSIZE_BITS
struct if_dqinfo {
	__u64 dqi_bgrace;
	__u64 dqi_igrace;
	__u32 dqi_flags;
	__u32 dqi_valid;
};

struct if_dqblk {
	__u64 dqb_bhardlimit;
	__u64 dqb_bsoftlimit;
	__u64 dqb_curspace;
	__u64 dqb_ihardlimit;
	__u64 dqb_isoftlimit;
	__u64 dqb_curinodes;
	__u64 dqb_btime;
	__u64 dqb_itime;
	__u32 dqb_valid;
};
#define QIF_DQBLKSIZE_BITS 10
#endif

#ifndef FS_IOC_FSGETXATTR
#define FS_IOC_FSGETXATTR _IOR ('X', 31, struct fsxattr)
#endif

#ifndef FS_IOC_FSSETXATTR
#define FS_IOC_FSSETXATTR _IOW ('X', 32, struct fsxattr)
#endif

#ifndef PRJQUOTA
#define PRJQUOTA 2
#endif

int quota_supported(char *dev_path) {
	struct if_dqinfo dqinfo;

	return quotactl(QCMD(Q_GETINFO, PRJQUOTA), dev_path, 0, (caddr_t)&dqinfo);
}

int64_t quota_get_usage(char *dev_path, uint32_t id) {
	struct if_dqblk quota;

	if (quotactl(QCMD(Q_GETQUOTA, PRJQUOTA), dev_path, id, (caddr_t)&quota) < 0) {
		return -1;
	}

	return quota.dqb_curspace;
}

int quota_set(char *dev_path, uint32_t id, uint64_t hard_bytes) {
	struct if_dqblk quota;
	fs_disk_quota_t xfsquota;

	if (quotactl(QCMD(Q_GETQUOTA, PRJQUOTA), dev_path, id, (caddr_t)&quota) < 0) {
		return -1;
	}

	quota.dqb_bhardlimit = hard_bytes;
	if (quotactl(QCMD(Q_SETQUOTA, PRJQUOTA), dev_path, id, (caddr_t)&quota) < 0) {
		xfsquota.d_version = FS_DQUOT_VERSION;
		xfsquota.d_id = id;
		xfsquota.d_flags = FS_PROJ_QUOTA;
		xfsquota.d_fieldmask = FS_DQ_BHARD;
		xfsquota.d_blk_hardlimit = hard_bytes * 1024 / 512;

		if (quotactl(QCMD(Q_XSETQLIM, PRJQUOTA), dev_path, id, (caddr_t)&xfsquota) < 0) {
			return -1;
		}
	}

	return 0;
}

int quota_set_path(char *path, uint32_t id, bool inherit) {
	struct fsxattr attr;
	int fd;
	int ret;

	fd = open(path, O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;

	ret = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
	if (ret < 0) {
		close(fd);
		return -1;
	}

	if (inherit) {
		attr.fsx_xflags |= FS_XFLAG_PROJINHERIT;
	}

	attr.fsx_projid = id;

	ret = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
	if (ret < 0) {
		close(fd);
		return -1;
	}

	close(fd);
	return 0;
}

int32_t quota_get_path(char *path) {
	struct fsxattr attr;
	int fd;
	int ret;

	fd = open(path, O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;

	ret = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
	if (ret < 0) {
		close(fd);
		return -1;
	}

	close(fd);
	return attr.fsx_projid;
}

*/
import "C"

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"unsafe"

	"golang.org/x/sys/unix"

	"github.com/lxc/incus/shared"
)

var errNoDevice = fmt.Errorf("Couldn't find backing device for mountpoint")

func devForPath(path string) (string, error) {
	// Get major/minor
	var stat unix.Stat_t
	err := unix.Lstat(path, &stat)
	if err != nil {
		return "", err
	}

	devMajor := unix.Major(uint64(stat.Dev))
	devMinor := unix.Minor(uint64(stat.Dev))

	// Parse mountinfo for it
	mountinfo, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		return "", err
	}

	defer func() { _ = mountinfo.Close() }()

	scanner := bufio.NewScanner(mountinfo)
	for scanner.Scan() {
		line := scanner.Text()

		tokens := strings.Fields(line)
		if len(tokens) < 5 {
			continue
		}

		if tokens[2] == fmt.Sprintf("%d:%d", devMajor, devMinor) {
			if shared.PathExists(tokens[len(tokens)-2]) {
				return tokens[len(tokens)-2], nil
			}
		}
	}

	return "", errNoDevice
}

// Supported check if the given path supports project quotas.
func Supported(path string) (bool, error) {
	// Get the backing device
	devPath, err := devForPath(path)
	if err != nil {
		return false, err
	}

	// Call quotactl through CGo
	cDevPath := C.CString(devPath)
	defer C.free(unsafe.Pointer(cDevPath))

	return C.quota_supported(cDevPath) == 0, nil
}

// GetProject returns the project quota ID for the given path.
func GetProject(path string) (uint32, error) {
	// Call ioctl through CGo
	cPath := C.CString(path)
	defer C.free(unsafe.Pointer(cPath))

	id := C.quota_get_path(cPath)
	if id < 0 {
		return 0, fmt.Errorf("Failed to get project from %q", path)
	}

	return uint32(id), nil
}

// SetProject recursively sets the project quota ID (and project inherit flag on directories) for the given path.
func SetProject(path string, id uint32) error {
	err := filepath.Walk(path, func(filePath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		inherit := false
		if info.IsDir() {
			inherit = true // Only can set FS_XFLAG_PROJINHERIT on directories.
		} else if !info.Mode().IsRegular() {
			// Cannot set project ID on non-regular files after file creation. Infact trying to set
			// project ID on some file types just blocks forever (such as pipe files).
			// So skip them as they don't take up disk space anyway.
			return nil
		}

		// Call ioctl through CGo.
		cPath := C.CString(filePath)
		defer C.free(unsafe.Pointer(cPath))

		if C.quota_set_path(cPath, C.uint32_t(id), C.bool(inherit)) != 0 {
			return fmt.Errorf(`Failed to set project ID "%d" on %q (inherit %t)`, id, filePath, inherit)
		}

		return nil
	})

	return err
}

// DeleteProject unsets the project id from the path and clears the quota for the project ID.
func DeleteProject(path string, id uint32) error {
	// Unset the project from the path.
	err := SetProject(path, 0)
	if err != nil {
		return err
	}

	// Unset the quota on the project.
	err = SetProjectQuota(path, id, 0)
	if err != nil {
		return err
	}

	return nil
}

// GetProjectUsage returns the current consumption.
func GetProjectUsage(path string, id uint32) (int64, error) {
	// Get the backing device.
	devPath, err := devForPath(path)
	if err != nil {
		return -1, err
	}

	// Call quotactl through CGo.
	cDevPath := C.CString(devPath)
	defer C.free(unsafe.Pointer(cDevPath))

	size := C.quota_get_usage(cDevPath, C.uint32_t(id))
	if size < 0 {
		return -1, fmt.Errorf(`Failed to get project consumption for ID "%d" on %q`, id, devPath)
	}

	return int64(size), nil
}

// SetProjectQuota sets the quota on the project ID.
func SetProjectQuota(path string, id uint32, bytes int64) error {
	// Get the backing device
	devPath, err := devForPath(path)
	if err != nil {
		return err
	}

	// Call quotactl through CGo
	cDevPath := C.CString(devPath)
	defer C.free(unsafe.Pointer(cDevPath))

	if C.quota_set(cDevPath, C.uint32_t(id), C.uint64_t(bytes/1024)) != 0 {
		return fmt.Errorf(`Failed to set project quota for ID "%d" on %q`, id, devPath)
	}

	return nil
}

repository: lxc/incus

repo_name: lxc/incus

branch_name: refs/heads/main

gha_language: Go

extension: go


text:
@inproceedings{nwpt2011,
	author = "Luckow, Kasper S{\o}e and Korsholm, Stephan Erbs and Thomsen, Bent",
	booktitle = "{Proceedings of the 23rd Nordic Workshop on Programming Theory}",
	location = "M{\"a}lardalen, Sweden",
	numpages = "3",
	pages = "68--88",
	series = "{NWPT '11}",
	title = "{Towards a Real-Time, WCET Analysable JVM Running in 256 kB of Flash Memory}",
	url = "www.mrtc.mdh.se/nwpt2011/nwpt11-proceedings.pdf",
	year = "2011"
}


text:
@Book{Abbott1959,
  Title                    = {Theory of wing sections including a summary of airfoil data},
  Author                   = {Ira H. Abbott and Albert E. Von DoenHoff},
  Publisher                = {Dover},
  Year                     = {1959}
}

@Article{Abkar2015,
  Title                    = {A new wind-farm parameterization for large-scale atmospheric models},
  Author                   = {Mahdi Abkar and Fernando Porte-Agel},
  Journal                  = {Journal of Renewable and Sustainable Energy},
  Year                     = {2015},
  Volume                   = {7},
  Doi                      = {10.1063/1.4907600}
}

repository: petebachant/unh-thesis-latex

repo_name: petebachant/unh-thesis-latex

gha_license_id: NOASSERTION

gha_language: TeX


text:
// Copyright 2015 Zalando SE
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package builtin

import (
	"net/http"
	"net/url"
	"strings"

	"github.com/zalando/skipper/filters"
)

type redirectType int

const (
	redDeprecated redirectType = iota
	redTo
	redToLower
)

// Filter to return
type redirect struct {
	typ      redirectType
	code     int
	location *url.URL
}

// NewRedirect returns a new filter Spec, whose instances create an HTTP redirect
// response. Marks the request as served. Instances expect two
// parameters: the redirect status code and the redirect location.
// Name: "redirect".
//
// This filter is deprecated, use RedirectTo instead.
// This *DEPRECATED* filter can not be used with filters from scheduler package.
func NewRedirect() filters.Spec { return &redirect{typ: redDeprecated} }

// NewRedirectTo returns a new filter Spec, whose instances create an HTTP redirect
// response. It shunts the request flow, meaning that the filter chain on
// the request path is not continued. The request is not forwarded to the
// backend. Instances expect two parameters: the redirect status code and
// the redirect location.
// Name: "redirectTo".
func NewRedirectTo() filters.Spec { return &redirect{typ: redTo} }

// NewRedirectLower returns a new filter Spec, whose instances create an HTTP redirect
// response, which redirects with a lowercase path. It is similar to redTo except that
// it converts the route path to lower while redirecting
// Name: "redirectToLower".
func NewRedirectLower() filters.Spec { return &redirect{typ: redToLower} }

// "redirect" or "redirectToLower" or "redirectTo"
func (spec *redirect) Name() string {
	switch spec.typ {
	case redDeprecated:
		return RedirectName
	case redToLower:
		return filters.RedirectToLowerName
	default:
		return filters.RedirectToName
	}
}

// Creates an instance of the redirect filter.
func (spec *redirect) CreateFilter(config []interface{}) (filters.Filter, error) {
	invalidArgs := func() (filters.Filter, error) {
		return nil, filters.ErrInvalidFilterParameters
	}

	if len(config) == 1 {
		config = append(config, "")
	}

	if len(config) != 2 {
		return invalidArgs()
	}

	code, ok := config[0].(float64)
	if !ok {
		return invalidArgs()
	}

	location, ok := config[1].(string)
	if !ok {
		return invalidArgs()
	}

	u, err := url.Parse(location)
	if err != nil {
		return invalidArgs()
	}

	return &redirect{spec.typ, int(code), u}, nil
}

func getRequestHost(r *http.Request) string {
	h := r.Header.Get("Host")

	if h == "" {
		h = r.Host
	}

	if h == "" {
		h = r.URL.Host
	}

	return h
}

func getLocation(ctx filters.FilterContext, location *url.URL, typ redirectType) string {
	r := ctx.Request()

	uc := *location
	u := &uc

	if u.Scheme == "" {
		if r.URL.Scheme != "" {
			u.Scheme = r.URL.Scheme
		} else {
			u.Scheme = "https"
		}
	}

	u.User = r.URL.User

	if u.Host == "" {
		u.Host = getRequestHost(r)
	}

	if u.Path == "" {
		u.Path = r.URL.Path
	}

	// Check if the redirect has to be case-insensitive
	if typ == redToLower {
		u.Path = strings.ToLower(u.Path)
	}

	if u.RawQuery == "" {
		u.RawQuery = r.URL.RawQuery
	}

	return u.String()
}

func redirectWithType(ctx filters.FilterContext, code int, location *url.URL, typ redirectType) {
	u := getLocation(ctx, location, typ)
	ctx.Serve(&http.Response{
		StatusCode: code,
		Header:     http.Header{"Location": []string{u}}})
}

// Redirect implements the redirect logic as a standalone function.
func Redirect(ctx filters.FilterContext, code int, location *url.URL) {
	redirectWithType(ctx, code, location, redTo)
}

func (spec *redirect) Request(ctx filters.FilterContext) {

	if spec.typ == redDeprecated {
		return
	}

	redirectWithType(ctx, spec.code, spec.location, spec.typ)
}

// Sets the status code and the location header of the response. Marks the
// request served.
func (spec *redirect) Response(ctx filters.FilterContext) {
	if spec.typ != redDeprecated {
		return
	}

	u := getLocation(ctx, spec.location, spec.typ)
	w := ctx.ResponseWriter()
	w.Header().Set("Location", u)
	w.WriteHeader(spec.code)
	ctx.MarkServed()
}

repository: zalando/skipper

repo_name: zalando/skipper


text:
package models

import (
	"database/sql"
	"fmt"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/go-test/deep"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
)

type CashSuite struct {
	suite.Suite
	DB   *gorm.DB
	mock sqlmock.Sqlmock

	cash             Cash
	cash_requirement *CashRequirement
}

func (c *CashSuite) SetupSuite() {
	var (
		db  *sql.DB
		err error
	)

	db, c.mock, err = sqlmock.New()
	require.NoError(c.T(), err)

	c.DB, err = gorm.Open("mysql", db)
	require.NoError(c.T(), err)

	//s.DB.LogMode(true)

	c.cash = CreateCashRequirement(c.DB)
}

func (c *CashSuite) AfterTest(_, _ string) {
	require.NoError(c.T(), c.mock.ExpectationsWereMet())
}

func TestCashInit(t *testing.T) {
	suite.Run(t, new(CashSuite))
}

func (c *CashSuite) TestGetCashRequirement() {
	var (
		id              = "1"
		cashrequirement = 100.12
		maxvalueatrisk  = 200.23
		primebrokercash = 300.34
		totalcash       = 400.45
	)
	selectQuery := fmt.Sprintf("SELECT id,cash_requirement,max_value_at_risk,prime_broker_cash,total_cash FROM `cash_requirement`  ORDER BY id desc LIMIT 1")
	c.mock.ExpectQuery(selectQuery).
		WillReturnRows(sqlmock.NewRows([]string{"id", "cashrequirement", "maxvalueatrisk", "primebrokercash", "totalcash"}).
			AddRow(id, cashrequirement, maxvalueatrisk, primebrokercash, totalcash))
	res, err := c.cash.GetCashRequirement()
	if err != nil {
		fmt.Println(err)
	}
	require.NoError(c.T(), err)
	require.Nil(c.T(), deep.Equal(CashRequirement{ID: id, CashRequirement: cashrequirement, MaxValueAtRisk: maxvalueatrisk, PrimeBrokerCash: primebrokercash, TotalCash: totalcash}, res))
}

repository: Mukul-Palit/capital-adequacy

repo_name: Mukul-Palit/capital-adequacy


text:
DESCRIPTION = "libdvdread provides a simple foundation for reading DVD video disks. \
It provides the functionality that is required to access many DVDs. \
It parses IFO files, reads NAV-blocks, and performs CSS authentication and descrambling."
HOMEPAGE = "http://www.dtek.chalmers.se/groups/dvd/development.shtml"
LICENSE = "GPL"
DEPENDS = "libdvdcss"
RRECOMMENDS_${PN} = "libdvdcss"
SECTION = "libs/multimedia"

# debian/4.1.4-1219-1
SRCREV = "9e62d1f071d70ab28f943438e80b940aa5e271bf"

PR = "r0"

SRC_URI = "git://git.debian-maintainers.org/git/daniel/libdvdread.git;protocol=git;branch=debian;tag=${SRCREV}"
S = "${WORKDIR}/git"

inherit autotools pkgconfig

EXTRA_OEMAKE = "DESTDIR=${D}"

do_munge() {
	for i in `ls debian/patches | grep ".patch" | sort -n`; do
		oenote "Applying debian patch '$i'";
		patch -p1 < debian/patches/$i;
	done;
}

addtask munge before do_configure after do_patch

do_stage() {
	autotools_stage_all
	cat ${S}/misc/dvdread-config | sed -e "s,-I/usr/include,-I${STAGING_INCDIR}," \
				     | sed -e "s,-L/usr/lib,-L${STAGING_LIBDIR}," \
		> ${STAGING_BINDIR_CROSS}/dvdread-config
	chmod a+rx ${STAGING_BINDIR_CROSS}/dvdread-config
}

gha_language: C

extension: bb


text:
package virtualbmc

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
)

type authenticationType uint8

const (
	authTypeNone                = authenticationType(0x00)
	authTypeMD2                 = authenticationType(0x01)
	authTypeMD5                 = authenticationType(0x02)
	authTypeStraightPasswordKey = authenticationType(0x04)
	authTypeOEM                 = authenticationType(0x05)
	authTypeRMCPPlus            = authenticationType(0x06)
)

type ipmiSession struct {
	authType authenticationType
}

// ipmiSessionWrapper represents ipmi RMCPPlusSession header v1.5 format
// BMCs that support ipmi v2.0/RMCP+ must support the Get Channel Authentication Capabilities command in both the ipmi v1.5 and v2.0 packet formats
// It is recommended that a remote console uses the ipmi v1.5 formats until it has confirmed ipmi v2.0 support
type ipmiSessionWrapper struct {
	AuthenticationType authenticationType
	SequenceNumber     uint32
	SessionId          uint32
	AuthenticationCode [16]byte
	MessageLen         uint8
}

func newIPMISession(buf io.Reader) (*ipmiSession, error) {
	var authType authenticationType
	if err := binary.Read(buf, binary.LittleEndian, &authType); err != nil {
		return nil, fmt.Errorf("failed to read authentication type: %w", err)
	}

	return &ipmiSession{authType: authType}, nil
}

// handle handles both ipmi v1.5 and v2.0 packet formats and dispatches layers below
func (r *ipmiSession) handle(buf io.Reader, machine Machine, session *rmcpPlusSessionHolder, bmcUser *bmcUserHolder) ([]byte, error) {
	rmcpPlus, err := isRMCPPlusFormat(r.authType)
	if err != nil {
		return nil, err
	}

	if rmcpPlus {
		rmcpPlus, err := newRMCPPlus(buf, r.authType, session, bmcUser)
		if err != nil {
			return nil, err
		}
		return rmcpPlus.handle(buf, machine)
	}

	wrapper, err := deserializeIPMISessionWrapper(buf, r.authType)
	if err != nil {
		return nil, err
	}

	ipmi, err := newIPMI(buf, int(wrapper.MessageLen), machine, session)
	if err != nil {
		return nil, err
	}
	res, err := ipmi.handle()
	if err != nil {
		return nil, err
	}

	responseWrapper := ipmiSessionWrapper{
		AuthenticationType: r.authType,
		SequenceNumber:     wrapper.SequenceNumber,
		SessionId:          wrapper.SessionId,
		MessageLen:         uint8(len(res)),
	}

	obuf := bytes.Buffer{}
	if err := serializeIPMISessionWrapper(&obuf, responseWrapper); err != nil {
		return nil, err
	}
	if err := binary.Write(&obuf, binary.LittleEndian, res); err != nil {
		return nil, fmt.Errorf("failed to write ipmi response body: %w", err)
	}
	return obuf.Bytes(), nil
}

func isRMCPPlusFormat(authType authenticationType) (bool, error) {
	switch authType {
	case authTypeRMCPPlus:
		return true, nil
	case authTypeNone:
		return false, nil
	case authTypeMD2:
	case authTypeMD5:
	case authTypeStraightPasswordKey:
	case authTypeOEM:
	default:
	}

	return false, fmt.Errorf("unsupported authentication type %d", authType)
}

func deserializeIPMISessionWrapper(buf io.Reader, authType authenticationType) (*ipmiSessionWrapper, error) {
	wrapper := &ipmiSessionWrapper{}
	wrapper.AuthenticationType = authType
	if err := binary.Read(buf, binary.LittleEndian, &wrapper.SequenceNumber); err != nil {
		return nil, fmt.Errorf("failed to read SequenceNumber: %w", err)
	}
	if err := binary.Read(buf, binary.LittleEndian, &wrapper.SessionId); err != nil {
		return nil, fmt.Errorf("failed to read SessionId: %w", err)
	}
	if wrapper.SessionId != 0x00 {
		if err := binary.Read(buf, binary.LittleEndian, &wrapper.AuthenticationCode); err != nil {
			return nil, fmt.Errorf("failed to read AuthenticationCode: %w", err)
		}
	}
	if err := binary.Read(buf, binary.LittleEndian, &wrapper.MessageLen); err != nil {
		return nil, fmt.Errorf("failed to read MessageLen: %w", err)
	}
	return wrapper, nil
}

func serializeIPMISessionWrapper(buf *bytes.Buffer, wrapper ipmiSessionWrapper) error {
	if err := binary.Write(buf, binary.LittleEndian, wrapper.AuthenticationType); err != nil {
		return fmt.Errorf("failed to write authenticationType: %w", err)
	}
	if err := binary.Write(buf, binary.LittleEndian, wrapper.SequenceNumber); err != nil {
		return fmt.Errorf("failed to write SequenceNumber: %w", err)
	}
	if err := binary.Write(buf, binary.LittleEndian, wrapper.SessionId); err != nil {
		return fmt.Errorf("failed to write SessionId: %w", err)
	}
	if wrapper.SessionId != 0 {
		if err := binary.Write(buf, binary.LittleEndian, wrapper.AuthenticationCode); err != nil {
			return fmt.Errorf("failed to write AuthenticationCode: %w", err)
		}
	}
	if err := binary.Write(buf, binary.LittleEndian, wrapper.MessageLen); err != nil {
		return fmt.Errorf("failed to write MessageLen: %w", err)
	}

	return nil
}

repository: cybozu-go/placemat

repo_name: cybozu-go/placemat


text:
package predict

import (
	"path/filepath"
	"strings"

	"github.com/mitchellh/go-homedir"
	"github.com/replicate/cog/pkg/util/console"
)

type Input struct {
	String *string
	File   *string
}

type Inputs map[string]Input

func NewInputs(keyVals map[string]string) Inputs {
	input := Inputs{}
	for key, val := range keyVals {
		val := val
		if strings.HasPrefix(val, "@") {
			val = val[1:]
			expandedVal, err := homedir.Expand(val)
			if err != nil {
				// FIXME: handle this better?
				console.Warnf("Error expanding homedir: %s", err)
			} else {
				val = expandedVal
			}

			input[key] = Input{File: &val}
		} else {
			input[key] = Input{String: &val}
		}
	}
	return input
}

func NewInputsWithBaseDir(keyVals map[string]string, baseDir string) Inputs {
	input := Inputs{}
	for key, val := range keyVals {
		val := val
		if strings.HasPrefix(val, "@") {
			val = filepath.Join(baseDir, val[1:])
			input[key] = Input{File: &val}
		} else {
			input[key] = Input{String: &val}
		}
	}
	return input
}

repository: amarjandu/cog

repo_name: amarjandu/cog


text:
package model

// Data related to the authentication of the cardholder.
type CardholderAuthentication9 struct {

	// Method and data intended to be used for this transaction to authenticate the cardholder or its card.
	AuthenticationMethod *AuthenticationMethod5Code `xml:"AuthntcnMtd"`

	// Value used to authenticate the cardholder.
	AuthenticationValue *Max5000Binary `xml:"AuthntcnVal,omitempty"`

	// Protection of the authentication value.
	ProtectedAuthenticationValue *ContentInformationType10 `xml:"PrtctdAuthntcnVal,omitempty"`

	// Encrypted personal identification number (PIN) and related information.
	CardholderOnLinePIN *OnLinePIN4 `xml:"CrdhldrOnLinePIN,omitempty"`

	// Identification of the cardholder to verify.
	CardholderIdentification *PersonIdentification11 `xml:"CrdhldrId,omitempty"`

	// Numeric characters of the cardholder's billing or shipping address for verification.
	AddressVerification *AddressVerification1 `xml:"AdrVrfctn,omitempty"`
}

func (c *CardholderAuthentication9) SetAuthenticationMethod(value string) {
	c.AuthenticationMethod = (*AuthenticationMethod5Code)(&value)
}

func (c *CardholderAuthentication9) SetAuthenticationValue(value string) {
	c.AuthenticationValue = (*Max5000Binary)(&value)
}

func (c *CardholderAuthentication9) AddProtectedAuthenticationValue() *ContentInformationType10 {
	c.ProtectedAuthenticationValue = new(ContentInformationType10)
	return c.ProtectedAuthenticationValue
}

func (c *CardholderAuthentication9) AddCardholderOnLinePIN() *OnLinePIN4 {
	c.CardholderOnLinePIN = new(OnLinePIN4)
	return c.CardholderOnLinePIN
}

func (c *CardholderAuthentication9) AddCardholderIdentification() *PersonIdentification11 {
	c.CardholderIdentification = new(PersonIdentification11)
	return c.CardholderIdentification
}

func (c *CardholderAuthentication9) AddAddressVerification() *AddressVerification1 {
	c.AddressVerification = new(AddressVerification1)
	return c.AddressVerification
}


text:
package service

import (
	"github.com/tealeg/xlsx"
)

type ExcelDataSheet struct {
	Rows  [][]string `json:"rows"`
	Sheet string     `json:"sheet"`
}

type ExcelDataArgs struct {
	OutFilePath string           `json:"out_file_path"`
	Sheets      []ExcelDataSheet `json:"sheets"`
}

func GenExcelFile(req *ExcelDataArgs) error {
	file := xlsx.NewFile()
	for i := 0; i < len(req.Sheets); i++ {
		sheet, err := file.AddSheet(req.Sheets[i].Sheet)
		if err != nil {
			return err
		}
		for j := 0; j < len(req.Sheets[i].Rows); j++ {
			row := sheet.AddRow()
			for k := 0; k < len(req.Sheets[i].Rows[j]); k++ {
				row.AddCell().Value = req.Sheets[i].Rows[j][k]
			}
		}
	}
	return file.Save(req.OutFilePath)
}

repository: iooikaak/micro-mall-api

repo_name: iooikaak/micro-mall-api


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/boost_regex-mt-shared-debug.dir/c_regex_traits.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/cpp_regex_traits.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/cregex.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/fileiter.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/icu.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/instances.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/posix_api.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/regex.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/regex_debug.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/regex_raw_buffer.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/regex_traits_defaults.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/static_mutex.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/w32_regex_traits.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/wc_regex_traits.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/wide_posix_api.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/winstances.cpp.o"
  "CMakeFiles/boost_regex-mt-shared-debug.dir/usinstances.cpp.o"
  "../../../lib/libboost_regex-mt-d.dylib"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/boost_regex-mt-shared-debug.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)

extension: cmake


text:
@article{brown2001regulation,
 author = {Brown, James H and Ernest, SK Morgan and Parody, Jennifer M and Haskell, John P},
 journal = {Oecologia},
 number = {3},
 pages = {321--332},
 publisher = {Springer Berlin Heidelberg},
 title = {Regulation of diversity: maintenance of species richness in changing environments},
 volume = {126},
 year = {2001}
}

repository: weecology/website

repo_name: weecology/website

gha_license_id: MIT


text:
package protocol

import (
	"WizechainFoundation/wizechain/network"
	"WizechainFoundation/wizechain/network/identity"
	"github.com/libp2p/go-libp2p-core/peer"
)

type MemberProvider interface {
	GetMembers() []identity.ID
}

type DefaultMembersProvider struct {
	WLP network.WhiteListProvider
}

// GetMembers return the list of all the members
func (d *DefaultMembersProvider) GetMembers() []identity.ID {
	pis, _ := d.WLP.GetPeers()
	members := make([]identity.ID, len(pis))
	for index, b := range pis {
		pi := peer.AddrInfo{}
		_ = pi.UnmarshalJSON(b)
		members[index] = identity.ID(pi.ID)
	}
	return members
}

repository: wizegene/wizechain

repo_name: wizegene/wizechain


text:
PV = "0.0cvs${CVSDATE}"
SECTION = "libs"
LICENSE = "Xorg"
MAINTAINER = "Greg Gilbert <greg@treke.net>"
DEPENDS = "xextensions"
DESCRIPTION = "X Resource usage extension headers"

SRC_URI = "cvs://anoncvs:anoncvs@pdx.freedesktop.org/cvs/xlibs;module=ResourceExt"
S = "${WORKDIR}/ResourceExt"

inherit autotools pkgconfig

do_stage() {
	oe_runmake install prefix=${STAGING_DIR} \
	       bindir=${STAGING_BINDIR} \
	       includedir=${STAGING_INCDIR} \
	       libdir=${STAGING_LIBDIR} \
	       datadir=${STAGING_DATADIR}
}

repository: Terentyev/familiar-linux

repo_name: Terentyev/familiar-linux


text:
# Copyright (c) 2021-2022 LG Electronics, Inc.

SUMMARY = "Image Viewer application"
AUTHOR = "Revanth Kumar <revanth.kumar@lge.com>"
SECTION = "webos/apps"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = " \
    file://LICENSE;md5=86d3f3a95c324c9479bd8986968f4327 \
    file://oss-pkg-info.yaml;md5=3072ffcf5bdbbc376ed21c9d378d14d5 \
"

WEBOS_VERSION = "0.0.1-15_ca49d724d66ff827acee8eb5e95c380fd3fc1de2"
PR = "r1"

PV = "0.0.1-15+git${SRCPV}"
SRCREV = "ca49d724d66ff827acee8eb5e95c380fd3fc1de2"

inherit webos_enactjs_app
inherit webos_public_repo

SRC_URI = "${WEBOSOSE_GIT_REPO_COMPLETE}"
S = "${WORKDIR}/git"

WEBOS_ENACTJS_APP_ID = "com.webos.app.imageviewer"
WEBOS_LOCALIZATION_DATA_PATH = "${S}"
WEBOS_LOCALIZATION_XLIFF_BASENAME = "imageviewer"

# Workaround for network access issue during do_compile task
do_compile[network] = "1"

repository: webOS-ports/meta-webos-ports

repo_name: webOS-ports/meta-webos-ports

branch_name: refs/heads/kirkstone

gha_language: BitBake


text:
SUMMARY = "Miscellaneous nilrt utilities"
DESCRIPTION = "nilrt distro-specific miscellaneous utilities that provide basic system functionality."
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
SECTION = "base"

SRC_URI = "file://status_led \
	   file://nisetbootmode.functions \
	   file://nisetbootmode \
"

FILES_${PN} += "\
	/usr/lib/nisetbootmode.functions \
"

DEPENDS += "shadow-native pseudo-native niacctbase"

RDEPENDS_${PN} += "niacctbase bash"

RDEPENDS_${PN}_append_x64 += "fw-printenv"

S = "${WORKDIR}"

do_install () {
	install -d ${D}${bindir}
	install -d ${D}${sysconfdir}
	install -d ${D}${libdir}
	install -m 0755   ${WORKDIR}/status_led         ${D}${bindir}
	install -m 0440   ${WORKDIR}/nisetbootmode.functions         ${D}${libdir}
	install -m 0550   ${WORKDIR}/nisetbootmode         ${D}${bindir}

	chown 0:${LVRT_GROUP} ${D}${bindir}/status_led

}

repository: NIwkoe/meta-nilrt

repo_name: NIwkoe/meta-nilrt

branch_name: refs/heads/nilrt/master/sumo


text:
package payload

import (
	"fmt"
)

type ResponseCode int

const (
	ResponseCodeNone         = ResponseCode(-1)
	ResponseCodeOK           = ResponseCode(0)
	ResponseCodeRejected     = ResponseCode(1)
	ResponseCodeBusy         = ResponseCode(2)
	ResponseCodeMoreBlocks   = ResponseCode(3)
	ResponseCodeNoMoreBlocks = ResponseCode(4)
	ResponseCodeSynced       = ResponseCode(5)
)

func (c ResponseCode) String() string {
	switch c {
	case ResponseCodeOK:
		return "ok"
	case ResponseCodeRejected:
		return "rejected"
	case ResponseCodeBusy:
		return "busy"
	case ResponseCodeMoreBlocks:
		return "more-blocks"
	case ResponseCodeNoMoreBlocks:
		return "no-more-blocks"
	case ResponseCodeSynced:
		return "synced"
	}
	return fmt.Sprintf("%d", c)
}

type Type int

const (
	PayloadTypeSalam                = Type(1) // Hello message
	PayloadTypeAleyk                = Type(2) // Hello Ack message
	PayloadTypeLatestBlocksRequest  = Type(3)
	PayloadTypeLatestBlocksResponse = Type(4)
	PayloadTypeQueryTransactions    = Type(5)
	PayloadTypeTransactions         = Type(6)
	PayloadTypeQueryProposal        = Type(7)
	PayloadTypeProposal             = Type(8)
	PayloadTypeHeartBeat            = Type(9)
	PayloadTypeQueryVotes           = Type(10)
	PayloadTypeVote                 = Type(11)
	PayloadTypeBlockAnnounce        = Type(12)
	PayloadTypeDownloadRequest      = Type(13)
	PayloadTypeDownloadResponse     = Type(14)
)

func (t Type) String() string {
	switch t {
	case PayloadTypeSalam:
		return "salam"
	case PayloadTypeAleyk:
		return "aleyk"
	case PayloadTypeLatestBlocksRequest:
		return "blocks-req"
	case PayloadTypeLatestBlocksResponse:
		return "blocks-res"
	case PayloadTypeQueryTransactions:
		return "query-txs"
	case PayloadTypeTransactions:
		return "txs"
	case PayloadTypeQueryProposal:
		return "query-proposal"
	case PayloadTypeProposal:
		return "proposal"
	case PayloadTypeHeartBeat:
		return "heart-beat"
	case PayloadTypeQueryVotes:
		return "query-votes"
	case PayloadTypeVote:
		return "vote"
	case PayloadTypeBlockAnnounce:
		return "block-announce"
	case PayloadTypeDownloadRequest:
		return "download-req"
	case PayloadTypeDownloadResponse:
		return "download-res"
	}
	return fmt.Sprintf("%d", t)
}

func MakePayload(t Type) Payload {
	switch t {
	case PayloadTypeSalam:
		return &SalamPayload{}
	case PayloadTypeAleyk:
		return &AleykPayload{}
	case PayloadTypeLatestBlocksRequest:
		return &LatestBlocksRequestPayload{}
	case PayloadTypeLatestBlocksResponse:
		return &LatestBlocksResponsePayload{}
	case PayloadTypeQueryTransactions:
		return &QueryTransactionsPayload{}
	case PayloadTypeTransactions:
		return &TransactionsPayload{}
	case PayloadTypeQueryProposal:
		return &QueryProposalPayload{}
	case PayloadTypeProposal:
		return &ProposalPayload{}
	case PayloadTypeHeartBeat:
		return &HeartBeatPayload{}
	case PayloadTypeQueryVotes:
		return &QueryVotesPayload{}
	case PayloadTypeVote:
		return &VotePayload{}
	case PayloadTypeBlockAnnounce:
		return &BlockAnnouncePayload{}
	case PayloadTypeDownloadRequest:
		return &DownloadRequestPayload{}
	case PayloadTypeDownloadResponse:
		return &DownloadResponsePayload{}
	}

	//
	return nil
}

type Payload interface {
	SanityCheck() error
	Type() Type
	Fingerprint() string
}

repository: FarhadGhE/zarb-go

repo_name: FarhadGhE/zarb-go


text:
@inproceedings{LeCerf2020,
  author={Maëlle Le Cerf and Emmanuel Ferragne},
  title={{Paramètres acoustiques et phonétiques dans la parole parkinsonienne avant et après traitement LSVT LOUD®}},
  year=2020,
  booktitle={Proc. XXXIIIe Journées d’Études sur la Parole},
  pages={326--334}
}

repository: emmanuelferragne/academic-kickstart

repo_name: emmanuelferragne/academic-kickstart


text:
DESCRIPTION = "Configuration files for online package repositories aka feeds"

PR = "1"
PACKAGE_ARCH = "${MACHINE_ARCH}"

FEED_BASEPATH ?= "unstable/feed/"

do_compile() {
        mkdir -p ${S}/${sysconfdir}/ipkg
	for feed in base debug perl python gstreamer ; do
          echo "src/gz ${feed} ${ANGSTROM_URI}/${FEED_BASEPATH}${FEED_ARCH}/${feed}" > ${S}/${sysconfdir}/ipkg/${feed}-feed.conf
	done

        echo "src/gz ${MACHINE_ARCH} ${ANGSTROM_URI}/${FEED_BASEPATH}${FEED_ARCH}/${MACHINE_ARCH}" >  ${S}/${sysconfdir}/ipkg/${MACHINE_ARCH}-feed.conf
	echo "src/gz no-arch ${ANGSTROM_URI}/${FEED_BASEPATH}/all" > ${S}/${sysconfdir}/ipkg/noarch-feed.conf
}

do_install () {
        install -d ${D}${sysconfdir}/ipkg
	install -m 0644  ${S}/${sysconfdir}/ipkg/* ${D}${sysconfdir}/ipkg/
}

CONFFILES_${PN} += "${sysconfdir}/ipkg/base-feed.conf \
                    ${sysconfdir}/ipkg/debug-feed.conf \
                    ${sysconfdir}/ipkg/perl-feed.conf \
                    ${sysconfdir}/ipkg/python-feed.conf \
                    ${sysconfdir}/ipkg/gstreamer-feed.conf \
                    ${sysconfdir}/ipkg/${MACHINE_ARCH}-feed.conf \
                    ${sysconfdir}/ipkg/noarch-feed.conf \
                   "

repository: jdegges/gumstix-pip-oe

repo_name: jdegges/gumstix-pip-oe


text:
#############################
# STM32F103VBIx (Cortex-M3) #
#############################

# CMake includes the toolchain file multiple times when configuring the build,
# which causes errors for some flags (e.g., --specs=nano.specs).
# We prevent this with an include guard.
if(STM32F103VBIx_TOOLCHAIN_INCLUDED)
	return()
endif()

set(STM32F103VBIx_TOOLCHAIN_INCLUDED true)

set(CPU_NAME STM32F103VBIx)

set(LINKER_SCRIPT_DIR ${CMAKE_SOURCE_DIR}/cmake/linker-scripts/stm)
set(LINKER_SCRIPT_PRIMARY_FILE STM32F103VBIx_FLASH.ld)

# These dependencies are applied to add_executable targets by the
# AddExecutableWithLinkerScriptDep module
list(APPEND LINKER_SCRIPT_DEPENDENCIES "${LINKER_SCRIPT_DIR}/${LINKER_SCRIPT_PRIMARY_FILE}")

set(LD_FLAGS "-T${LINKER_SCRIPT_PRIMARY_FILE} -L${LINKER_SCRIPT_DIR}")

include(${CMAKE_CURRENT_LIST_DIR}/cortex-m3.cmake)

repository: embeddedartistry/cmake-buildsystem

repo_name: embeddedartistry/cmake-buildsystem


text:
package SearchInRotatedSortedArray

import "testing"

func TestSearch(t *testing.T) {

	if search([]int{}, 1) == -1 {
		t.Log("pass")
	} else {
		t.Error("failed")
	}

	if search([]int{0, 1, 2, 4, 5, 6, 7}, 7) == 6 {
		t.Log("pass")
	} else {
		t.Error("failed")
	}

	if search([]int{4, 5, 6, 7, 0, 1, 2}, 7) == 3 {
		t.Log("pass")
	} else {
		t.Error("failed")
	}

	if search([]int{5, 6, 7, 0, 1, 2, 4}, 7) == 2 {
		t.Log("pass")
	} else {
		t.Error("failed")
	}

	if search([]int{4, 5, 6, 7, 0, 1, 2}, 8) == -1 {
		t.Log("pass")
	} else {
		t.Error("failed")
	}

}


text:
package main

import (
	"fmt"
	"sync"
)

var connectionManagerOnce sync.Once
var connectionManager *ConnectionManager

type ConnectionManager struct {
	address string
}

func (cm *ConnectionManager) GetAddress() string {
	return cm.address
}

func NewConnectionManager(address string) *ConnectionManager {
	connectionManagerOnce.Do(func() {
		connectionManager = &ConnectionManager{
			address: address,
		}
	})
	return connectionManager
}

type fruit struct {
	name string
}

var singletonFruit *fruit

func init() {
	//initialize static instance on load
	singletonFruit = &fruit{name: "fruit"}
}

//GetFruit - get singleton instance pre-initialized
func GetFruit() *fruit {
	return singletonFruit
}

func (f *fruit) GetName() string {
	return f.name
}

func main() {
	//in the main thread connectionManager will create once time.
	cm := NewConnectionManager("apple")
	fmt.Println(cm.GetAddress())

	//  can not new different object, cm is apple forever
	cm = NewConnectionManager("banana")
	fmt.Println(cm.GetAddress())

	// when import a package the fruit object will be set up at init function  , everyone can not revise it anymore in runtime.
	f := GetFruit()
	fmt.Println(f.GetName())
}


text:
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

// Package commonsubset wraps the ACS (Asynchronous Common Subset) part from
// the HoneyBadgerBFT with the Peering for communication layer. The main objective
// here is to ensure eventual delivery of all the messages, as that is the assumption
// of the ACS algorithm.
//
// To ensure the eventual delivery of messages, we are resending them until they
// are acknowledged by a peer. The acknowledgements are carried along with other
// messages to decrease communication overhead.
//
// We are using a forked version of https://github.com/anthdm/hbbft. The fork was
// made to gave misc mistakes fixed that made apparent in the case of out-of-order
// message delivery.
//
// The main references:
//
//  - https://eprint.iacr.org/2016/199.pdf
//    The original HBBFT paper.
//
//  - https://dl.acm.org/doi/10.1145/2611462.2611468
//    Here the BBA part is originally presented.
//    Most of the mistakes in the lib was in this part.
//
//  - https://dl.acm.org/doi/10.1145/197917.198088
//    The definition of ACS is by Ben-Or. At least looks so.
//

//nolint:dupl // TODO there is a bunch of duplicated code in this file, should be refactored to reusable funcs
package commonsubset

import (
	"bytes"
	"encoding/binary"
	"io"
	"time"

	"github.com/anthdm/hbbft"
	"github.com/iotaledger/hive.go/logger"
	"github.com/iotaledger/wasp/packages/chain/consensus/commoncoin"
	"github.com/iotaledger/wasp/packages/peering"
	"github.com/iotaledger/wasp/packages/tcrypto"
	"github.com/iotaledger/wasp/packages/util"
	"golang.org/x/xerrors"
)

const (
	acsMsgType   = 50 + peering.FirstUserMsgCode
	resendPeriod = 500 * time.Millisecond
)

// region CommonSubset /////////////////////////////////////////////////////////

// CommonSubject is responsible for executing a single instance of agreement.
// The main task for this object is to manage all the redeliveries and acknowledgements.
type CommonSubset struct {
	impl *hbbft.ACS // The ACS implementation.

	batchCounter   uint32               // Used to assign unique numbers to the messages.
	missingAcks    map[uint32]time.Time // Not yet acknowledged batches sent by us and the time of the last resend.
	pendingAcks    [][]uint32           // pendingAcks[PeerID] -- acks to be sent to the peer.
	recvMsgBatches []map[uint32]uint32  // [PeerId]ReceivedMbID -> AckedInMb (0 -- unacked). It remains 0, if acked in non-data message.
	sentMsgBatches map[uint32]*msgBatch // BatchID -> MsgBatch

	sessionID   uint64                // Unique identifier for this consensus instance. Used to route messages.
	stateIndex  uint32                // Sequence number of the CS transaction we are agreeing on.
	peeringID   peering.PeeringID     // ID for the communication group.
	netGroup    peering.GroupProvider // Group of nodes we are communicating with.
	netOwnIndex uint16                // Our index in the group.

	inputCh  chan []byte            // For our input to the consensus.
	recvCh   chan *msgBatch         // For incoming messages.
	closeCh  chan bool              // To implement closing of the object.
	outputCh chan map[uint16][]byte // The caller will receive its result via this channel.
	done     bool                   // Indicates, if the decision is already made.
	log      *logger.Logger         // Logger, of course.
}

func NewCommonSubset(
	sessionID uint64,
	stateIndex uint32,
	peeringID peering.PeeringID,
	netGroup peering.GroupProvider,
	dkShare *tcrypto.DKShare,
	allRandom bool, // Set to true to have real CC rounds for each epoch. That's for testing mostly.
	outputCh chan map[uint16][]byte,
	log *logger.Logger,
) (*CommonSubset, error) {
	ownIndex := netGroup.SelfIndex()
	allNodes := netGroup.AllNodes()
	nodeCount := len(allNodes)
	nodes := make([]uint64, nodeCount)
	nodePos := 0
	for ni := range allNodes {
		nodes[nodePos] = uint64(ni)
		nodePos++
	}
	if outputCh == nil {
		outputCh = make(chan map[uint16][]byte, 1)
	}
	var salt [8]byte
	binary.BigEndian.PutUint64(salt[:], sessionID)
	acsCfg := hbbft.Config{
		N:          nodeCount,
		F:          nodeCount - int(dkShare.T),
		ID:         uint64(ownIndex),
		Nodes:      nodes,
		BatchSize:  0, // Unused in ACS.
		CommonCoin: commoncoin.NewBlsCommonCoin(dkShare, salt[:], allRandom),
	}
	cs := CommonSubset{
		impl:           hbbft.NewACS(acsCfg),
		batchCounter:   0,
		missingAcks:    make(map[uint32]time.Time),
		pendingAcks:    make([][]uint32, nodeCount),
		recvMsgBatches: make([]map[uint32]uint32, nodeCount),
		sentMsgBatches: make(map[uint32]*msgBatch),
		sessionID:      sessionID,
		stateIndex:     stateIndex,
		peeringID:      peeringID,
		netGroup:       netGroup,
		netOwnIndex:    ownIndex,
		inputCh:        make(chan []byte, 1),
		recvCh:         make(chan *msgBatch, 1),
		closeCh:        make(chan bool),
		outputCh:       outputCh,
		log:            log,
	}
	for i := range cs.recvMsgBatches {
		cs.recvMsgBatches[i] = make(map[uint32]uint32)
	}
	for i := range cs.pendingAcks {
		cs.pendingAcks[i] = make([]uint32, 0)
	}
	go cs.run()
	return &cs, nil
}

// OutputCh returns the output channel, so that the called don't need to track it.
func (cs *CommonSubset) OutputCh() chan map[uint16][]byte {
	return cs.outputCh
}

// Input accepts the current node's proposal for the consensus.
func (cs *CommonSubset) Input(input []byte) {
	cs.inputCh <- input
}

// TryHandleMessage checks, if the RecvEvent is of suitable type and
// processed the message as an input from a peer if the type matches.
// This one is called from the ACS tests.
func (cs *CommonSubset) TryHandleMessage(recv *peering.RecvEvent) bool {
	if recv.Msg.MsgType != acsMsgType {
		return false
	}
	mb := msgBatch{}
	if err := mb.FromBytes(recv.Msg.MsgData); err != nil {
		cs.log.Errorf("Cannot decode message: %v", err)
		return true
	}
	cs.HandleMsgBatch(&mb)
	return true
}

// HandleMsgBatch accepts a parsed msgBatch as an input from other node.
// This function is used in the CommonSubsetCoordinator to avoid parsing
// the received message multiple times.
func (cs *CommonSubset) HandleMsgBatch(mb *msgBatch) {
	defer func() {
		if err := recover(); err != nil {
			// Just to avoid panics on writing to a closed channel.
			// This can happen on the ACS termination.
			cs.log.Warnf("Dropping msgBatch reason=%v", err)
		}
	}()
	cs.recvCh <- mb
}

func (cs *CommonSubset) Close() {
	cs.impl.Stop()
	close(cs.closeCh)
	close(cs.recvCh)
	close(cs.inputCh)
}

func (cs *CommonSubset) run() {
	retry := time.After(resendPeriod)
	for {
		select {
		case <-retry:
			cs.timeTick()
			if !cs.done || len(cs.pendingAcks) != 0 {
				// The condition for stopping the resend is a bit tricky, because it is
				// not enough for this node to complete with the decision. This node
				// must help others to decide as well.
				retry = time.After(resendPeriod)
			}
		case input, ok := <-cs.inputCh:
			if !ok {
				return
			}
			if err := cs.handleInput(input); err != nil {
				cs.log.Errorf("Failed to handle input, reason: %v", err)
			}
		case mb, ok := <-cs.recvCh:
			if !ok {
				return
			}
			cs.handleMsgBatch(mb)
		case <-cs.closeCh:
			return
		}
	}
}

func (cs *CommonSubset) timeTick() {
	if cs.log.Desugar().Core().Enabled(logger.LevelDebug) { // Debug info for the ACS.
		rbcInstances, bbaInstances, rbcResults, bbaResults, msgQueue := cs.impl.DebugInfo()
		cs.log.Debugf("ACS::timeTick[%v], sessionId=%v, done=%v queue.len=%v, bba.res=%v", cs.impl.ID, cs.sessionID, cs.done, len(msgQueue), bbaResults)
		for i, bba := range bbaInstances {
			if !bba.Done() {
				cs.log.Debugf("ACS::timeTick[%v], sessionId=%v, impl.bba[%v]=%+v", cs.impl.ID, cs.sessionID, i, bba)
			}
		}
		for i, rbc := range rbcInstances {
			if _, ok := rbcResults[i]; !ok {
				cs.log.Debugf("ACS::timeTick[%v], sessionId=%v, impl.rbc[%v]=%+v", cs.impl.ID, cs.sessionID, i, rbc)
			}
		}
	}

	now := time.Now()
	resentBefore := now.Add(resendPeriod * (-2))
	for missingAck, lastSentTime := range cs.missingAcks {
		if lastSentTime.Before(resentBefore) {
			if mb, ok := cs.sentMsgBatches[missingAck]; ok {
				cs.send(mb)
				cs.missingAcks[missingAck] = now
			} else {
				// Batch is already cleaned up, so we don't need the ack.
				delete(cs.missingAcks, missingAck)
			}
		}
	}
}

func (cs *CommonSubset) handleInput(input []byte) error {
	var err error
	if err = cs.impl.InputValue(input); err != nil {
		return xerrors.Errorf("Failed to process ACS.InputValue: %w", err)
	}
	cs.sendPendingMessages()
	return nil
}

func (cs *CommonSubset) handleMsgBatch(recvBatch *msgBatch) {
	//
	// Cleanup all the acknowledged messages from the missing acks list.
	for _, receivedAck := range recvBatch.acks {
		delete(cs.missingAcks, receivedAck)
	}
	//
	// Resend the old responses, if ack was not received
	// and the message is already processed.
	if ackIn, ok := cs.recvMsgBatches[recvBatch.src][recvBatch.id]; ok {
		if ackIn == 0 {
			// Make a fake message just to acknowledge the message, because sender has
			// retried it already and we haven't sent the ack yet. We will not expect
			// an acknowledgement for this ack.
			cs.send(cs.makeAckOnlyBatch(recvBatch.src, recvBatch.id))
		} else {
			cs.send(cs.sentMsgBatches[ackIn])
		}
		return
	}
	//
	// If we have completed with the decision, we just acknowledging other's messages.
	// That is needed to help other members to decide on termination.
	if cs.done {
		if recvBatch.NeedsAck() {
			cs.send(cs.makeAckOnlyBatch(recvBatch.src, recvBatch.id))
		}
		return
	}
	if recvBatch.NeedsAck() {
		// Batches with id=0 are for acks only, they contain no data,
		// therefore we will not track them, just respond on the fly.
		// Otherwise we store the batch ID to be acknowledged with the
		// next outgoing message batch to that peer.
		cs.recvMsgBatches[recvBatch.src][recvBatch.id] = 0 // Received, not acknowledged yet.
		cs.pendingAcks[recvBatch.src] = append(cs.pendingAcks[recvBatch.src], recvBatch.id)
	}
	//
	// Process the messages.
	for _, m := range recvBatch.msgs {
		if err := cs.impl.HandleMessage(uint64(recvBatch.src), m); err != nil {
			cs.log.Errorf("Failed to handle message: %v, message=%+v", err, m)
		}
	}
	//
	// Send the outgoing messages.
	cs.sendPendingMessages()
	//
	// Check, maybe we are done.
	if cs.impl.Done() {
		var output map[uint64][]byte = cs.impl.Output()
		out16 := make(map[uint16][]byte)
		for index, share := range output {
			out16[uint16(index)] = share
		}
		cs.done = true
		cs.outputCh <- out16
	}
}

func (cs *CommonSubset) sendPendingMessages() {
	var outBatches []*msgBatch
	var err error
	if outBatches, err = cs.makeBatches(cs.impl.Messages()); err != nil {
		cs.log.Errorf("Failed to make out batch: %v", err)
	}
	now := time.Now()
	for _, b := range outBatches {
		b.acks = cs.pendingAcks[b.dst]
		cs.pendingAcks[b.dst] = make([]uint32, 0)
		for i := range b.acks {
			// Update the reverse index, i.e. for each message,
			// specify message which have acknowledged it.
			cs.recvMsgBatches[b.dst][b.acks[i]] = b.id
		}
		cs.sentMsgBatches[b.id] = b
		cs.missingAcks[b.id] = now
		cs.send(b)
	}
}

func (cs *CommonSubset) makeBatches(msgs []hbbft.MessageTuple) ([]*msgBatch, error) {
	batchMsgs := make([][]*hbbft.ACSMessage, cs.impl.N)
	for i := range batchMsgs {
		batchMsgs[i] = make([]*hbbft.ACSMessage, 0)
	}
	for _, m := range msgs {
		if acsMsg, ok := m.Payload.(*hbbft.ACSMessage); ok {
			batchMsgs[m.To] = append(batchMsgs[m.To], acsMsg)
		} else {
			return nil, xerrors.Errorf("unexpected message payload type: %T", m.Payload)
		}
	}
	batches := make([]*msgBatch, 0)
	for i := range batchMsgs {
		if len(batchMsgs[i]) == 0 {
			continue
		}
		cs.batchCounter++
		batches = append(batches, &msgBatch{
			sessionID:  cs.sessionID,
			stateIndex: cs.stateIndex,
			id:         cs.batchCounter,
			src:        uint16(cs.impl.ID),
			dst:        uint16(i),
			msgs:       batchMsgs[i],
			acks:       make([]uint32, 0), // Filled later.
		})
	}
	return batches, nil
}

func (cs *CommonSubset) makeAckOnlyBatch(peerID uint16, ackMB uint32) *msgBatch {
	acks := []uint32{}
	if ackMB != 0 {
		acks = append(acks, ackMB)
	}
	if len(cs.pendingAcks[peerID]) != 0 {
		acks = append(acks, cs.pendingAcks[peerID]...)
		cs.pendingAcks[peerID] = make([]uint32, 0)
	}
	if len(acks) == 0 {
		return nil
	}
	return &msgBatch{
		sessionID:  cs.sessionID,
		stateIndex: cs.stateIndex,
		id:         0, // Do not require an acknowledgement.
		src:        uint16(cs.impl.ID),
		dst:        peerID,
		msgs:       []*hbbft.ACSMessage{},
		acks:       acks,
	}
}

func (cs *CommonSubset) send(msgBatch *msgBatch) {
	if msgBatch == nil {
		// makeAckOnlyBatch can produce nil batches, if there is nothing
		// to acknowledge. We handle that here, to avoid IFs in multiple places.
		return
	}
	cs.log.Debugf("ACS::IO - Sending a msgBatch=%+v", msgBatch)
	cs.netGroup.SendMsgByIndex(msgBatch.dst, &peering.PeerMessage{
		PeeringID:   cs.peeringID,
		SenderIndex: cs.netOwnIndex,
		Timestamp:   0,
		MsgType:     acsMsgType,
		MsgData:     msgBatch.Bytes(),
	})
}

// endregion ///////////////////////////////////////////////////////////////////

// region msgBatch /////////////////////////////////////////////////////////////

/** msgBatch groups messages generated at one step in the protocol for a single recipient. */
type msgBatch struct {
	sessionID  uint64
	stateIndex uint32
	id         uint32              // ID of the batch for the acks, ID=0 => Acks are not needed.
	src        uint16              // Sender of the batch.
	dst        uint16              // Recipient of the batch.
	msgs       []*hbbft.ACSMessage // New messages to send.
	acks       []uint32            // Acknowledgements.
}

const (
	acsMsgTypeRbcProofRequest byte = 1 << 4
	acsMsgTypeRbcEchoRequest  byte = 2 << 4
	acsMsgTypeRbcReadyRequest byte = 3 << 4
	acsMsgTypeAbaBvalRequest  byte = 4 << 4
	acsMsgTypeAbaAuxRequest   byte = 5 << 4
	acsMsgTypeAbaCCRequest    byte = 6 << 4
	acsMsgTypeAbaDoneRequest  byte = 7 << 4
)

func (b *msgBatch) NeedsAck() bool {
	return b.id != 0
}

//nolint:funlen, gocyclo // TODO this function is too long and has a high cyclomatic complexity, should be refactored
func (b *msgBatch) Write(w io.Writer) error {
	var err error
	if err = util.WriteUint64(w, b.sessionID); err != nil {
		return xerrors.Errorf("failed to write msgBatch.sessionID: %w", err)
	}
	if err = util.WriteUint32(w, b.stateIndex); err != nil {
		return xerrors.Errorf("failed to write msgBatch.stateIndex: %w", err)
	}
	if err = util.WriteUint32(w, b.id); err != nil {
		return xerrors.Errorf("failed to write msgBatch.id: %w", err)
	}
	if err = util.WriteUint16(w, b.src); err != nil {
		return xerrors.Errorf("failed to write msgBatch.src: %w", err)
	}
	if err = util.WriteUint16(w, b.dst); err != nil {
		return xerrors.Errorf("failed to write msgBatch.dst: %w", err)
	}
	if err = util.WriteUint16(w, uint16(len(b.msgs))); err != nil {
		return xerrors.Errorf("failed to write msgBatch.msgs.len: %w", err)
	}
	for i, acsMsg := range b.msgs {
		if err = util.WriteUint16(w, uint16(acsMsg.ProposerID)); err != nil {
			return xerrors.Errorf("failed to write msgBatch.msgs[%v].ProposerID: %w", i, err)
		}
		switch acsMsgPayload := acsMsg.Payload.(type) {
		case *hbbft.BroadcastMessage:
			switch rbcMsgPayload := acsMsgPayload.Payload.(type) {
			case *hbbft.ProofRequest:
				if err = util.WriteByte(w, acsMsgTypeRbcProofRequest); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].type: %w", i, err)
				}
				if err = util.WriteBytes16(w, rbcMsgPayload.RootHash); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].RootHash: %w", i, err)
				}
				if err = util.WriteUint32(w, uint32(len(rbcMsgPayload.Proof))); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Proof.len: %w", i, err)
				}
				for pi, p := range rbcMsgPayload.Proof {
					if err = util.WriteBytes32(w, p); err != nil {
						return xerrors.Errorf("failed to write msgBatch.msgs[%v].Proof[%v]: %w", i, pi, err)
					}
				}
				if err = util.WriteUint16(w, uint16(rbcMsgPayload.Index)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Index: %w", i, err)
				}
				if err = util.WriteUint16(w, uint16(rbcMsgPayload.Leaves)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Leaves: %w", i, err)
				}
			case *hbbft.EchoRequest:
				if err = util.WriteByte(w, acsMsgTypeRbcEchoRequest); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].type: %w", i, err)
				}
				if err = util.WriteBytes16(w, rbcMsgPayload.RootHash); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].RootHash: %w", i, err)
				}
				if err = util.WriteUint32(w, uint32(len(rbcMsgPayload.Proof))); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Proof.len: %w", i, err)
				}
				for pi, p := range rbcMsgPayload.Proof {
					if err = util.WriteBytes32(w, p); err != nil {
						return xerrors.Errorf("failed to write msgBatch.msgs[%v].Proof[%v]: %w", i, pi, err)
					}
				}
				if err = util.WriteUint16(w, uint16(rbcMsgPayload.Index)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Index: %w", i, err)
				}
				if err = util.WriteUint16(w, uint16(rbcMsgPayload.Leaves)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Leaves: %w", i, err)
				}
			case *hbbft.ReadyRequest:
				if err = util.WriteByte(w, acsMsgTypeRbcReadyRequest); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].type: %w", i, err)
				}
				if err = util.WriteBytes16(w, rbcMsgPayload.RootHash); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].RootHash: %w", i, err)
				}
			default:
				return xerrors.Errorf("failed to write msgBatch.msgs[%v]: unexpected broadcast message type", i)
			}
		case *hbbft.AgreementMessage:
			switch abaMsgPayload := acsMsgPayload.Message.(type) {
			case *hbbft.BvalRequest:
				encoded := acsMsgTypeAbaBvalRequest
				if abaMsgPayload.Value {
					encoded |= 1
				}
				if err = util.WriteByte(w, encoded); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].value: %w", i, err)
				}
				if err = util.WriteUint16(w, uint16(acsMsgPayload.Epoch)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].epoch: %w", i, err)
				}
			case *hbbft.AuxRequest:
				encoded := acsMsgTypeAbaAuxRequest
				if abaMsgPayload.Value {
					encoded |= 1
				}
				if err = util.WriteByte(w, encoded); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].value: %w", i, err)
				}
				if err = util.WriteUint16(w, uint16(acsMsgPayload.Epoch)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].epoch: %w", i, err)
				}
			case *hbbft.CCRequest:
				coinMsg := abaMsgPayload.Payload.(*commoncoin.BlsCommonCoinMsg)
				if err = util.WriteByte(w, acsMsgTypeAbaCCRequest); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].type: %w", i, err)
				}
				if err = util.WriteUint16(w, uint16(acsMsgPayload.Epoch)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].epoch: %w", i, err)
				}
				if err = coinMsg.Write(w); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].Payload: %w", i, err)
				}
			case *hbbft.DoneRequest:
				encoded := acsMsgTypeAbaDoneRequest
				if err = util.WriteByte(w, encoded); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].type: %w", i, err)
				}
				if err = util.WriteUint16(w, uint16(acsMsgPayload.Epoch)); err != nil {
					return xerrors.Errorf("failed to write msgBatch.msgs[%v].epoch: %w", i, err)
				}
			default:
				return xerrors.Errorf("failed to write msgBatch.msgs[%v]: unexpected agreemet message type", i)
			}
		default:
			return xerrors.Errorf("failed to write msgBatch.msgs[%v]: unexpected acs message type", i)
		}
	}
	if err = util.WriteUint16(w, uint16(len(b.acks))); err != nil {
		return xerrors.Errorf("failed to write msgBatch.acks.len: %w", err)
	}
	for i, ack := range b.acks {
		if err = util.WriteUint32(w, ack); err != nil {
			return xerrors.Errorf("failed to write msgBatch.acks[%v]: %w", i, err)
		}
	}
	return nil
}

//nolint:funlen, gocyclo // TODO this function is too long and has a high cyclomatic complexity, should be refactored
func (b *msgBatch) Read(r io.Reader) error {
	var err error
	if err = util.ReadUint64(r, &b.sessionID); err != nil {
		return xerrors.Errorf("failed to read msgBatch.sessionID: %w", err)
	}
	if err = util.ReadUint32(r, &b.stateIndex); err != nil {
		return xerrors.Errorf("failed to read msgBatch.stateIndex: %w", err)
	}
	if err = util.ReadUint32(r, &b.id); err != nil {
		return xerrors.Errorf("failed to read msgBatch.id: %w", err)
	}
	if err = util.ReadUint16(r, &b.src); err != nil {
		return xerrors.Errorf("failed to read msgBatch.src: %w", err)
	}
	if err = util.ReadUint16(r, &b.dst); err != nil {
		return xerrors.Errorf("failed to read msgBatch.dst: %w", err)
	}
	//
	// Msgs.
	var msgsLen uint16
	if err = util.ReadUint16(r, &msgsLen); err != nil {
		return xerrors.Errorf("failed to read msgBatch.msgs.len: %w", err)
	}
	b.msgs = make([]*hbbft.ACSMessage, msgsLen)
	for mi := range b.msgs {
		acsMsg := hbbft.ACSMessage{}
		b.msgs[mi] = &acsMsg
		// ProposerID.
		var proposerID uint16
		if err = util.ReadUint16(r, &proposerID); err != nil {
			return xerrors.Errorf("failed to read msgBatch.msgs[%v].ProposerID: %w", mi, err)
		}
		acsMsg.ProposerID = uint64(proposerID)
		// By Type.
		var msgType byte
		if msgType, err = util.ReadByte(r); err != nil {
			return xerrors.Errorf("failed to read msgBatch.msgs[%v].type: %w", mi, err)
		}
		switch msgType & 0xF0 {
		case acsMsgTypeRbcProofRequest:
			proofRequest := hbbft.ProofRequest{}
			if proofRequest.RootHash, err = util.ReadBytes16(r); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].RootHash: %w", mi, err)
			}
			var proofLen uint32
			if err = util.ReadUint32(r, &proofLen); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Proof.len: %w", mi, err)
			}
			proofRequest.Proof = make([][]byte, proofLen)
			for pi := range proofRequest.Proof {
				if proofRequest.Proof[pi], err = util.ReadBytes32(r); err != nil {
					return xerrors.Errorf("failed to read msgBatch.msgs[%v].Proof[%v]: %w", mi, pi, err)
				}
			}
			var proofRequestIndex uint16
			if err = util.ReadUint16(r, &proofRequestIndex); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Index: %w", mi, err)
			}
			proofRequest.Index = int(proofRequestIndex)
			var proofRequestLeaves uint16
			if err = util.ReadUint16(r, &proofRequestLeaves); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Leaves: %w", mi, err)
			}
			proofRequest.Leaves = int(proofRequestLeaves)
			acsMsg.Payload = &hbbft.BroadcastMessage{
				Payload: &proofRequest,
			}
		case acsMsgTypeRbcEchoRequest:
			echoRequest := hbbft.EchoRequest{}
			if echoRequest.RootHash, err = util.ReadBytes16(r); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].RootHash: %w", mi, err)
			}
			var proofLen uint32
			if err = util.ReadUint32(r, &proofLen); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Proof.len: %w", mi, err)
			}
			echoRequest.Proof = make([][]byte, proofLen)
			for pi := range echoRequest.Proof {
				if echoRequest.Proof[pi], err = util.ReadBytes32(r); err != nil {
					return xerrors.Errorf("failed to read msgBatch.msgs[%v].Proof[%v]: %w", mi, pi, err)
				}
			}
			var echoRequestIndex uint16
			if err = util.ReadUint16(r, &echoRequestIndex); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Index: %w", mi, err)
			}
			echoRequest.Index = int(echoRequestIndex)
			var echoRequestLeaves uint16
			if err = util.ReadUint16(r, &echoRequestLeaves); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Leaves: %w", mi, err)
			}
			echoRequest.Leaves = int(echoRequestLeaves)
			acsMsg.Payload = &hbbft.BroadcastMessage{
				Payload: &echoRequest,
			}
		case acsMsgTypeRbcReadyRequest:
			readyRequest := hbbft.ReadyRequest{}
			if readyRequest.RootHash, err = util.ReadBytes16(r); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].RootHash: %w", mi, err)
			}
			acsMsg.Payload = &hbbft.BroadcastMessage{
				Payload: &readyRequest,
			}
		case acsMsgTypeAbaBvalRequest:
			var epoch uint16
			if err = util.ReadUint16(r, &epoch); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].epoch: %w", mi, err)
			}
			acsMsg.Payload = &hbbft.AgreementMessage{
				Epoch:   int(epoch),
				Message: &hbbft.BvalRequest{Value: msgType&0x01 == 1},
			}
		case acsMsgTypeAbaAuxRequest:
			var epoch uint16
			if err = util.ReadUint16(r, &epoch); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].epoch: %w", mi, err)
			}
			acsMsg.Payload = &hbbft.AgreementMessage{
				Epoch:   int(epoch),
				Message: &hbbft.AuxRequest{Value: msgType&0x01 == 1},
			}
		case acsMsgTypeAbaCCRequest:
			var epoch uint16
			if err = util.ReadUint16(r, &epoch); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].epoch: %w", mi, err)
			}
			var ccReq commoncoin.BlsCommonCoinMsg
			if err = ccReq.Read(r); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].Payload: %w", mi, err)
			}
			acsMsg.Payload = &hbbft.AgreementMessage{
				Epoch: int(epoch),
				Message: &hbbft.CCRequest{
					Payload: &ccReq,
				},
			}
		case acsMsgTypeAbaDoneRequest:
			var epoch uint16
			if err = util.ReadUint16(r, &epoch); err != nil {
				return xerrors.Errorf("failed to read msgBatch.msgs[%v].epoch: %w", mi, err)
			}
			acsMsg.Payload = &hbbft.AgreementMessage{
				Epoch:   int(epoch),
				Message: &hbbft.DoneRequest{},
			}
		default:
			return xerrors.Errorf("failed to read msgBatch.msgs[%v]: unexpected message type %v, b=%+v", mi, msgType, b)
		}
	}
	//
	// Acks.
	var acksLen uint16
	if err = util.ReadUint16(r, &acksLen); err != nil {
		return xerrors.Errorf("failed to read msgBatch.acks.len: %w", err)
	}
	b.acks = make([]uint32, acksLen)
	for ai := range b.acks {
		if err = util.ReadUint32(r, &b.acks[ai]); err != nil {
			return xerrors.Errorf("failed to read msgBatch.acks[%v]: %w", ai, err)
		}
	}
	return nil
}

func (b *msgBatch) FromBytes(buf []byte) error {
	r := bytes.NewReader(buf)
	return b.Read(r)
}

func (b *msgBatch) Bytes() []byte {
	var buf bytes.Buffer
	_ = b.Write(&buf)
	return buf.Bytes()
}

// endregion ///////////////////////////////////////////////////////////////////