text:
/*
	Module: rt2x00lib
	Abstract: rt2x00 debugfs specific routines.
 */

#include <linux/debugfs.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/uaccess.h>

#include "rt2x00.h"
#include "rt2x00lib.h"
#include "rt2x00dump.h"

#define MAX_LINE_LENGTH 64

struct rt2x00debug_crypto {
	unsigned long success;
	unsigned long icv_error;
	unsigned long mic_error;
	unsigned long key_error;
};

struct rt2x00debug_intf {
	/*
	 * Pointer to driver structure where
	 * this debugfs entry belongs to.
	 */
	struct rt2x00_dev *rt2x00dev;

	/*
	 * Reference to the rt2x00debug structure
	 * which can be used to communicate with
	 * the registers.
	 */
	const struct rt2x00debug *debug;

	/*
	 * Debugfs entries for:
	 * - driver folder
	 *   - driver file
	 *   - chipset file
	 *   - device flags file
	 *   - register folder
	 *     - csr offset/value files
	 *     - eeprom offset/value files
	 *     - bbp offset/value files
	 *     - rf offset/value files
	 *   - queue folder
	 *     - frame dump file
	 *     - queue stats file
	 *     - crypto stats file
	 */
	struct dentry *driver_folder;
	struct dentry *driver_entry;
	struct dentry *chipset_entry;
	struct dentry *dev_flags;
	struct dentry *register_folder;
	struct dentry *csr_off_entry;
	struct dentry *csr_val_entry;
	struct dentry *eeprom_off_entry;
	struct dentry *eeprom_val_entry;
	struct dentry *bbp_off_entry;
	struct dentry *bbp_val_entry;
	struct dentry *rf_off_entry;
	struct dentry *rf_val_entry;
	struct dentry *queue_folder;
	struct dentry *queue_frame_dump_entry;
	struct dentry *queue_stats_entry;
	struct dentry *crypto_stats_entry;

	/*
	 * The frame dump file only allows a single reader,
	 * so we need to store the current state here.
	 */
	unsigned long frame_dump_flags;
#define FRAME_DUMP_FILE_OPEN	1

	/*
	 * We queue each frame before dumping it to the user,
	 * per read command we will pass a single skb structure
	 * so we should be prepared to queue multiple sk buffers
	 * before sending it to userspace.
	 */
	struct sk_buff_head frame_dump_skbqueue;
	wait_queue_head_t frame_dump_waitqueue;

	/*
	 * HW crypto statistics.
	 * All statistics are stored seperately per cipher type.
	 */
	struct rt2x00debug_crypto crypto_stats[CIPHER_MAX];

	/*
	 * Driver and chipset files will use a data buffer
	 * that has been created in advance. This will simplify
	 * the code since we can use the debugfs functions.
	 */
	struct debugfs_blob_wrapper driver_blob;
	struct debugfs_blob_wrapper chipset_blob;

	/*
	 * Requested offset for each register type.
	 */
	unsigned int offset_csr;
	unsigned int offset_eeprom;
	unsigned int offset_bbp;
	unsigned int offset_rf;
};

void rt2x00debug_update_crypto(struct rt2x00_dev *rt2x00dev,
			       struct rxdone_entry_desc *rxdesc)
{
	struct rt2x00debug_intf *intf = rt2x00dev->debugfs_intf;
	enum cipher cipher = rxdesc->cipher;
	enum rx_crypto status = rxdesc->cipher_status;

	if (cipher == CIPHER_TKIP_NO_MIC)
		cipher = CIPHER_TKIP;
	if (cipher == CIPHER_NONE || cipher >= CIPHER_MAX)
		return;

	/* Remove CIPHER_NONE index */
	cipher--;

	intf->crypto_stats[cipher].success += (status == RX_CRYPTO_SUCCESS);
	intf->crypto_stats[cipher].icv_error += (status == RX_CRYPTO_FAIL_ICV);
	intf->crypto_stats[cipher].mic_error += (status == RX_CRYPTO_FAIL_MIC);
	intf->crypto_stats[cipher].key_error += (status == RX_CRYPTO_FAIL_KEY);
}

void rt2x00debug_dump_frame(struct rt2x00_dev *rt2x00dev,
			    enum rt2x00_dump_type type, struct sk_buff *skb)
{
	struct rt2x00debug_intf *intf = rt2x00dev->debugfs_intf;
	struct skb_frame_desc *desc = get_skb_frame_desc(skb);
	struct sk_buff *skbcopy;
	struct rt2x00dump_hdr *dump_hdr;
	struct timeval timestamp;

	do_gettimeofday(&timestamp);

	if (!test_bit(FRAME_DUMP_FILE_OPEN, &intf->frame_dump_flags))
		return;

	if (skb_queue_len(&intf->frame_dump_skbqueue) > 20) {
		DEBUG(rt2x00dev, "txrx dump queue length exceeded.\n");
		return;
	}

	skbcopy = alloc_skb(sizeof(*dump_hdr) + desc->desc_len + skb->len,
			    GFP_ATOMIC);
	if (!skbcopy) {
		DEBUG(rt2x00dev, "Failed to copy skb for dump.\n");
		return;
	}

	dump_hdr = (struct rt2x00dump_hdr *)skb_put(skbcopy, sizeof(*dump_hdr));
	dump_hdr->version = cpu_to_le32(DUMP_HEADER_VERSION);
	dump_hdr->header_length = cpu_to_le32(sizeof(*dump_hdr));
	dump_hdr->desc_length = cpu_to_le32(desc->desc_len);
	dump_hdr->data_length = cpu_to_le32(skb->len);
	dump_hdr->chip_rt = cpu_to_le16(rt2x00dev->chip.rt);
	dump_hdr->chip_rf = cpu_to_le16(rt2x00dev->chip.rf);
	dump_hdr->chip_rev = cpu_to_le32(rt2x00dev->chip.rev);
	dump_hdr->type = cpu_to_le16(type);
	dump_hdr->queue_index = desc->entry->queue->qid;
	dump_hdr->entry_index = desc->entry->entry_idx;
	dump_hdr->timestamp_sec = cpu_to_le32(timestamp.tv_sec);
	dump_hdr->timestamp_usec = cpu_to_le32(timestamp.tv_usec);

	memcpy(skb_put(skbcopy, desc->desc_len), desc->desc, desc->desc_len);
	memcpy(skb_put(skbcopy, skb->len), skb->data, skb->len);

	skb_queue_tail(&intf->frame_dump_skbqueue, skbcopy);
	wake_up_interruptible(&intf->frame_dump_waitqueue);

	/*
	 * Verify that the file has not been closed while we were working.
	 */
	if (!test_bit(FRAME_DUMP_FILE_OPEN, &intf->frame_dump_flags))
		skb_queue_purge(&intf->frame_dump_skbqueue);
}

static int rt2x00debug_file_open(struct inode *inode, struct file *file)
{
	struct rt2x00debug_intf *intf = inode->i_private;

	file->private_data = inode->i_private;

	if (!try_module_get(intf->debug->owner))
		return -EBUSY;

	return 0;
}

static int rt2x00debug_file_release(struct inode *inode, struct file *file)
{
	struct rt2x00debug_intf *intf = file->private_data;

	module_put(intf->debug->owner);

	return 0;
}

static int rt2x00debug_open_queue_dump(struct inode *inode, struct file *file)
{
	struct rt2x00debug_intf *intf = inode->i_private;
	int retval;

	retval = rt2x00debug_file_open(inode, file);
	if (retval)
		return retval;

	if (test_and_set_bit(FRAME_DUMP_FILE_OPEN, &intf->frame_dump_flags)) {
		rt2x00debug_file_release(inode, file);
		return -EBUSY;
	}

	return 0;
}

static int rt2x00debug_release_queue_dump(struct inode *inode, struct file *file)
{
	struct rt2x00debug_intf *intf = inode->i_private;

	skb_queue_purge(&intf->frame_dump_skbqueue);

	clear_bit(FRAME_DUMP_FILE_OPEN, &intf->frame_dump_flags);

	return rt2x00debug_file_release(inode, file);
}

static ssize_t rt2x00debug_read_queue_dump(struct file *file,
					   char __user *buf,
					   size_t length,
					   loff_t *offset)
{
	struct rt2x00debug_intf *intf = file->private_data;
	struct sk_buff *skb;
	size_t status;
	int retval;

	if (file->f_flags & O_NONBLOCK)
		return -EAGAIN;

	retval =
	    wait_event_interruptible(intf->frame_dump_waitqueue,
				     (skb =
				     skb_dequeue(&intf->frame_dump_skbqueue)));
	if (retval)
		return retval;

	status = min((size_t)skb->len, length);
	if (copy_to_user(buf, skb->data, status)) {
		status = -EFAULT;
		goto exit;
	}

	*offset += status;

exit:
	kfree_skb(skb);

	return status;
}

static unsigned int rt2x00debug_poll_queue_dump(struct file *file,
						poll_table *wait)
{
	struct rt2x00debug_intf *intf = file->private_data;

	poll_wait(file, &intf->frame_dump_waitqueue, wait);

	if (!skb_queue_empty(&intf->frame_dump_skbqueue))
		return POLLOUT | POLLWRNORM;

	return 0;
}

static const struct file_operations rt2x00debug_fop_queue_dump = {
	.owner		= THIS_MODULE,
	.read		= rt2x00debug_read_queue_dump,
	.poll		= rt2x00debug_poll_queue_dump,
	.open		= rt2x00debug_open_queue_dump,
	.release	= rt2x00debug_release_queue_dump,
};

static ssize_t rt2x00debug_read_queue_stats(struct file *file,
					    char __user *buf,
					    size_t length,
					    loff_t *offset)
{
	struct rt2x00debug_intf *intf = file->private_data;
	struct data_queue *queue;
	unsigned long irqflags;
	unsigned int lines = 1 + intf->rt2x00dev->data_queues;
	size_t size;
	char *data;
	char *temp;

	if (*offset)
		return 0;

	data = kzalloc(lines * MAX_LINE_LENGTH, GFP_KERNEL);
	if (!data)
		return -ENOMEM;

	temp = data +
	    sprintf(data, "qid\tcount\tlimit\tlength\tindex\tdone\tcrypto\n");

	queue_for_each(intf->rt2x00dev, queue) {
		spin_lock_irqsave(&queue->lock, irqflags);

		temp += sprintf(temp, "%d\t%d\t%d\t%d\t%d\t%d\t%d\n", queue->qid,
				queue->count, queue->limit, queue->length,
				queue->index[Q_INDEX],
				queue->index[Q_INDEX_DONE],
				queue->index[Q_INDEX_CRYPTO]);

		spin_unlock_irqrestore(&queue->lock, irqflags);
	}

	size = strlen(data);
	size = min(size, length);

	if (copy_to_user(buf, data, size)) {
		kfree(data);
		return -EFAULT;
	}

	kfree(data);

	*offset += size;
	return size;
}

static const struct file_operations rt2x00debug_fop_queue_stats = {
	.owner		= THIS_MODULE,
	.read		= rt2x00debug_read_queue_stats,
	.open		= rt2x00debug_file_open,
	.release	= rt2x00debug_file_release,
};

#ifdef CONFIG_RT2X00_LIB_CRYPTO
static ssize_t rt2x00debug_read_crypto_stats(struct file *file,
					     char __user *buf,
					     size_t length,
					     loff_t *offset)
{
	struct rt2x00debug_intf *intf = file->private_data;
	char *name[] = { "WEP64", "WEP128", "TKIP", "AES" };
	char *data;
	char *temp;
	size_t size;
	unsigned int i;

	if (*offset)
		return 0;

	data = kzalloc((1 + CIPHER_MAX) * MAX_LINE_LENGTH, GFP_KERNEL);
	if (!data)
		return -ENOMEM;

	temp = data;
	temp += sprintf(data, "cipher\tsuccess\ticv err\tmic err\tkey err\n");

	for (i = 0; i < CIPHER_MAX; i++) {
		temp += sprintf(temp, "%s\t%lu\t%lu\t%lu\t%lu\n", name[i],
				intf->crypto_stats[i].success,
				intf->crypto_stats[i].icv_error,
				intf->crypto_stats[i].mic_error,
				intf->crypto_stats[i].key_error);
	}

	size = strlen(data);
	size = min(size, length);

	if (copy_to_user(buf, data, size)) {
		kfree(data);
		return -EFAULT;
	}

	kfree(data);

	*offset += size;
	return size;
}

static const struct file_operations rt2x00debug_fop_crypto_stats = {
	.owner		= THIS_MODULE,
	.read		= rt2x00debug_read_crypto_stats,
	.open		= rt2x00debug_file_open,
	.release	= rt2x00debug_file_release,
};
#endif

#define RT2X00DEBUGFS_OPS_READ(__name, __format, __type)	\
static ssize_t rt2x00debug_read_##__name(struct file *file,	\
					 char __user *buf,	\
					 size_t length,		\
					 loff_t *offset)	\
{								\
	struct rt2x00debug_intf *intf = file->private_data;	\
	const struct rt2x00debug *debug = intf->debug;		\
	char line[16];						\
	size_t size;						\
	unsigned int index = intf->offset_##__name;		\
	__type value;						\
								\
	if (*offset)						\
		return 0;					\
								\
	if (index >= debug->__name.word_count)			\
		return -EINVAL;					\
								\
	index += (debug->__name.word_base /			\
		  debug->__name.word_size);			\
								\
	if (debug->__name.flags & RT2X00DEBUGFS_OFFSET)		\
		index *= debug->__name.word_size;		\
								\
	debug->__name.read(intf->rt2x00dev, index, &value);	\
								\
	size = sprintf(line, __format, value);			\
								\
	if (copy_to_user(buf, line, size))			\
		return -EFAULT;					\
								\
	*offset += size;					\
	return size;						\
}

#define RT2X00DEBUGFS_OPS_WRITE(__name, __type)			\
static ssize_t rt2x00debug_write_##__name(struct file *file,	\
					  const char __user *buf,\
					  size_t length,	\
					  loff_t *offset)	\
{								\
	struct rt2x00debug_intf *intf = file->private_data;	\
	const struct rt2x00debug *debug = intf->debug;		\
	char line[16];						\
	size_t size;						\
	unsigned int index = intf->offset_##__name;		\
	__type value;						\
								\
	if (*offset)						\
		return 0;					\
								\
	if (index >= debug->__name.word_count)			\
		return -EINVAL;					\
								\
	if (copy_from_user(line, buf, length))			\
		return -EFAULT;					\
								\
	size = strlen(line);					\
	value = simple_strtoul(line, NULL, 0);			\
								\
	index += (debug->__name.word_base /			\
		  debug->__name.word_size);			\
								\
	if (debug->__name.flags & RT2X00DEBUGFS_OFFSET)		\
		index *= debug->__name.word_size;		\
								\
	debug->__name.write(intf->rt2x00dev, index, value);	\
								\
	*offset += size;					\
	return size;						\
}

#define RT2X00DEBUGFS_OPS(__name, __format, __type)		\
RT2X00DEBUGFS_OPS_READ(__name, __format, __type);		\
RT2X00DEBUGFS_OPS_WRITE(__name, __type);			\
								\
static const struct file_operations rt2x00debug_fop_##__name = {\
	.owner		= THIS_MODULE,				\
	.read		= rt2x00debug_read_##__name,		\
	.write		= rt2x00debug_write_##__name,		\
	.open		= rt2x00debug_file_open,		\
	.release	= rt2x00debug_file_release,		\
};

RT2X00DEBUGFS_OPS(csr, "0x%.8x\n", u32);
RT2X00DEBUGFS_OPS(eeprom, "0x%.4x\n", u16);
RT2X00DEBUGFS_OPS(bbp, "0x%.2x\n", u8);
RT2X00DEBUGFS_OPS(rf, "0x%.8x\n", u32);

static ssize_t rt2x00debug_read_dev_flags(struct file *file,
					  char __user *buf,
					  size_t length,
					  loff_t *offset)
{
	struct rt2x00debug_intf *intf =	file->private_data;
	char line[16];
	size_t size;

	if (*offset)
		return 0;

	size = sprintf(line, "0x%.8x\n", (unsigned int)intf->rt2x00dev->flags);

	if (copy_to_user(buf, line, size))
		return -EFAULT;

	*offset += size;
	return size;
}

static const struct file_operations rt2x00debug_fop_dev_flags = {
	.owner		= THIS_MODULE,
	.read		= rt2x00debug_read_dev_flags,
	.open		= rt2x00debug_file_open,
	.release	= rt2x00debug_file_release,
};

static struct dentry *rt2x00debug_create_file_driver(const char *name,
						     struct rt2x00debug_intf
						     *intf,
						     struct debugfs_blob_wrapper
						     *blob)
{
	char *data;

	data = kzalloc(3 * MAX_LINE_LENGTH, GFP_KERNEL);
	if (!data)
		return NULL;

	blob->data = data;
	data += sprintf(data, "driver:\t%s\n", intf->rt2x00dev->ops->name);
	data += sprintf(data, "version:\t%s\n", DRV_VERSION);
	data += sprintf(data, "compiled:\t%s %s\n", __DATE__, __TIME__);
	blob->size = strlen(blob->data);

	return debugfs_create_blob(name, S_IRUSR, intf->driver_folder, blob);
}

static struct dentry *rt2x00debug_create_file_chipset(const char *name,
						      struct rt2x00debug_intf
						      *intf,
						      struct
						      debugfs_blob_wrapper
						      *blob)
{
	const struct rt2x00debug *debug = intf->debug;
	char *data;

	data = kzalloc(8 * MAX_LINE_LENGTH, GFP_KERNEL);
	if (!data)
		return NULL;

	blob->data = data;
	data += sprintf(data, "rt chip:\t%04x\n", intf->rt2x00dev->chip.rt);
	data += sprintf(data, "rf chip:\t%04x\n", intf->rt2x00dev->chip.rf);
	data += sprintf(data, "revision:\t%08x\n", intf->rt2x00dev->chip.rev);
	data += sprintf(data, "\n");
	data += sprintf(data, "register\tbase\twords\twordsize\n");
	data += sprintf(data, "csr\t%d\t%d\t%d\n",
			debug->csr.word_base,
			debug->csr.word_count,
			debug->csr.word_size);
	data += sprintf(data, "eeprom\t%d\t%d\t%d\n",
			debug->eeprom.word_base,
			debug->eeprom.word_count,
			debug->eeprom.word_size);
	data += sprintf(data, "bbp\t%d\t%d\t%d\n",
			debug->bbp.word_base,
			debug->bbp.word_count,
			debug->bbp.word_size);
	data += sprintf(data, "rf\t%d\t%d\t%d\n",
			debug->rf.word_base,
			debug->rf.word_count,
			debug->rf.word_size);
	blob->size = strlen(blob->data);

	return debugfs_create_blob(name, S_IRUSR, intf->driver_folder, blob);
}

void rt2x00debug_register(struct rt2x00_dev *rt2x00dev)
{
	const struct rt2x00debug *debug = rt2x00dev->ops->debugfs;
	struct rt2x00debug_intf *intf;

	intf = kzalloc(sizeof(struct rt2x00debug_intf), GFP_KERNEL);
	if (!intf) {
		ERROR(rt2x00dev, "Failed to allocate debug handler.\n");
		return;
	}

	intf->debug = debug;
	intf->rt2x00dev = rt2x00dev;
	rt2x00dev->debugfs_intf = intf;

	intf->driver_folder =
	    debugfs_create_dir(intf->rt2x00dev->ops->name,
			       rt2x00dev->hw->wiphy->debugfsdir);
	if (IS_ERR(intf->driver_folder) || !intf->driver_folder)
		goto exit;

	intf->driver_entry =
	    rt2x00debug_create_file_driver("driver", intf, &intf->driver_blob);
	if (IS_ERR(intf->driver_entry) || !intf->driver_entry)
		goto exit;

	intf->chipset_entry =
	    rt2x00debug_create_file_chipset("chipset",
					    intf, &intf->chipset_blob);
	if (IS_ERR(intf->chipset_entry) || !intf->chipset_entry)
		goto exit;

	intf->dev_flags = debugfs_create_file("dev_flags", S_IRUSR,
					      intf->driver_folder, intf,
					      &rt2x00debug_fop_dev_flags);
	if (IS_ERR(intf->dev_flags) || !intf->dev_flags)
		goto exit;

	intf->register_folder =
	    debugfs_create_dir("register", intf->driver_folder);
	if (IS_ERR(intf->register_folder) || !intf->register_folder)
		goto exit;

#define RT2X00DEBUGFS_CREATE_REGISTER_ENTRY(__intf, __name)	\
({								\
	(__intf)->__name##_off_entry =				\
	    debugfs_create_u32(__stringify(__name) "_offset",	\
			       S_IRUSR | S_IWUSR,		\
			       (__intf)->register_folder,	\
			       &(__intf)->offset_##__name);	\
	if (IS_ERR((__intf)->__name##_off_entry)		\
			|| !(__intf)->__name##_off_entry)	\
		goto exit;					\
								\
	(__intf)->__name##_val_entry =				\
	    debugfs_create_file(__stringify(__name) "_value",	\
				S_IRUSR | S_IWUSR,		\
				(__intf)->register_folder,	\
				(__intf), &rt2x00debug_fop_##__name);\
	if (IS_ERR((__intf)->__name##_val_entry)		\
			|| !(__intf)->__name##_val_entry)	\
		goto exit;					\
})

	RT2X00DEBUGFS_CREATE_REGISTER_ENTRY(intf, csr);
	RT2X00DEBUGFS_CREATE_REGISTER_ENTRY(intf, eeprom);
	RT2X00DEBUGFS_CREATE_REGISTER_ENTRY(intf, bbp);
	RT2X00DEBUGFS_CREATE_REGISTER_ENTRY(intf, rf);

#undef RT2X00DEBUGFS_CREATE_REGISTER_ENTRY

	intf->queue_folder =
	    debugfs_create_dir("queue", intf->driver_folder);
	if (IS_ERR(intf->queue_folder) || !intf->queue_folder)
		goto exit;

	intf->queue_frame_dump_entry =
	    debugfs_create_file("dump", S_IRUSR, intf->queue_folder,
				intf, &rt2x00debug_fop_queue_dump);
	if (IS_ERR(intf->queue_frame_dump_entry)
		|| !intf->queue_frame_dump_entry)
		goto exit;

	skb_queue_head_init(&intf->frame_dump_skbqueue);
	init_waitqueue_head(&intf->frame_dump_waitqueue);

	intf->queue_stats_entry =
	    debugfs_create_file("queue", S_IRUSR, intf->queue_folder,
				intf, &rt2x00debug_fop_queue_stats);

#ifdef CONFIG_RT2X00_LIB_CRYPTO
	if (test_bit(CONFIG_SUPPORT_HW_CRYPTO, &rt2x00dev->flags))
		intf->crypto_stats_entry =
		    debugfs_create_file("crypto", S_IRUGO, intf->queue_folder,
					intf, &rt2x00debug_fop_crypto_stats);
#endif

	return;

exit:
	rt2x00debug_deregister(rt2x00dev);
	ERROR(rt2x00dev, "Failed to register debug handler.\n");

	return;
}

void rt2x00debug_deregister(struct rt2x00_dev *rt2x00dev)
{
	struct rt2x00debug_intf *intf = rt2x00dev->debugfs_intf;

	if (unlikely(!intf))
		return;

	skb_queue_purge(&intf->frame_dump_skbqueue);

#ifdef CONFIG_RT2X00_LIB_CRYPTO
	debugfs_remove(intf->crypto_stats_entry);
#endif
	debugfs_remove(intf->queue_stats_entry);
	debugfs_remove(intf->queue_frame_dump_entry);
	debugfs_remove(intf->queue_folder);
	debugfs_remove(intf->rf_val_entry);
	debugfs_remove(intf->rf_off_entry);
	debugfs_remove(intf->bbp_val_entry);
	debugfs_remove(intf->bbp_off_entry);
	debugfs_remove(intf->eeprom_val_entry);
	debugfs_remove(intf->eeprom_off_entry);
	debugfs_remove(intf->csr_val_entry);
	debugfs_remove(intf->csr_off_entry);
	debugfs_remove(intf->register_folder);
	debugfs_remove(intf->dev_flags);
	debugfs_remove(intf->chipset_entry);
	debugfs_remove(intf->driver_entry);
	debugfs_remove(intf->driver_folder);
	kfree(intf->chipset_blob.data);
	kfree(intf->driver_blob.data);
	kfree(intf);

	rt2x00dev->debugfs_intf = NULL;
}


text: <input type="checkbox" id="select_all_objects_checkbox" onclick="toggle_select_all_objects();" arial-label="Checkbox for Selection of All Items"/>

redpajama_set_name: RedPajamaGithub


text:
namespace Tangram {

class MockPlatform : public Platform {

public:
    MockPlatform();

    void shutdown() override {}
    void requestRender() const override;
    std::vector<FontSourceHandle> systemFontFallbacksHandle() const override;
    bool startUrlRequestImpl(const Url& _url, const UrlRequestHandle _request, UrlRequestId& _id) override;
    void cancelUrlRequestImpl(const UrlRequestId _id) override;

    // Put content at a URL to be retrieved by startUrlRequest.
    void putMockUrlContents(Url url, std::string contents);
    void putMockUrlContents(Url url, std::vector<char> contents);

    // Get the contents of a local file (not mock URL contents).
    static std::vector<char> getBytesFromFile(const char* path);

    Url resolveUrl(Url _url) { return m_baseUrl.resolve(_url); }
private:

    std::unordered_map<Url, std::vector<char>> m_files;
    Url m_baseUrl;
};

} // namespace Tangram


text:
"""Classes::
  EvaluateFit -- The EvaluateFit class is a collection of
    functions that allows you evaluate a fourier representation
    of a function created by FitData (fit.json) at arbitrary points.

"""

import numpy as np
from json import load

from dftintegrate import customserializer as cs
from dftintegrate.fourier import fitdata

class EvaluateFit(object):
    """
    Evaluate a fourier representation of a 3D function created by the
    FitData object.

    Solve A x = b where A is a matrix and x and b are column vectors.

    Variables::
      name -- Path to directory with data to work on.

      bandnum -- Number of bands to fit.

      data -- Data to fit represented in data.json.

      kgrid -- A list of lists. Each inner list is a triplet that
        represents a k-point. The outer list is the collection of
        the triplets or k-points and therefore represents the k-kgrid.
        This is set to the points you want to evaluate the fit at in
        "evaluate."

      series -- Matrix representation of the series. "A" in the equation
        to solve.

      coeffs -- Fourier Coefficients in the Fourier series. "x" in the
        equation to solve. A dictionary, the key is the band number and
        the value is the list of coefficients for that band.

      recips -- Reciprocal lattice vectors in the Fourier sum.

    Funtions::
      __evaluatefit -- Generates "A" by calling FitData.gen_series
        and sets "x" to the coeffs for a particular band. Solves for "b"
        by finding the dot product of "A" and "x".

      evaluate -- Sets kgrid to points you wish to evaluate fit at.
        Recursively calls __evaluatefit according to specified number of
        bands. Returns dictionary of results.

    """

    def __init__(self, name_of_directory, bandnum='all'):
        """
        Arguments::
          name_of_directory -- path to directory that contains the
            output from readdata.py

        Keyword Arguments::
          bandnum -- Number of bands to fit. Default is to fit all bands
            in data.json.
        """
        self.name = name_of_directory+'/'
        self.bandnum = bandnum
        with open(self.name+'fit.json', mode='r',
                  encoding='utf-8') as inf:
            self.data = load(inf, object_hook=cs.fromjson)
        self.recips = self.data['reciprocals']
        self.coeffs = self.data['coefficients']

    def _evaluatefit(self):
        """
        Use A x = b to solve for b. First generate A with fitdata's
        gen_series. x is the coefficients that correspond to the
        band we are currently calculating (num).
        """
        fitdata.FitData.gen_series(self)
        A = self.series
        x = self.coeffs[self.num]
        return(np.dot(A, x))

    def evaluate(self, points):
        fiteval = {}
        self.kgrid = points
        if self.bandnum == 'all':
            for num in range(1, len(self.coeffs.keys())+1):
                self.num = num
                fiteval[num] = self._evaluatefit()
        else:
            for num in range(1, self.bandnum+1):
                self.num = str(num)
                fiteval[num] = self._evaluatefit()
        return fiteval


text:
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}

-- | Functions to create references from simple functions
-- and members of the lens library.
module Control.Reference.Generators where

import Control.Reference.Representation
import Control.Reference.Types

import Control.Instances.Morph
import qualified Data.Traversable as Trav
import Control.Applicative
import Control.Monad
import Control.Monad.Identity
import Control.Monad.Writer
import Data.Generics.Uniplate.Operations

-- | Generates a traversal for any 'Trav.Traversable' 'Functor'
traversal :: (Trav.Traversable t) => Traversal (t a) (t b) a b
traversal = reference (morph . execWriter . Trav.mapM (tell . (:[])))
                      (Trav.mapM . const . return)
                      Trav.mapM

-- | Generate a lens from a pair of inverse functions
iso :: (a -> b) -> (b -> a) -> Simple Iso a b
iso f g = bireference (return . f) (\b _ -> return . g $ b) (\trf a -> trf (f a) >>= return . g  )
                      (return . g) (\a _ -> return . f $ a) (\trf b -> trf (g b) >>= return . f  )

iso' :: (a -> b) -> (a' -> b') -> (b -> a) -> (b' -> a') -> Iso a a' b b'
iso' f f' g g'
  = bireference (return . f) (\b _ -> return . g' $ b) (\trf a -> trf (f a) >>= return . g'  )
                (return . g) (\a _ -> return . f' $ a) (\trf b -> trf (g b) >>= return . f'  )

-- | Generates a lens from a getter and a setter
lens :: (s -> a) -> (b -> s -> t) -> Lens s t a b
lens get set = reference (return . get)
                         (\b -> return . set b )
                         (\f a -> f (get a) >>= \b -> return $ set b a)

-- | Creates a polymorphic partial lense
--
-- @Either t a@ is used instead of @Maybe a@ to permit the types of 's' and 't' to differ.
partial :: (s -> Either t (a, b -> t)) -> Partial s t a b
partial access
  = reference
      (either (const $ morph Nothing) (return . fst) . access)
      (\b -> return . either id (($b) . snd) . access)
      (\f -> either return (\(a,set) -> f a >>= return . set) . access)

-- | Creates a polymorphic partial lens that can be turned to give a total lens
prism :: (a -> s) -> (b -> t) -> (s -> Either t a) -> (t -> Maybe b) -> Prism s t a b
prism back back' access access'
  = bireference (either (const $ morph Nothing) return . access)
                (\b -> return . either id (const $ (back' b)) . access)
                (\f -> either return (f >=> return . back') . access)
                (return . back)
                (\t _ -> morph $ access' t)
                (\f a -> f (back a) >>= morph . access')

-- | Creates a monomorphic partial lens that can be turned to give a total lens
simplePrism :: (a -> s) -> (s -> Maybe a) -> Prism s s a a
simplePrism back access = prism back back (\s -> maybe (Left s) Right (access s)) access

-- | Creates a simple partial lens
simplePartial :: (s -> Maybe (a, a -> s)) -> Partial s s a a
simplePartial access
  = partial (\s -> maybe (Left s) Right (access s))

-- | Clones a lens from "Control.Lens"
fromLens :: (forall f . Functor f => (a -> f b) -> s -> f t) -> Lens s t a b
fromLens l = reference (\s -> return (getConst $ l Const s))
                       (\b -> return . (runIdentity . l (\_ -> Identity b)))
                       l

-- | Clones a traversal from "Control.Lens"
fromTraversal :: (forall f . Applicative f => (a -> f b) -> s -> f t) -> Traversal s t a b
fromTraversal l = reference (morph . execWriter . l (\a -> tell [a] >> return undefined))
                            (\b -> return . (runIdentity . l (\_ -> Identity b)))
                            l

-- | References all the elements accessed by uniplate
uniplateRef :: Uniplate a => Simple Traversal a a
uniplateRef = reference (morph . universe)
                        (\b -> return . (transform (const b)))
                        transformM

-- | References all the elements accessed by biplate
biplateRef :: Biplate a b => Simple Traversal a b
biplateRef = reference (morph . universeBi)
                       (\b -> return . (transformBi (const b)))
                       transformBiM

-- | Filters the traversed elements with a given predicate.
-- Has specific versions for traversals and partial lenses.
filtered :: (a -> Bool) -> Simple RefPlus a a
filtered p = reference (\s -> if p s then return s else mzero)
                       (\a s -> if p s then return a else return s)
                       (\f s -> if p s then f s else return s)


text:
#include "hal.h"
#include "hal_types.h"
#include "ble_status.h"
#include "bluenrg_aci.h"
#include "bluenrg_utils.h"
#include "hci.h"
#include "hci_le.h"
#include "osal.h"
#include "string.h"
#include "stm32_bluenrg_ble.h"

uint8_t getBlueNRGVersion(uint8_t *hwVersion, uint16_t *fwVersion)
{
  uint8_t status;
  uint8_t hci_version, lmp_pal_version;
  uint16_t hci_revision, manufacturer_name, lmp_pal_subversion;

  status = hci_le_read_local_version(&hci_version, &hci_revision, &lmp_pal_version,
				     &manufacturer_name, &lmp_pal_subversion);

  if (status == BLE_STATUS_SUCCESS) {
    *hwVersion = hci_revision >> 8;
    *fwVersion = (hci_revision & 0xFF) << 8;              // Major Version Number
    *fwVersion |= ((lmp_pal_subversion >> 4) & 0xF) << 4; // Minor Version Number
    *fwVersion |= lmp_pal_subversion & 0xF;               // Patch Version Number
  }

  HCI_Process(); // To receive the BlueNRG EVT

  return status;
}


text:
package nw.commons;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class StopWatchTest {

	@Test
	public void testElapsedTime() {
		StopWatch sw = new StopWatch();
		Date now = new Date();

		sleep(1);
		assertThat(new BigDecimal(sw.elapsedTime()), closeTo(new BigDecimal(new Date().getTime() - now.getTime()), new BigDecimal("100")));
	}

//	@Test
//	public void testCurrentElapsedTime() {
//		fail("Not yet implemented");
//	}

	@Test
	public void testZero() {
		StopWatch sw = new StopWatch();
		sleep(1);
		sw.zero();
		assertThat(1L, greaterThan(sw.elapsedTime()));
	}

//	@Test
//	public void testStart() {
//		fail("Not yet implemented");
//	}
//
//	@Test
//	public void testStop() {
//		fail("Not yet implemented");
//	}
//
//	@Test
//	public void testMark() {
//		fail("Not yet implemented");
//	}
//
//	@Test
//	public void testElapsedTimeToMessage() {
//		fail("Not yet implemented");
//	}
//
//	@Test
//	public void testCurrentElapsedTimeToMessage() {
//		fail("Not yet implemented");
//	}

	private void sleep(long timeout){
		try {
			TimeUnit.SECONDS.sleep(timeout);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


text:
#include <af/features.h>
#include <Array.hpp>

using af::features;

namespace cpu
{

template<typename T, typename convAccT>
unsigned sift(Array<float>& x, Array<float>& y, Array<float>& score,
              Array<float>& ori, Array<float>& size, Array<float>& desc,
              const Array<T>& in, const unsigned n_layers,
              const float contrast_thr, const float edge_thr,
              const float init_sigma, const bool double_input,
              const float img_scale, const float feature_ratio);

}


text:
package org.eclipse.jgit.treewalk;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Comparator;

import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;

/**
 * Walks a working directory tree as part of a {@link TreeWalk}.
 *

 * Most applications will want to use the standard implementation of this
 * iterator, {@link FileTreeIterator}, as that does all IO through the standard
 * java.io package. Plugins for a Java based IDE may however wish
 * to create their own implementations of this class to allow traversal of the
 * IDE's project space, as well as benefit from any caching the IDE may have.
 *
 * @see FileTreeIterator
 */
public abstract class WorkingTreeIterator extends AbstractTreeIterator {
	/** An empty entry array, suitable for {@link #init(Entry[])}. */
	protected static final Entry[] EOF = {};

	/** Size we perform file IO in if we have to read and hash a file. */
	private static final int BUFFER_SIZE = 2048;

	/** The {@link #idBuffer()} for the current entry. */
	private byte[] contentId;

	/** Index within {@link #entries} that {@link #contentId} came from. */
	private int contentIdFromPtr;

	/** Buffer used to perform {@link #contentId} computations. */
	private byte[] contentReadBuffer;

	/** Digest computer for {@link #contentId} computations. */
	private MessageDigest contentDigest;

	/** File name character encoder. */
	private final CharsetEncoder nameEncoder;

	/** List of entries obtained from the subclass. */
	private Entry[] entries;

	/** Total number of entries in {@link #entries} that are valid. */
	private int entryCnt;

	/** Current position within {@link #entries}. */
	private int ptr;

	/** Create a new iterator with no parent. */
	protected WorkingTreeIterator() {
		super();
		nameEncoder = Constants.CHARSET.newEncoder();
	}

	/**
	 * Create a new iterator with no parent and a prefix.
	 *

	 * The prefix path supplied is inserted in front of all paths generated by
	 * this iterator. It is intended to be used when an iterator is being
	 * created for a subsection of an overall repository and needs to be
	 * combined with other iterators that are created to run over the entire
	 * repository namespace.
	 *
	 * @param prefix
	 *            position of this iterator in the repository tree. The value
	 *            may be null or the empty string to indicate the prefix is the
	 *            root of the repository. A trailing slash ('/') is
	 *            automatically appended if the prefix does not end in '/'.
	 */
	protected WorkingTreeIterator(final String prefix) {
		super(prefix);
		nameEncoder = Constants.CHARSET.newEncoder();
	}

	/**
	 * Create an iterator for a subtree of an existing iterator.
	 *
	 * @param p
	 *            parent tree iterator.
	 */
	protected WorkingTreeIterator(final WorkingTreeIterator p) {
		super(p);
		nameEncoder = p.nameEncoder;
	}

	@Override
	public byte[] idBuffer() {
		if (contentIdFromPtr == ptr)
			return contentId;
		switch (mode & FileMode.TYPE_MASK) {
		case FileMode.TYPE_FILE:
			contentIdFromPtr = ptr;
			return contentId = idBufferBlob(entries[ptr]);
		case FileMode.TYPE_SYMLINK:
			// Java does not support symbolic links, so we should not
			// have reached this particular part of the walk code.
			//
			return zeroid;
		case FileMode.TYPE_GITLINK:
			// TODO: Support obtaining current HEAD SHA-1 from nested repository
			//
			return zeroid;
		}
		return zeroid;
	}

	private void initializeDigest() {
		if (contentDigest != null)
			return;

		if (parent == null) {
			contentReadBuffer = new byte[BUFFER_SIZE];
			contentDigest = Constants.newMessageDigest();
		} else {
			final WorkingTreeIterator p = (WorkingTreeIterator) parent;
			p.initializeDigest();
			contentReadBuffer = p.contentReadBuffer;
			contentDigest = p.contentDigest;
		}
	}

	private static final byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9' };

	private static final byte[] hblob = Constants
			.encodedTypeString(Constants.OBJ_BLOB);

	private byte[] idBufferBlob(final Entry e) {
		try {
			final InputStream is = e.openInputStream();
			if (is == null)
				return zeroid;
			try {
				initializeDigest();

				contentDigest.reset();
				contentDigest.update(hblob);
				contentDigest.update((byte) ' ');

				final long blobLength = e.getLength();
				long sz = blobLength;
				if (sz == 0) {
					contentDigest.update((byte) '0');
				} else {
					final int bufn = contentReadBuffer.length;
					int p = bufn;
					do {
						contentReadBuffer[--p] = digits[(int) (sz % 10)];
						sz /= 10;
					} while (sz > 0);
					contentDigest.update(contentReadBuffer, p, bufn - p);
				}
				contentDigest.update((byte) 0);

				for (;;) {
					final int r = is.read(contentReadBuffer);
					if (r <= 0)
						break;
					contentDigest.update(contentReadBuffer, 0, r);
					sz += r;
				}
				if (sz != blobLength)
					return zeroid;
				return contentDigest.digest();
			} finally {
				try {
					is.close();
				} catch (IOException err2) {
					// Suppress any error related to closing an input
					// stream. We don't care, we should not have any
					// outstanding data to flush or anything like that.
				}
			}
		} catch (IOException err) {
			// Can't read the file? Don't report the failure either.
			//
			return zeroid;
		}
	}

	@Override
	public int idOffset() {
		return 0;
	}

	@Override
	public boolean first() {
		return ptr == 0;
	}

	@Override
	public boolean eof() {
		return ptr == entryCnt;
	}

	@Override
	public void next(final int delta) throws CorruptObjectException {
		ptr += delta;
		if (!eof())
			parseEntry();
	}

	@Override
	public void back(final int delta) throws CorruptObjectException {
		ptr -= delta;
		parseEntry();
	}

	private void parseEntry() {
		final Entry e = entries[ptr];
		mode = e.getMode().getBits();

		final int nameLen = e.encodedNameLen;
		ensurePathCapacity(pathOffset + nameLen, pathOffset);
		System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
		pathLen = pathOffset + nameLen;
	}

	/**
	 * Get the byte length of this entry.
	 *
	 * @return size of this file, in bytes.
	 */
	public long getEntryLength() {
		return current().getLength();
	}

	/**
	 * Get the last modified time of this entry.
	 *
	 * @return last modified time of this file, in milliseconds since the epoch
	 *         (Jan 1, 1970 UTC).
	 */
	public long getEntryLastModified() {
		return current().getLastModified();
	}

	private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
		public int compare(final Entry o1, final Entry o2) {
			final byte[] a = o1.encodedName;
			final byte[] b = o2.encodedName;
			final int aLen = o1.encodedNameLen;
			final int bLen = o2.encodedNameLen;
			int cPos;

			for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
				final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
				if (cmp != 0)
					return cmp;
			}

			if (cPos < aLen)
				return (a[cPos] & 0xff) - lastPathChar(o2);
			if (cPos < bLen)
				return lastPathChar(o1) - (b[cPos] & 0xff);
			return lastPathChar(o1) - lastPathChar(o2);
		}
	};

	static int lastPathChar(final Entry e) {
		return e.getMode() == FileMode.TREE ? '/' : '\0';
	}

	/**
	 * Constructor helper.
	 *
	 * @param list
	 *            files in the subtree of the work tree this iterator operates
	 *            on
	 */
	protected void init(final Entry[] list) {
		// Filter out nulls, . and .. as these are not valid tree entries,
		// also cache the encoded forms of the path names for efficient use
		// later on during sorting and iteration.
		//
		entries = list;
		int i, o;

		for (i = 0, o = 0; i < entries.length; i++) {
			final Entry e = entries[i];
			if (e == null)
				continue;
			final String name = e.getName();
			if (".".equals(name) || "..".equals(name))
				continue;
			if (".git".equals(name))
				continue;
			if (i != o)
				entries[o] = e;
			e.encodeName(nameEncoder);
			o++;
		}
		entryCnt = o;
		Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);

		contentIdFromPtr = -1;
		ptr = 0;
		if (!eof())
			parseEntry();
	}

	/**
	 * Obtain the current entry from this iterator.
	 *
	 * @return the currently selected entry.
	 */
	protected Entry current() {
		return entries[ptr];
	}

	/** A single entry within a working directory tree. */
	protected static abstract class Entry {
		byte[] encodedName;

		int encodedNameLen;

		void encodeName(final CharsetEncoder enc) {
			final ByteBuffer b;
			try {
				b = enc.encode(CharBuffer.wrap(getName()));
			} catch (CharacterCodingException e) {
				// This should so never happen.
				throw new RuntimeException("Unencodeable file: " + getName());
			}

			encodedNameLen = b.limit();
			if (b.hasArray() && b.arrayOffset() == 0)
				encodedName = b.array();
			else
				b.get(encodedName = new byte[encodedNameLen]);
		}

		public String toString() {
			return getMode().toString() + " " + getName();
		}

		/**
		 * Get the type of this entry.
		 *

		 * Note: Efficient implementation required.
		 *

		 * The implementation of this method must be efficient. If a subclass
		 * needs to compute the value they should cache the reference within an
		 * instance member instead.
		 *
		 * @return a file mode constant from {@link FileMode}.
		 */
		public abstract FileMode getMode();

		/**
		 * Get the byte length of this entry.
		 *

		 * Note: Efficient implementation required.
		 *

		 * The implementation of this method must be efficient. If a subclass
		 * needs to compute the value they should cache the reference within an
		 * instance member instead.
		 *
		 * @return size of this file, in bytes.
		 */
		public abstract long getLength();

		/**
		 * Get the last modified time of this entry.
		 *

		 * Note: Efficient implementation required.
		 *

		 * The implementation of this method must be efficient. If a subclass
		 * needs to compute the value they should cache the reference within an
		 * instance member instead.
		 *
		 * @return time since the epoch (in ms) of the last change.
		 */
		public abstract long getLastModified();

		/**
		 * Get the name of this entry within its directory.
		 *

		 * Efficient implementations are not required. The caller will obtain
		 * the name only once and cache it once obtained.
		 *
		 * @return name of the entry.
		 */
		public abstract String getName();

		/**
		 * Obtain an input stream to read the file content.
		 *

		 * Efficient implementations are not required. The caller will usually
		 * obtain the stream only once per entry, if at all.
		 *

		 * The input stream should not use buffering if the implementation can
		 * avoid it. The caller will buffer as necessary to perform efficient
		 * block IO operations.
		 *

		 * The caller will close the stream once complete.
		 *
		 * @return a stream to read from the file.
		 * @throws IOException
		 *             the file could not be opened for reading.
		 */
		public abstract InputStream openInputStream() throws IOException;
	}
}


text:
.image-blocks-table td.has-error {
    border: 2px solid red !important;
}

.image-blocks-table td.has-image {
    padding: 15px !important;
}

.image-blocks-table td {
    border: 1px solid rgba(0, 0, 0, 0.05) !important;
    padding: 5px !important;
}

.image-blocks-table td {
    border: 1px solid rgba(0, 0, 0, 0.05) !important;
    padding: 5px !important;
}

.padding-5 {
    padding: 5px !important;
}


text:
var searchData=
[
  ['database_5fhandler',['database_handler',['../namespacedatabase__handler.html',1,'']]]
];


text:
layout: docs
title: Update Strategies
category: cluster_management
sub_category: setting_up
weight: 7
---

# Update Strategies

The overarching goal of CoreOS is to secure the internet's backend infrastructure. We believe that [automatically updating]({{site.url}}/using-coreos/updates) the operating system is one of the best tools to achieve this goal.

We realize that each CoreOS cluster has a unique tolerance for risk and the operational needs of your applications are complex. In order to meet everyone's needs, there are four update strategies that we have developed based on feedback during our alpha period.

It's important to note that updates are always downloaded to the passive partition when they become available. A reboot is the last step of the update, where the active and passive partitions are swapped. These strategies control how that reboot occurs:

| Strategy           | Description |
|--------------------|-------------|
| `best-effort`        | Default. If etcd is running, `etcd-lock`, otherwise simply `reboot`. |
| `etcd-lock`          | Reboot after first taking a distributed lock in etcd. |
| `reboot`             | Reboot immediately after an update is applied. |
| `off`                | Do not reboot after updates are applied. |

## Strategy Options

The update strategy is defined in [cloud-config]({{site.url}}/docs/cluster-management/setup/cloudinit-cloud-config/#coreos):

```yaml
#cloud-config
coreos:
  update:
    reboot-strategy: best-effort
```

### Best Effort

The default setting is for CoreOS to make a `best-effort` to determine if the machine is part of a cluster. Currently this logic is very simple: if etcd has started, assume that the machine is part of a cluster and use the `etcd-lock` strategy.

Otherwise, use the `reboot` strategy.

### etcd-Lock

The `etcd-lock` strategy mandates that each machine acquire and hold a reboot lock before it is allowed to reboot. The main goal behind this strategy is to allow for an update to be applied to a cluster quickly, without losing the quorum membership in etcd or rapidly reducing capacity for the services running on the cluster. The reboot lock is held until the machine releases it after a successful update.

The number of machines allowed to reboot simultaneously is configurable via a command line utility:

```sh
$ locksmithctl set-max 4
Old: 1
New: 4
```

This setting is stored in etcd so it won't have to be configured for subsequent machines.

To view the number of available slots and find out which machines in the cluster are holding locks, run:

```sh
$ locksmithctl status
Available: 0
Max: 1

MACHINE ID
69d27b356a94476da859461d3a3bc6fd
```

If needed, you can manually clear a lock by providing the machine ID:

```sh
locksmithctl unlock 69d27b356a94476da859461d3a3bc6fd
```

### Reboot Immediately

The `reboot` strategy works exactly like it sounds: the machine is rebooted as soon as the update has been installed to the passive partition. If the applications running on your cluster are highly resilient, this strategy was made for you.

### Off

The `off` strategy is also straightforward. The update will be installed onto the passive partion and await a reboot command to complete the update. We don't recommend this strategy unless you reboot frequently as part of your normal operations workflow.

## Updating PXE/iPXE Machines

PXE/iPXE machines download a new copy of CoreOS every time they are started thus are dependent on the version of CoreOS they are served. If you don't automatically load new CoreOS images into your PXE/iPXE server, your machines will never have new features or security updates.

An easy solution to this problem is to use iPXE and reference images [directly from the CoreOS storage site]({{site.url}}/docs/running-coreos/bare-metal/booting-with-ipxe/#setting-up-the-boot-script). The `alpha` URL is automatically pointed to the new version of CoreOS as it is released.


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.KeyVault.Models;
using System.Globalization;
using System.Management.Automation;
using KeyVaultProperties = Microsoft.Azure.Commands.KeyVault.Properties;

namespace Microsoft.Azure.Commands.KeyVault
{
    [Cmdlet(VerbsCommon.Remove, "AzureKeyVaultSecret",
        SupportsShouldProcess = true,
         ConfirmImpact = ConfirmImpact.High,
        HelpUri = Constants.KeyVaultHelpUri)]
    [OutputType(typeof(DeletedSecret))]
    public class RemoveAzureKeyVaultSecret : KeyVaultCmdletBase
    {
        #region Input Parameter Definitions

        /// <summary>
        /// Vault name
        /// </summary>
        [Parameter(Mandatory = true,
            Position = 0,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Vault name. Cmdlet constructs the FQDN of a vault based on the name and currently selected environment.")]
        [ValidateNotNullOrEmpty]
        public string VaultName { get; set; }

        /// <summary>
        /// Secret name
        /// </summary>
        [Parameter(Mandatory = true,
            Position = 1,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "Secret name. Cmdlet constructs the FQDN of a secret from vault name, currently selected environment and secret name.")]
        [ValidateNotNullOrEmpty]
        [Alias(Constants.SecretName)]
        public string Name { get; set; }

        /// <summary>
        /// If present, do not ask for confirmation
        /// </summary>
        [Parameter(Mandatory = false,
            HelpMessage = "Do not ask for confirmation.")]
        public SwitchParameter Force { get; set; }

        [Parameter(Mandatory = false,
            HelpMessage = "Cmdlet does not return an object by default. If this switch is specified, cmdlet returns the secret that was deleted.")]
        public SwitchParameter PassThru { get; set; }

        /// <summary>
        /// If present, operate on the deleted secret entity.
        /// </summary>
        [Parameter(Mandatory = false,
           HelpMessage = "If present, removes the previously deleted secret permanently.")]
        public SwitchParameter InRemovedState { get; set; }

        #endregion

        public override void ExecuteCmdlet()
        {
            if(InRemovedState.IsPresent)
            {
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        KeyVaultProperties.Resources.RemoveDeletedSecretWarning,
                        Name),
                    string.Format(
                        CultureInfo.InvariantCulture,
                        KeyVaultProperties.Resources.RemoveDeletedSecretWhatIfMessage,
                        Name),
                    Name,
                   () => { DataServiceClient.PurgeSecret(VaultName, Name); });
                return;
            }

            DeletedSecret deletedSecret = null;
            ConfirmAction(
                Force.IsPresent,
                string.Format(
                    CultureInfo.InvariantCulture,
                    KeyVaultProperties.Resources.RemoveSecretWarning,
                    Name),
                string.Format(
                    CultureInfo.InvariantCulture,
                    KeyVaultProperties.Resources.RemoveSecretWhatIfMessage,
                    Name),
                Name,
               () => { deletedSecret = DataServiceClient.DeleteSecret(VaultName, Name); });

            if (PassThru)
            {
                WriteObject(deletedSecret);
            }
        }
    }
}


text:
using System;
using System.Drawing;
using System.IO;
using System.Resources;
using System.Windows.Forms;
using System.Reflection;

[assembly: AssemblyCompany("Michael Trenholm-Boyle")]
[assembly: AssemblyCopyright("© 2016 Michael Trenholm-Boyle")]
[assembly: AssemblyTitle("Creates .NET resource files.")]
[assembly: AssemblyProduct(@"Michael Trenholm-Boyle's Ad Hoc .NET Tools Suite")]
[assembly: AssemblyVersion("0.1.*")]

namespace mkres
{
	public class MainClass
	{
		public static void Main(string[] args)
		{
			if((0 == args.Length) || ("/?" == args[0]))
			{
				Console.WriteLine("Creates .NET resource files.\nsyntax: mkres filename.(resources|resX) resources...\nsupported resources:\n\t/icon resName fileName\n\t/image resName fileName\n\t/cursor resName fileName\n\t/string resName \"string\"\n\t/filestring resName fileName\n\t/filebytes resName fileName\n\t/imagelist resName fileName fileName fileName...");
				return;
			}
			IResourceWriter rw;
			switch(Path.GetExtension(args[0]).ToLower())
			{
				case ".resources":
					try
					{
						rw = new ResourceWriter(args[0]);
					}
					catch(Exception e)
					{
						Console.WriteLine(String.Format("error: {0}: {1}", args[0], e.Message));
						return;
					}
					break;
				case ".resx":
					try
					{
						rw = new ResXResourceWriter(args[0]);
					}
					catch(Exception e)
					{
						Console.WriteLine(String.Format("error: {0}: {1}", args[0], e.Message));
						return;
					}
					break;
				default:
					Console.WriteLine(String.Format("error: {0}: unknown filename extension; must be .resources or .resX", args[0]));
					return;
			}
			for(int i = 1; i < args.Length;)
			{
				switch(args[i].ToLower())
				{
					default:
						Console.WriteLine(String.Format("error: {0}: invalid argument; see mkres /? for syntax help", args[i]));
						return;
					case "/icon":
						try
						{
							rw.AddResource(args[i+1], new Icon(args[i + 2]));
						}
						catch(Exception e)
						{
							Console.WriteLine(String.Format("error: {0}: {1}", args[i + 2], e.Message));
							return;
						}
						i += 3;
						break;
					case "/image":
						try
						{
							rw.AddResource(args[i + 1], Image.FromFile(args[i + 2]));
						}
						catch(Exception e)
						{
							Console.WriteLine(String.Format("error: {0}: {1}", args[i + 2], e.Message));
							return;
						}
						i += 3;
						break;
					case "/cursor":
						try
						{
							rw.AddResource(args[i + 1], new Cursor(args[i + 2]));
						}
						catch(Exception e)
						{
							Console.WriteLine(String.Format("error: {0}: {1}", args[i + 2], e.Message));
							return;
						}
						i += 3;
						break;
					case "/string":
						rw.AddResource(args[i + 1], args[i + 2]);
						i += 3;
						break;
					case "/filestring":
						try
						{
							StreamReader sr = new StreamReader(args[i + 2]);
							rw.AddResource(args[i + 1], sr.ReadToEnd());
							sr.Close();
						}
						catch(Exception e)
						{
							Console.WriteLine(String.Format("error: {0}: {1}", args[i + 2], e.Message));
							return;
						}
						i += 3;
						break;
					case "/filebytes":
						try
						{
							FileStream fs = new FileStream(args[i + 2], FileMode.Open);
							byte[] arr = new byte[fs.Length];
							fs.Read(arr, 0, arr.Length);
							rw.AddResource(args[i + 1], arr);
							fs.Close();
						}
						catch(Exception e)
						{
							Console.WriteLine(String.Format("error: {0}: {1}", args[i + 2], e.Message));
							return;
						}
						i += 3;
						break;
					case "/imagelist":
						using(ImageList il = new ImageList())
						{
							il.ColorDepth = ColorDepth.Depth32Bit;
							string resname = args[i + 1];
							bool haveSetSize = false;
							try
							{
								for(i+=2; (i < args.Length) && ('/' != args[i][0]); i++)
								{
									Image img;
									Icon ico;
									switch(Path.GetExtension(args[i]).ToLower())
									{
										default:
											img = Image.FromFile(args[i]);
											if(!haveSetSize)
											{
												il.ImageSize = img.Size;
												haveSetSize = true;
											}
											else if(img.Size != il.ImageSize)
											{
												Console.WriteLine("warning: cannot store differently sized images in an ImageList.\n{0} stored in ImageList {1} will be truncated from {2} to {3} pixels\n", args[i], resname, img.Size, il.ImageSize);
											}
											il.Images.Add(img);
											break;
										case ".ico":
											ico = new Icon(args[i]);
											if(!haveSetSize)
											{
												il.ImageSize = ico.Size;
												haveSetSize = true;
											}
											else if(ico.Size != il.ImageSize)
											{
												Console.WriteLine("warning: cannot store differently sized images in an ImageList.\n{0} stored in ImageList {1} will be truncated from {2} to {3} pixels\n", args[i], resname, ico.Size, il.ImageSize);
											}
											il.Images.Add(ico);
											break;
									}
								}
							}
							catch(Exception e)
							{
								Console.WriteLine(String.Format("error: {0}: {1}", args[i], e.Message));
								return;
							}
							try
							{
								rw.AddResource(resname, il.ImageStream);
							}
							catch(Exception e)
							{
								Console.WriteLine(String.Format("error: {0}: {1}", resname, e.Message));
							}
						}
						break;
				}
			}
			try
			{
				rw.Close();
			}
			catch(Exception e)
			{
				Console.WriteLine(String.Format("error: {0}: {1}", args[0], e.Message));
			}
		}
	}
}


text:
var layer = require('layer')
  , should = require('should')
  , intercept = require('../index.js');

describe('intercept', function() {

  it('intercepts stuff', function() {
    var ctx = {
      hi: function(x, y, z) {
        throw new Error('hi got called');
      }
    }
    var result = intercept(ctx, ctx.hi);
    // stays false until ctx.hi is called
    result().should.be.equal(false);

    ctx.hi(1, 2, 3);

    // once called it populates with some information
    result().should.eql({called: true, args: [1,2,3] });

    // the intercepted function automatically resets after the result is called
    var error = false;
    try {
      ctx.hi(1, 2, 3);
    } catch(e) {
      error = true;
    }
    error.should.be.equal(true);
  });

  it('calls intercepting func if there is one', function(done) {
    var ctx = {
      hi: function(x, y, z) {
        throw new Error('hi got called');
      }
    }

    var intercepting = function(result2) {
      result().should.eql({called: true, args: [1,2,3] });
      result2.should.eql({called: true, args: [1,2,3] });
      done();
    }

    var result = intercept(ctx, ctx.hi, intercepting);
    // stays false until ctx.hi is called
    result().should.be.equal(false);
    ctx.hi(1, 2, 3);
  });

  it('resets the interception', function() {
    var ctx = {
      hi: function(x, y, z) {
        throw new Error('hi got called');
      }
    }
    var result = intercept(ctx, ctx.hi);
    // stays false until ctx.hi is called
    result().should.be.equal(false);

    // reset the interception
    result.reset();

    var error = false;
    try {
      ctx.hi(1, 2, 3);
    } catch(e) {
      error = true;
    }
    error.should.be.equal(true);

    // calling reset again does nothing
    result.reset();
  });

});


text:
package io.rong.app.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

/**
 * Created by zhjchen on 8/12/15.
 */
public class RongHorizontalScrollView extends HorizontalScrollView {

    public RongHorizontalScrollView(Context context) {
        super(context);
        initView();
    }

    public RongHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public RongHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public RongHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    private void initView() {

        LinearLayout linearLayout = new LinearLayout(getContext());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setLayoutParams(layoutParams);

        addView(linearLayout);
    }

    public void addLayoutChildView(View v) {
        if (v == null) return;

        View view = getChildAt(0);

        if (view != null) {
            if (view instanceof LinearLayout) {
                LinearLayout layout = (LinearLayout) view;
                layout.addView(v);
            }
        }
    }

    public void removeLayoutChildView(View v) {
        if (v == null) return;

        View view = getChildAt(0);

        if (view != null) {
            if (view instanceof LinearLayout) {
                LinearLayout layout = (LinearLayout) view;
                layout.removeView(v);
            }
        }
    }

    public View getLayoutChileView(String tag) {
        if (tag == null) return null;

        View layoutView = getChildAt(0);

        if (layoutView != null) {
            if (layoutView instanceof LinearLayout) {
                LinearLayout layout = (LinearLayout) layoutView;
                int childCount = layout.getChildCount();

                for (int i = 0; i < childCount; i++) {
                    View view = layout.getChildAt(i);

                    if (view.getTag() != null && tag.equals(view.getTag())) {
                        return view;
                    }
                }
            }
        }
        return null;
    }
}


text:
/*
@page whatsnew New in 2.0
@tag new

New in 2.0

In order of significance:

jQuery

A far cry from the "library interdependance" of 1.5, 2.0 has sold is soul to jQuery.
   It's been great for the project, allowing us to focus on what makes JavaScriptMVC
   different - development tools and architecture.

Testing

Likely the most effort has gone into JavaScriptMVC's testing.  You can now write your tests and
expect them to run in all browsers, Rhino, and Selenium automatically.

Documentation

The most obvious change has been to the new Documentation engine.
*/


text:
#ifndef _H_SHARED

#include "shrdob.h"
#include "parse.h"

typedef struct tagPRINTLISTWND {
   HWND hwnd;
   int idDlg;
   HPSTR lpLines;
   HPDWORD lpIndexTable;
   DWORD cLines;
} PRINTLISTWND;

/* FWMAIL.C */
LRESULT EXPORT CALLBACK ObProc_ForwardMail( UINT, HNDFILE, LPVOID, LPVOID );
void FASTCALL CmdForwardMailMessage( HWND, PTH );

/* MAIL.C */
LRESULT EXPORT CALLBACK ObProc_MailMessage( UINT, HNDFILE, LPVOID, LPVOID );
LRESULT EXPORT CALLBACK ObProc_CIXMailMessage( UINT, HNDFILE, LPVOID, LPSTR );
void FASTCALL InstallMailForms( void );
void FASTCALL ComposeMailForm( char *, BOOL, HPSTR, HEADER FAR * );
HWND FASTCALL CreateMailWindow( HWND, MAILOBJECT FAR *, LPOB );
void FASTCALL CommonPickerCode( HWND, int, int, int, BOOL, BOOL );
void FASTCALL CmdMailMessage( HWND, LPSTR, LPSTR );
void FASTCALL CmdMailReply( HWND, BOOL, BOOL );
void FASTCALL CommonSigChangeCode( HWND, char *, BOOL, BOOL );
void FASTCALL CommonTopicSigChangeCode( HWND, char * );
void FASTCALL CommonSetSignature( HWND, PTL );
void FASTCALL FillEncodingScheme( HWND, int, UINT, BOOL, BOOL );
BOOL FASTCALL GetReplyMailHeaderField( PTH, char *, char *, int );
UINT FASTCALL GetEncodingScheme( HWND, int );
BOOL FASTCALL IsCixAddress( char * );
void FASTCALL CreateLocalCopyOfAttachmentMail( MAILOBJECT FAR *, LPSTR, int, char * );
void FASTCALL CreateLocalCopyOfForwardAttachmentMail( FORWARDMAILOBJECT FAR *, LPSTR, int, char * );
LPSTR FASTCALL ExtractMailAddress( LPSTR, LPSTR, int );
LRESULT EXPORT CALLBACK ObProc_ClearCIXMail( UINT, HNDFILE, LPVOID, LPSTR );
void FASTCALL CreateReplyAddress( RECPTR *, PTL );
void FASTCALL CreateMailMailAddress( RECPTR *, PTL );

/* ARTICLE.C */
void FASTCALL CmdPostArticle( HWND, LPSTR );
void FASTCALL CmdFollowUpArticle( HWND, BOOL );
void FASTCALL ShowHideEncodingField( HWND );
LRESULT EXPORT CALLBACK ObProc_ArticleMessage( UINT, HNDFILE, LPVOID, LPVOID );
BOOL FASTCALL CreateArticleWindow( HWND, ARTICLEOBJECT FAR *, LPOB );

/* GRPLIST.C */
BOOL FASTCALL CreateGroupListWindow( HWND );
void FASTCALL RefreshNewsgroupWindow( void );
void FASTCALL ReadGroupsDat( HWND, char * );
BOOL FASTCALL Subscribe( HWND, LPSTR );
void FASTCALL DisplayNewsgroupStatus();
DWORD FASTCALL GetNewNewsgroups( void );
LRESULT EXPORT CALLBACK ObProc_GetNewNewsgroups( UINT, HNDFILE, LPVOID, LPVOID );
LRESULT EXPORT CALLBACK ObProc_GetNewsgroups( UINT, HNDFILE, LPVOID, LPVOID );
void FASTCALL EnsureNewsFolder( void );
void FASTCALL CommonListCommands( HWND, int, HWND, UINT );

/* CIXLIST */
void FASTCALL CmdPrintGeneralList( HWND, PRINTLISTWND * );

#define _H_SHARED
#endif


text:
import re

"""
There are two types of checks: a header check and a body check.
"""

class BaseCheck:
    """
    code used by both header and body checks
    """
    def __init__(self, name, group, regex, meta_token = 0):
        self.name = name
        self.group = (group or name)
        self.regex = regex
        self.meta_token = meta_token

    def mangle(self, tokens):
        if self.meta_token:
            return [self.group] * len(tokens)
        else:
            return [self.group + x for x in tokens]

class Header(BaseCheck):
    def __init__(self, header, name, group, regex, meta_token = 0):
        BaseCheck.__init__(self, name, group, regex, meta_token)
        self.header = header

    def get_tokens(self, targets):
        matches = [self.regex(x) for x in targets]
        tokens = []
        for m in matches:
            tokens += self.mangle(m)
        return tokens

class Body(BaseCheck):
    def get_tokens(self, target):
        return self.mangle(self.regex(target))

if __name__ == "__main__":
    b = Body("A", None, re.compile(r"ab[cd]\b").findall, 0)
    print b.get_tokens("abc abe abd abdd")

    h = Header("X-Something", "B", "C", re.compile(r"\b\w+'?\w+\b").findall, 1)
    print h.get_tokens(["hi there", "how are you", "i'm fine"])


text:
package org.chimi.ipfilter.web;

public interface IpBlocker {
    boolean accept(String remoteAddr);

    void reload();
}


text:
module VagrantPlugins
  module OVirtProvider
    module Action
      class MessageAlreadyUp
        def initialize(app, env)
          @app = app
        end

        def call(env)
          env[:ui].info(I18n.t("vagrant_ovirt3.already_up"))
          @app.call(env)
        end
      end
    end
  end
end


text:
var ss_IEquatable = function#? DEBUG IEquatable$##() { };
ss_IEquatable.prototype = {
	equalsT: null
};

ss_IEquatable.__typeName = 'ss.IEquatable';
ss.IEquatable = ss_IEquatable;
ss.initInterface(ss_IEquatable);


text:
require 'rubygems'
require 'bundler'
Bundler.setup

if ::Bundler.definition.specs['debugger'].first
  require 'debugger'
elsif ::Bundler.definition.specs['ruby-debug'].first
  require 'ruby-debug'
end

require 'test/unit'
require 'fileutils'
require 'active_record'
require 'posix/spawn'
require 'mysql2xxxx'

MYSQL_USER = 'root'
MYSQL_PASS = 'password'
MYSQL_HOST = '127.0.0.1'
TEST_DB = 'mysql2xxxx_test'

def execute_sql(sql, db = 'mysql')
  POSIX::Spawn::Child.new %{mysql -u #{MYSQL_USER} -p#{MYSQL_PASS} --database="#{db}" --execute="#{sql}"}
end

execute_sql "DROP DATABASE IF EXISTS #{TEST_DB}"
execute_sql "CREATE DATABASE #{TEST_DB}"
execute_sql "SOURCE test/fixtures/automobile_makes.sql", TEST_DB
execute_sql "SOURCE test/fixtures/automobile_make_years.sql", TEST_DB

class Test::Unit::TestCase
  def setup
    @options = {
      :execute => %{SELECT * FROM automobile_makes WHERE automobile_makes.name IN (SELECT DISTINCT automobile_make_years.make_name FROM automobile_make_years)},
      :user => MYSQL_USER,
      :password => MYSQL_PASS,
      :database => TEST_DB,
      :host => MYSQL_HOST
    }
  end
end


text:
import Player from './player';
import helpers from './../helpers';
import _ from 'underscore'

const getPossibleMoves = helpers.getPossibleMoves;

class RandomPlayer extends Player {
    constructor(...params) {
        super(...params);
        this.onMyTurn(gameGrid => {
            const possibleMoves = getPossibleMoves(gameGrid);
            const randomMove = _.sample(possibleMoves);
            this.makeMove(randomMove);
        });
    }
}

export default RandomPlayer;


text:
package org.metaeffekt.core.maven.inventory.extractor;

import org.metaeffekt.core.inventory.processor.model.Artifact;
import org.metaeffekt.core.inventory.processor.model.AssetMetaData;
import org.metaeffekt.core.inventory.processor.model.Inventory;
import org.metaeffekt.core.inventory.processor.reader.InventoryReader;
import org.metaeffekt.core.inventory.processor.writer.InventoryWriter;
import org.metaeffekt.reader.inspect.image.ImageInspectReader;
import org.metaeffekt.reader.inspect.image.model.ImageInspectData;
import org.metaeffekt.reader.inspect.image.model.ImageInspectElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

import static org.metaeffekt.core.inventory.processor.model.Constants.KEY_ISSUE;

public class ContainerAssetInventoryProcessor {

    private static final Logger LOG = LoggerFactory.getLogger(ContainerAssetInventoryProcessor.class);

    public static final String ASSET_MARKER = "x";

    private File analysisDir;
    private File containerInspectionFile;
    private File inventoryFile;

    private String repo;
    private String tag;
    private String qualifier;

    public ContainerAssetInventoryProcessor() {}

    public ContainerAssetInventoryProcessor basedOn(File containerInspectionFile) {
        this.containerInspectionFile = containerInspectionFile;
        return this;
    }

    public ContainerAssetInventoryProcessor augmenting(File inventoryFile) {
        this.inventoryFile = inventoryFile;
        return this;
    }

    public ContainerAssetInventoryProcessor fromRepo(String repo) {
        this.repo = repo;
        return this;
    }

    public ContainerAssetInventoryProcessor withTag(String tag) {
        this.tag = tag;
        return this;
    }

    public ContainerAssetInventoryProcessor fromAnalysisDir(File analysisDir) {
        this.analysisDir = analysisDir;
        return this;
    }

    public ContainerAssetInventoryProcessor qualifiedBy(String qualifier) {
        this.qualifier = qualifier;
        return this;
    }

    public void process() throws IOException {
        // load the inventory
        final Inventory inventory = new InventoryReader().readInventory(inventoryFile);

        final AssetMetaData assetMetadata = createAssetMetadata(inventory);
        final String assetId = assetMetadata.get(AssetMetaData.Attribute.ASSET_ID);

        // apply asset metadata to all entries in the inventory
        for (Artifact artifact : inventory.getArtifacts()) {
            artifact.set(assetId, ASSET_MARKER);

            // FIXME: we eliminate issue on artifact level; this is an asset level attribute
            //   Needs consolidation of new asset feature.
            artifact.set(KEY_ISSUE, null);
        }

        // write the inventory
        new InventoryWriter().writeInventory(inventory, inventoryFile);
    }

    private AssetMetaData createAssetMetadata(Inventory inventory) {
        AssetMetaData assetMetaData = new AssetMetaData();
        assetMetaData.set(AssetMetaData.Attribute.ASSET_ID, "CID-" + repo + "-" + tag);
        assetMetaData.set("Repository", repo);
        assetMetaData.set("Version", tag);
        inventory.getAssetMetaData().add(assetMetaData);

        attachContainerInspectionDetails(assetMetaData);
        attachIssueInformation(assetMetaData);

        return assetMetaData;
    }

    private void attachIssueInformation(AssetMetaData assetMetaData) {
        try {
            DebianInventoryExtractor extractor = new DebianInventoryExtractor();
            final String issue = extractor.extractIssue(analysisDir);
            assetMetaData.set(KEY_ISSUE, issue);

        } catch (Exception e) {
            LOG.error("Cannot inspect issue of container image {}:{}.", repo, tag, e);
        }
    }

    private void attachContainerInspectionDetails(AssetMetaData assetMetaData) {
        try {
            final ImageInspectData imageInspectElements = ImageInspectReader.dataFromJson(containerInspectionFile);
            if (imageInspectElements.size() == 1) {
                ImageInspectElement element = imageInspectElements.get(0);
                String created = element.getCreated();

                int index = created.indexOf(".");
                if (index != -1) {
                    created = created.substring(0, index);
                }

                assetMetaData.set("Created", created);

                assetMetaData.set("Size", String.valueOf(element.getSize()));
                assetMetaData.set("Image Id", String.valueOf(element.getId()));
                assetMetaData.set("Author", String.valueOf(element.getAuthor()));
                assetMetaData.set("Architecture", String.valueOf(element.getArchitecture()));
                assetMetaData.set("Os", String.valueOf(element.getOs()));
            }
        } catch (Exception e) {
            LOG.error("Cannot inspect container image {}:{}.", repo, tag, e);
        }
    }

}


text:
<?php

namespace Symfony\Component\Intl\Data\Provider;

use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReaderInterface;
use Symfony\Component\Intl\Exception\MissingResourceException;

/**
 * Data provider for currency-related data.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @internal to be removed in 5.0.
 */
class CurrencyDataProvider
{
    const INDEX_SYMBOL = 0;
    const INDEX_NAME = 1;
    const INDEX_FRACTION_DIGITS = 0;
    const INDEX_ROUNDING_INCREMENT = 1;

    private $path;
    private $reader;

    /**
     * Creates a data provider that reads currency-related data from a
     * resource bundle.
     *
     * @param string                     $path   The path to the resource bundle
     * @param BundleEntryReaderInterface $reader The reader for reading the resource bundle
     */
    public function __construct(string $path, BundleEntryReaderInterface $reader)
    {
        $this->path = $path;
        $this->reader = $reader;
    }

    public function getCurrencies()
    {
        return $this->reader->readEntry($this->path, 'meta', ['Currencies']);
    }

    public function getSymbol($currency, $displayLocale = null)
    {
        if (null === $displayLocale) {
            $displayLocale = \Locale::getDefault();
        }

        return $this->reader->readEntry($this->path, $displayLocale, ['Names', $currency, static::INDEX_SYMBOL]);
    }

    public function getName($currency, $displayLocale = null)
    {
        if (null === $displayLocale) {
            $displayLocale = \Locale::getDefault();
        }

        return $this->reader->readEntry($this->path, $displayLocale, ['Names', $currency, static::INDEX_NAME]);
    }

    public function getNames($displayLocale = null)
    {
        if (null === $displayLocale) {
            $displayLocale = \Locale::getDefault();
        }

        // ====================================================================
        // For reference: It is NOT possible to return names indexed by
        // numeric code here, because some numeric codes map to multiple
        // 3-letter codes (e.g. 32 => "ARA", "ARP", "ARS")
        // ====================================================================

        $names = $this->reader->readEntry($this->path, $displayLocale, ['Names']);

        if ($names instanceof \Traversable) {
            $names = iterator_to_array($names);
        }

        $index = static::INDEX_NAME;

        array_walk($names, function (&$value) use ($index) {
            $value = $value[$index];
        });

        // Sorting by value cannot be done during bundle generation, because
        // binary bundles are always sorted by keys
        $collator = new \Collator($displayLocale);
        $collator->asort($names);

        return $names;
    }

    /**
     * Data provider for {@link \Symfony\Component\Intl\Currency::getFractionDigits()}.
     */
    public function getFractionDigits($currency)
    {
        try {
            return $this->reader->readEntry($this->path, 'meta', ['Meta', $currency, static::INDEX_FRACTION_DIGITS]);
        } catch (MissingResourceException $e) {
            return $this->reader->readEntry($this->path, 'meta', ['Meta', 'DEFAULT', static::INDEX_FRACTION_DIGITS]);
        }
    }

    /**
     * Data provider for {@link \Symfony\Component\Intl\Currency::getRoundingIncrement()}.
     */
    public function getRoundingIncrement($currency)
    {
        try {
            return $this->reader->readEntry($this->path, 'meta', ['Meta', $currency, static::INDEX_ROUNDING_INCREMENT]);
        } catch (MissingResourceException $e) {
            return $this->reader->readEntry($this->path, 'meta', ['Meta', 'DEFAULT', static::INDEX_ROUNDING_INCREMENT]);
        }
    }

    /**
     * Data provider for {@link \Symfony\Component\Intl\Currency::getNumericCode()}.
     */
    public function getNumericCode($currency)
    {
        return $this->reader->readEntry($this->path, 'meta', ['Alpha3ToNumeric', $currency]);
    }

    /**
     * Data provider for {@link \Symfony\Component\Intl\Currency::forNumericCode()}.
     */
    public function forNumericCode($numericCode)
    {
        return $this->reader->readEntry($this->path, 'meta', ['NumericToAlpha3', (string) $numericCode]);
    }
}


text:
namespace Microsoft.Protocols.TestSuites.MS_ONESTORE
{
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The class is used to represent the Root File Node List.
    /// </summary>
    public class RootFileNodeList
    {
        public RootFileNodeList()
        {
            this.FileNodeListFragments = new List<FileNodeListFragment>();
            this.ObjectSpaceManifestList = new List<MS_ONESTORE.ObjectSpaceManifestList>();
            this.FileDataStoreListReference = new List<FileNode>();
            this.FileNodeSequence = new List<FileNode>();
        }
        /// <summary>
        /// Gets or sets the FileNodeListFragment list.
        /// </summary>
        public List<FileNodeListFragment> FileNodeListFragments { get; set; }
        /// <summary>
        /// Gets or sets the ObjectSpaceManifestRoot FileNode.
        /// </summary>
        public FileNode ObjectSpaceManifestRoot { get; set; }

        /// <summary>
        /// Gets or sets the FileNode list.
        /// </summary>
        public List<FileNode> FileNodeSequence { get; set; }
        /// <summary>
        /// Gets or sets the list of Object SpaceManifest List
        /// </summary>
        public List<ObjectSpaceManifestList> ObjectSpaceManifestList { get; set; }
        /// <summary>
        /// Gets or sets the list of FileDataStoreListReference FileNode.
        /// </summary>
        public List<FileNode> FileDataStoreListReference { get; set; }
        /// <summary>
        /// This method is used to deserialize the Root File Node List from the specified byte array and start index.
        /// </summary>
        /// <param name="byteArray">Specify the byte array.</param>
        /// <param name="reference">Specify the reference of Root File Node List.</param>
        public void DoDeserializeFromByteArray(byte[] byteArray, FileChunkReference64x32 reference)
        {
            FileNodeListFragment fragment = new FileNodeListFragment(reference.Cb);
            fragment.DoDeserializeFromByteArray(byteArray, (int)reference.Stp);
            this.FileNodeListFragments.Add(fragment);
            this.FileNodeSequence.AddRange(fragment.rgFileNodes.Where(f => f.FileNodeID != FileNodeIDValues.ChunkTerminatorFND).ToArray());
            FileChunkReference64x32 nextFragmentRef = fragment.nextFragment;
            while (nextFragmentRef.IsfcrNil()==false && nextFragmentRef.IsfcrZero() == false)
            {
                FileNodeListFragment nextFragment = new FileNodeListFragment(nextFragmentRef.Cb);
                nextFragment.DoDeserializeFromByteArray(byteArray, (int)nextFragmentRef.Stp);
                nextFragmentRef = nextFragment.nextFragment;
                this.FileNodeListFragments.Add(nextFragment);
                this.FileNodeSequence.AddRange(fragment.rgFileNodes.Where(f => f.FileNodeID != FileNodeIDValues.ChunkTerminatorFND).ToArray());
            }

            FileNode[] objectSpaceManifestListReferences = this.FileNodeSequence.Where(obj => obj.FileNodeID == FileNodeIDValues.ObjectSpaceManifestListReferenceFND).ToArray();
            foreach (FileNode node in objectSpaceManifestListReferences)
            {
                ObjectSpaceManifestListReferenceFND objectSpaceManifestListReference = node.fnd as ObjectSpaceManifestListReferenceFND;
                ObjectSpaceManifestList objectSpaceManifestList = new MS_ONESTORE.ObjectSpaceManifestList();
                objectSpaceManifestList.DoDeserializeFromByteArray(byteArray, objectSpaceManifestListReference.refField);
                this.ObjectSpaceManifestList.Add(objectSpaceManifestList);
            }

            this.FileDataStoreListReference.AddRange(this.FileNodeSequence.Where(obj => obj.FileNodeID == FileNodeIDValues.FileDataStoreListReferenceFND).ToArray());
            FileNode[] objectSpaceManifestRootArray = this.FileNodeSequence.Where(obj => obj.FileNodeID == FileNodeIDValues.ObjectSpaceManifestRootFND).ToArray();
            if (objectSpaceManifestRootArray.Length == 1)
            {
                this.ObjectSpaceManifestRoot = objectSpaceManifestRootArray[0];
            }
        }
    }
}