text:
/* SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) */
/* Copyright Authors of Cilium */

#ifndef __TEST_PKTGEN__
#define __TEST_PKTGEN__

#include <bpf/compiler.h>
#include <bpf/builtins.h>
#include <bpf/helpers.h>

#include <lib/endian.h>

#include <linux/byteorder.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/in.h>
#include <linux/if_ether.h>
#include <linux/tcp.h>

/* A collection of pre-defined Ethernet MAC addresses, so tests can reuse them
 *  without having to come up with custom addresses.
 */

#define mac_one   {0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xEF}
#define mac_two   {0x13, 0x37, 0x13, 0x37, 0x13, 0x37}
#define mac_three {0x31, 0x41, 0x59, 0x26, 0x35, 0x89}
#define mac_four  {0x0D, 0x1D, 0x22, 0x59, 0xA9, 0xC2}
#define mac_five  {0x15, 0x21, 0x39, 0x45, 0x4D, 0x5D}
#define mac_six   {0x08, 0x14, 0x1C, 0x32, 0x52, 0x7E}

/* A collection of pre-defined IP addresses, so tests can reuse them without
 *  having to come up with custom ips.
 */

#define IPV4(a, b, c, d) (((d) << 24) + ((c) << 16) + ((b) << 8) + (a))

/* IPv4 addresses for hosts, external to the cluster */
#define v4_ext_one	IPV4(110, 0, 11, 1)
#define v4_ext_two	IPV4(120, 0, 12, 2)
#define v4_ext_three	IPV4(130, 0, 13, 3)

/* IPv4 addresses for nodes in the cluster */
#define v4_node_one	IPV4(10, 0, 10, 1)
#define v4_node_two	IPV4(10, 0, 10, 2)
#define v4_node_three	IPV4(10, 0, 10, 3)

/* IPv4 addresses for services in the cluster */
#define v4_svc_one	IPV4(172, 16, 10, 1)
#define v4_svc_two	IPV4(172, 16, 10, 2)
#define v4_svc_three	IPV4(172, 16, 10, 3)

/* IPv4 addresses for pods in the cluster */
#define v4_pod_one	IPV4(192, 168, 0, 1)
#define v4_pod_two	IPV4(192, 168, 0, 2)
#define v4_pod_three	IPV4(192, 168, 0, 3)

/* Source port to be used by a client */
#define tcp_src_one	__bpf_htons(22334)
#define tcp_src_two	__bpf_htons(33445)
#define tcp_src_three	__bpf_htons(44556)

#define tcp_svc_one	__bpf_htons(80)
#define tcp_svc_two	__bpf_htons(443)
#define tcp_svc_three	__bpf_htons(53)

#define default_data "Should not change!!"

/* Define SCTP header here because this is all we need. */
struct sctphdr {
	__be16 source;
	__be16 dest;
	__be32 vtag;
	__le32 checksum;
};

enum pkt_layer {
	PKT_LAYER_NONE,

	/* L2 layers */
	PKT_LAYER_ETH,
	PKT_LAYER_8021Q,

	/* L3 layers */
	PKT_LAYER_IPV4,
	PKT_LAYER_IPV6,
	PKT_LAYER_ARP,
	/* TODO IPv6 extension headers */

	/* L4 layers */
	PKT_LAYER_TCP,
	PKT_LAYER_UDP,
	PKT_LAYER_ICMP,
	PKT_LAYER_ICMPV6,
	PKT_LAYER_SCTP,

	/* Packet data*/
	PKT_LAYER_DATA,
};

#define PKT_BUILDER_LAYERS 6

#define MAX_PACKET_OFF 0xffff

/* Packet builder */
struct pktgen {
	struct __ctx_buff *ctx;
	__u16 cur_off;
	__u16 layer_offsets[PKT_BUILDER_LAYERS];
	enum pkt_layer layers[PKT_BUILDER_LAYERS];
};

static __always_inline
void pktgen__init(struct pktgen *builder, struct __ctx_buff *ctx)
{
	builder->cur_off = 0;
	builder->ctx = ctx;
	#pragma unroll
	for (int i = 0; i < PKT_BUILDER_LAYERS; i++) {
		builder->layers[i] = PKT_LAYER_NONE;
		builder->layer_offsets[i] = 0;
	}
};

static __always_inline
int pktgen__free_layer(const struct pktgen *builder)
{
	#pragma unroll
	for (int i = 0; i < PKT_BUILDER_LAYERS; i++) {
		if (builder->layers[i] == PKT_LAYER_NONE)
			return i;
	}

	return -1;
}

/* Push an empty ethernet header onto the packet */
static __always_inline
__attribute__((warn_unused_result))
struct ethhdr *pktgen__push_ethhdr(struct pktgen *builder)
{
	struct __ctx_buff *ctx = builder->ctx;
	struct ethhdr *layer;
	int layer_idx;

	/* Request additional tailroom, and check that we got it. */
	ctx_adjust_troom(ctx, builder->cur_off + sizeof(struct ethhdr) - ctx_full_len(ctx));
	if (ctx_data(ctx) + builder->cur_off + sizeof(struct ethhdr) > ctx_data_end(ctx))
		return 0;

	/* Check that any value within the struct will not exceed a u16 which
	 * is the max allowed offset within a packet from ctx->data.
	 */
	if (builder->cur_off >= MAX_PACKET_OFF - sizeof(struct ethhdr))
		return 0;

	layer = ctx_data(ctx) + builder->cur_off;
	layer_idx = pktgen__free_layer(builder);

	if (layer_idx < 0)
		return 0;

	builder->layers[layer_idx] = PKT_LAYER_ETH;
	builder->layer_offsets[layer_idx] = builder->cur_off;
	builder->cur_off += sizeof(struct ethhdr);

	return layer;
}

/* helper to set the source and destination mac address at the same time */
static __always_inline
void ethhdr__set_macs(struct ethhdr *l2, unsigned char *src, unsigned char *dst)
{
	memcpy(l2->h_source, src, ETH_ALEN);
	memcpy(l2->h_dest, dst, ETH_ALEN);
}

/* Push an empty IPv4 header onto the packet */
static __always_inline
__attribute__((warn_unused_result))
struct iphdr *pktgen__push_iphdr(struct pktgen *builder)
{
	struct __ctx_buff *ctx = builder->ctx;
	struct iphdr *layer;
	int layer_idx;

	/* Request additional tailroom, and check that we got it. */
	ctx_adjust_troom(ctx, builder->cur_off + sizeof(struct iphdr) - ctx_full_len(ctx));
	if (ctx_data(ctx) + builder->cur_off + sizeof(struct iphdr) > ctx_data_end(ctx))
		return 0;

	/* Check that any value within the struct will not exceed a u16 which
	 * is the max allowed offset within a packet from ctx->data.
	 */
	if (builder->cur_off >= MAX_PACKET_OFF - sizeof(struct iphdr))
		return 0;

	layer = ctx_data(ctx) + builder->cur_off;
	layer_idx = pktgen__free_layer(builder);

	if (layer_idx < 0)
		return 0;

	builder->layers[layer_idx] = PKT_LAYER_IPV4;
	builder->layer_offsets[layer_idx] = builder->cur_off;
	builder->cur_off += sizeof(struct iphdr);

	return layer;
}

/* Push a IPv4 header with sane defaults onto the packet */
static __always_inline
__attribute__((warn_unused_result))
struct iphdr *pktgen__push_default_iphdr(struct pktgen *builder)
{
	struct iphdr *hdr = pktgen__push_iphdr(builder);

	if (!hdr)
		return 0;

	hdr->version = 4;
	/* No options by default */
	hdr->ihl = 5;
	hdr->ttl = 64;
	/* No fragmentation by default */
	hdr->frag_off = 0;

	return hdr;
}

/* Push an empty TCP header onto the packet */
static __always_inline
__attribute__((warn_unused_result))
struct tcphdr *pktgen__push_tcphdr(struct pktgen *builder)
{
	struct __ctx_buff *ctx = builder->ctx;
	struct tcphdr *layer;
	int layer_idx;

	/* Request additional tailroom, and check that we got it. */
	ctx_adjust_troom(ctx, builder->cur_off + sizeof(struct tcphdr) - ctx_full_len(ctx));
	if (ctx_data(ctx) + builder->cur_off + sizeof(struct tcphdr) > ctx_data_end(ctx))
		return 0;

	/* Check that any value within the struct will not exceed a u16 which
	 * is the max allowed offset within a packet from ctx->data.
	 */
	if (builder->cur_off >= MAX_PACKET_OFF - sizeof(struct tcphdr))
		return 0;

	layer = ctx_data(ctx) + builder->cur_off;
	layer_idx = pktgen__free_layer(builder);

	if (layer_idx < 0)
		return 0;

	builder->layers[layer_idx] = PKT_LAYER_TCP;
	builder->layer_offsets[layer_idx] = builder->cur_off;
	builder->cur_off += sizeof(struct tcphdr);

	return layer;
}

/* Push a TCP header with sane defaults onto the packet */
static __always_inline
__attribute__((warn_unused_result))
struct tcphdr *pktgen__push_default_tcphdr(struct pktgen *builder)
{
	struct tcphdr *hdr = pktgen__push_tcphdr(builder);

	if (!hdr)
		return 0;
	if ((void *)hdr + sizeof(struct tcphdr) > ctx_data_end(builder->ctx))
		return 0;

	hdr->syn = 1;
	hdr->seq = 123456;
	hdr->window = 65535;

	/* In most cases the doff is 5, so a good default if we can't
	 * calc the actual offset
	 */
	hdr->doff = 5;

	return hdr;
}

/* Push an empty SCTP header onto the packet */
static __always_inline
__attribute__((warn_unused_result))
struct sctphdr *pktgen__push_sctphdr(struct pktgen *builder)
{
	struct __ctx_buff *ctx = builder->ctx;
	struct sctphdr *layer;
	int layer_idx;

	/* Request additional tailroom, and check that we got it. */
	ctx_adjust_troom(ctx, builder->cur_off + sizeof(struct sctphdr) - ctx_full_len(ctx));
	if (ctx_data(ctx) + builder->cur_off + sizeof(struct sctphdr) > ctx_data_end(ctx))
		return 0;

	/* Check that any value within the struct will not exceed a u16 which
	 * is the max allowed offset within a packet from ctx->data.
	 */
	if (builder->cur_off >= MAX_PACKET_OFF - sizeof(struct sctphdr))
		return 0;

	layer = ctx_data(ctx) + builder->cur_off;
	layer_idx = pktgen__free_layer(builder);

	if (layer_idx < 0)
		return 0;

	builder->layers[layer_idx] = PKT_LAYER_SCTP;
	builder->layer_offsets[layer_idx] = builder->cur_off;
	builder->cur_off += sizeof(struct sctphdr);

	return layer;
}

/* Push room for x bytes of data onto the packet */
static __always_inline
__attribute__((warn_unused_result))
void *pktgen__push_data_room(struct pktgen *builder, int len)
{
	struct __ctx_buff *ctx = builder->ctx;
	void *layer;
	int layer_idx;

	/* Request additional tailroom, and check that we got it. */
	ctx_adjust_troom(ctx, builder->cur_off + len - ctx_full_len(ctx));
	if (ctx_data(ctx) + builder->cur_off + len > ctx_data_end(ctx))
		return 0;

	/* Check that any value within the struct will not exceed a u16 which
	 * is the max allowed offset within a packet from ctx->data.
	 */
	if (builder->cur_off >= MAX_PACKET_OFF - len)
		return 0;

	layer = ctx_data(ctx) + builder->cur_off;
	layer_idx = pktgen__free_layer(builder);

	if (layer_idx < 0)
		return 0;

	builder->layers[layer_idx] = PKT_LAYER_DATA;
	builder->layer_offsets[layer_idx] = builder->cur_off;
	builder->cur_off += len;

	return layer;
}

/* Push data onto the packet */
static __always_inline
__attribute__((warn_unused_result))
void *pktgen__push_data(struct pktgen *builder, void *data, int len)
{
	void *pkt_data = pktgen__push_data_room(builder, len);

	if (!pkt_data)
		return 0;
	if (pkt_data + len > ctx_data_end(builder->ctx))
		return 0;

	memcpy(pkt_data, data, len);

	return pkt_data;
}

/* Do a finishing pass on all the layers, which will set correct next layer
 * fields and length values. TODO checksum calculation?
 */
static __always_inline
void pktgen__finish(const struct pktgen *builder)
{
	struct ethhdr *eth_layer;
	struct iphdr *ipv4_layer;
	struct ipv6hdr *ipv6_layer;
	struct tcphdr *tcp_layer;
	__u16 layer_off;
	__u16 v4len;
	__be16 v6len;
	__u16 hdr_size;

	#pragma unroll
	for (int i = 0; i < PKT_BUILDER_LAYERS; i++) {
		switch (builder->layers[i]) {
		case PKT_LAYER_NONE:
			/* A none signals the end of the layer stack */
			goto exit;

		case PKT_LAYER_ETH:
			layer_off = builder->layer_offsets[i];
			/* Check that any value within the struct will not exceed a u16 which
			 * is the max allowed offset within a packet from ctx->data.
			 */
			if (layer_off >= MAX_PACKET_OFF - sizeof(struct ethhdr))
				return;

			eth_layer = ctx_data(builder->ctx) + layer_off;
			if ((void *)eth_layer + sizeof(struct ethhdr) > ctx_data_end(builder->ctx))
				return;

			if (i + 1 >= PKT_BUILDER_LAYERS)
				return;

			/* Set the proper next hdr value */
			switch (builder->layers[i + 1]) {
			case PKT_LAYER_IPV4:
				eth_layer->h_proto = __bpf_htons(ETH_P_IP);
				break;
			case PKT_LAYER_IPV6:
				eth_layer->h_proto = __bpf_htons(ETH_P_IPV6);
				break;
			case PKT_LAYER_ARP:
				eth_layer->h_proto = __bpf_htons(ETH_P_ARP);
				break;
			default:
				break;
			}

			break;

		case PKT_LAYER_8021Q:
			/* TODO set next protocol once 802.1Q is added */
			break;

		case PKT_LAYER_IPV4:
			layer_off = builder->layer_offsets[i];
			/* Check that any value within the struct will not exceed a u16 which
			 * is the max allowed offset within a packet from ctx->data.
			 */
			if (layer_off >= MAX_PACKET_OFF - sizeof(struct iphdr))
				return;

			ipv4_layer = ctx_data(builder->ctx) + layer_off;
			if ((void *)ipv4_layer + sizeof(struct iphdr) > ctx_data_end(builder->ctx))
				return;

			if (i + 1 >= PKT_BUILDER_LAYERS)
				return;

			switch (builder->layers[i + 1]) {
			case PKT_LAYER_TCP:
				ipv4_layer->protocol = IPPROTO_TCP;
				break;
			case PKT_LAYER_UDP:
				ipv4_layer->protocol = IPPROTO_UDP;
				break;
			case PKT_LAYER_ICMP:
				ipv4_layer->protocol = IPPROTO_ICMP;
				break;
			case PKT_LAYER_SCTP:
				ipv4_layer->protocol = IPPROTO_SCTP;
				break;
			default:
				break;
			}

			v4len = (__be16)(builder->cur_off - builder->layer_offsets[i]);
			/* Calculate total length, which is IPv4 hdr + all layers after it */
			ipv4_layer->tot_len = __bpf_htons(v4len);

			break;

		case PKT_LAYER_IPV6:
			layer_off = builder->layer_offsets[i];
			/* Check that any value within the struct will not exceed a u16 which
			 * is the max allowed offset within a packet from ctx->data.
			 */
			if (layer_off >= MAX_PACKET_OFF - sizeof(struct ipv6hdr))
				return;

			ipv6_layer = ctx_data(builder->ctx) + builder->layer_offsets[i];
			if ((void *)ipv6_layer + sizeof(struct ipv6hdr) >
				ctx_data_end(builder->ctx))
				return;

			if (i + 1 >= PKT_BUILDER_LAYERS)
				return;

			switch (builder->layers[i + 1]) {
			case PKT_LAYER_TCP:
				ipv6_layer->nexthdr = IPPROTO_TCP;
				break;
			case PKT_LAYER_UDP:
				ipv6_layer->nexthdr = IPPROTO_UDP;
				break;
			case PKT_LAYER_ICMPV6:
				ipv6_layer->nexthdr = IPPROTO_ICMPV6;
				break;
			case PKT_LAYER_SCTP:
				ipv6_layer->nexthdr = IPPROTO_SCTP;
				break;
			default:
				break;
			}

			v6len = (__be16)(builder->cur_off + sizeof(struct ipv6hdr) -
				builder->layer_offsets[i]);

			/* Calculate payload length, which doesn't include the header size */
			ipv6_layer->payload_len = __bpf_htons(v6len);

			break;

		case PKT_LAYER_TCP:
			layer_off = builder->layer_offsets[i];
			/* Check that any value within the struct will not exceed a u16 which
			 * is the max allowed offset within a packet from ctx->data.
			 */
			if (layer_off >= MAX_PACKET_OFF - sizeof(struct tcphdr))
				return;

			tcp_layer = ctx_data(builder->ctx) + layer_off;
			if ((void *)tcp_layer + sizeof(struct tcphdr) >
				ctx_data_end(builder->ctx))
				return;

			if (i + 1 >= PKT_BUILDER_LAYERS)
				return;

			/* Calculate the data offset, this is the diff between start of header
			 * and start of data in 32-bit words (bytes divided by 4).
			 */

			if (builder->layers[i + 1] == PKT_LAYER_NONE) {
				/* If no data or next header exists, calc using the current offset */
				hdr_size = builder->cur_off - builder->layer_offsets[i];
			} else {
				hdr_size = builder->layer_offsets[i + 1] -
						builder->layer_offsets[i];
			}

			tcp_layer->doff = hdr_size / 4;

			break;

		case PKT_LAYER_ARP:
			/* No sizes or checksums for ARP, so nothing to do */
			break;

		case PKT_LAYER_UDP:
			/* No sizes or checksums for UDP, so nothing to do */
			break;

		case PKT_LAYER_ICMP:
			/* TODO implement checksum calc? */
			break;

		case PKT_LAYER_ICMPV6:
			/* TODO implement checksum calc? */
			break;

		case PKT_LAYER_SCTP:
			/* TODO implement checksum calc */
			break;

		case PKT_LAYER_DATA:
			/* User defined data, nothing to do */
			break;
		}
	}
exit:
	return;
};

#endif /* __TEST_PKTGEN__ */


text:
---
id: 5a24c314108439a4d4036142
title: Manage State Locally First
challengeType: 6
forumTopicId: 301431
dashedName: manage-state-locally-first
---

# --description--

Here you'll finish creating the `DisplayMessages` component.

# --instructions--

First, in the `render()` method, have the component render an `input` element, `button` element, and `ul` element. When the `input` element changes, it should trigger a `handleChange()` method. Also, the `input` element should render the value of `input` that's in the component's state. The `button` element should trigger a `submitMessage()` method when it's clicked.

Second, write these two methods. The `handleChange()` method should update the `input` with what the user is typing. The `submitMessage()` method should concatenate the current message (stored in `input`) to the `messages` array in local state, and clear the value of the `input`.

Finally, use the `ul` to map over the array of `messages` and render it to the screen as a list of `li` elements.

# --hints--

The `DisplayMessages` component should initialize with a state equal to `{ input: "", messages: [] }`.

```js
assert(
  (function () {
    const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
    const initialState = mockedComponent.state();
    return (
      typeof initialState === 'object' &&
      initialState.input === '' &&
      initialState.messages.length === 0
    );
  })()
);
```

The `DisplayMessages` component should render a `div` containing an `h2` element, a `button` element, a `ul` element, and `li` elements as children.

```js
async () => {
  const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
  const waitForIt = (fn) =>
    new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
  const state = () => {
    mockedComponent.setState({ messages: ['__TEST__MESSAGE'] });
    return waitForIt(() => mockedComponent);
  };
  const updated = await state();
  assert(
    updated.find('div').length === 1 &&
      updated.find('h2').length === 1 &&
      updated.find('button').length === 1 &&
      updated.find('ul').length === 1 &&
      updated.find('li').length > 0
  );
};
```

`.map` should be used on the `messages` array.

```js
assert(code.match(/this\.state\.messages\.map/g));
```

The `input` element should render the value of `input` in local state.

```js
async () => {
  const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
  const waitForIt = (fn) =>
    new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
  const causeChange = (c, v) =>
    c.find('input').simulate('change', { target: { value: v } });
  const testValue = '__TEST__EVENT__INPUT';
  const changed = () => {
    causeChange(mockedComponent, testValue);
    return waitForIt(() => mockedComponent);
  };
  const updated = await changed();
  assert(updated.find('input').props().value === testValue);
};
```

Calling the method `handleChange` should update the `input` value in state to the current input.

```js
async () => {
  const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
  const waitForIt = (fn) =>
    new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
  const causeChange = (c, v) =>
    c.find('input').simulate('change', { target: { value: v } });
  const initialState = mockedComponent.state();
  const testMessage = '__TEST__EVENT__MESSAGE__';
  const changed = () => {
    causeChange(mockedComponent, testMessage);
    return waitForIt(() => mockedComponent);
  };
  const afterInput = await changed();
  assert(
    initialState.input === '' &&
      afterInput.state().input === '__TEST__EVENT__MESSAGE__'
  );
};
```

Clicking the `Add message` button should call the method `submitMessage` which should add the current `input` to the `messages` array in state.

```js
async () => {
  const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
  const waitForIt = (fn) =>
    new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
  const causeChange = (c, v) =>
    c.find('input').simulate('change', { target: { value: v } });
  const initialState = mockedComponent.state();
  const testMessage_1 = '__FIRST__MESSAGE__';
  const firstChange = () => {
    causeChange(mockedComponent, testMessage_1);
    return waitForIt(() => mockedComponent);
  };
  const firstResult = await firstChange();
  const firstSubmit = () => {
    mockedComponent.find('button').simulate('click');
    return waitForIt(() => mockedComponent);
  };
  const afterSubmit_1 = await firstSubmit();
  const submitState_1 = afterSubmit_1.state();
  const testMessage_2 = '__SECOND__MESSAGE__';
  const secondChange = () => {
    causeChange(mockedComponent, testMessage_2);
    return waitForIt(() => mockedComponent);
  };
  const secondResult = await secondChange();
  const secondSubmit = () => {
    mockedComponent.find('button').simulate('click');
    return waitForIt(() => mockedComponent);
  };
  const afterSubmit_2 = await secondSubmit();
  const submitState_2 = afterSubmit_2.state();
  assert(
    initialState.messages.length === 0 &&
      submitState_1.messages.length === 1 &&
      submitState_2.messages.length === 2 &&
      submitState_2.messages[1] === testMessage_2
  );
};
```

The `submitMessage` method should clear the current input.

```js
async () => {
  const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
  const waitForIt = (fn) =>
    new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100));
  const causeChange = (c, v) =>
    c.find('input').simulate('change', { target: { value: v } });
  const initialState = mockedComponent.state();
  const testMessage = '__FIRST__MESSAGE__';
  const firstChange = () => {
    causeChange(mockedComponent, testMessage);
    return waitForIt(() => mockedComponent);
  };
  const firstResult = await firstChange();
  const firstState = firstResult.state();
  const firstSubmit = () => {
    mockedComponent.find('button').simulate('click');
    return waitForIt(() => mockedComponent);
  };
  const afterSubmit = await firstSubmit();
  const submitState = afterSubmit.state();
  assert(firstState.input === testMessage && submitState.input === '');
};
```

# --seed--

## --after-user-code--

```jsx
ReactDOM.render(<DisplayMessages />, document.getElementById('root'))
```

## --seed-contents--

```jsx
class DisplayMessages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      messages: []
    }
  }
  // Add handleChange() and submitMessage() methods here

  render() {
    return (
      <div>
        <h2>Type in a new Message:</h2>
        { /* Render an input, button, and ul below this line */ }

        { /* Change code above this line */ }
      </div>
    );
  }
};
```

# --solutions--

```jsx
class DisplayMessages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      messages: []
    }
 this.handleChange = this.handleChange.bind(this);
   this.submitMessage = this.submitMessage.bind(this);
 }
  handleChange(event) {
    this.setState({
      input: event.target.value
    });
  }
  submitMessage() {
    this.setState((state) => {
      const currentMessage = state.input;
      return {
        input: '',
        messages: state.messages.concat(currentMessage)
      };
    });
  }
  render() {
    return (
      <div>
        <h2>Type in a new Message:</h2>
        <input
          value={this.state.input}
          onChange={this.handleChange}/><br/>
        <button onClick={this.submitMessage}>Submit</button>
        <ul>
          {this.state.messages.map( (message, idx) => {
              return (
                 <li key={idx}>{message}</li>
              )
            })
          }
        </ul>
      </div>
    );
  }
};
```

redpajama_set_name: RedPajamaGithub


text:
//#define BACKWARD_SYSTEN_UNKNOWN
//#define BACKWARD_HAS_UNWIND 0
//#define BACKWARD_HAS_DW 1
#define BACKWARD_HAS_BFD 1
//#define BACKWARD_CXX98

#include "backward.hpp"

#include <stdio.h>
#include "test/test.hpp"

using namespace backward;

void d(StackTrace& st)
{
	st.load_here();
}

void c(StackTrace& st)
{
	return d(st);
}

void b(StackTrace& st)
{
	return c(st);
}

__attribute__ ((noinline))
void a(StackTrace& st)
{
	return b(st);
}

TEST (smalltrace)
{
	StackTrace st;
	a(st);

	Printer printer;
	printer.print(st, stdout);
}


text:
using org.critterai.nav;
using org.critterai.nmgen;

namespace org.critterai.nmbuild
{
    /// <summary>
    /// An NMGen build context.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Holds objects related to an NMGen build during the build process.  The builder
    /// defines which assets are available at which point in the build.
    /// </para>
    /// </remarks>
    public class NMGenContext
        : BuildContext
    {
        private readonly int mTileX;
        private readonly int mTileZ;

        private readonly NMGenParams mConfig;

        private bool mNoResult;

        private Heightfield mHeightfield;
        private CompactHeightfield mCompactField;
        private ContourSet mContours;
        private PolyMesh mPolyMesh;
        private PolyMeshDetail mDetailMesh;

        /// <summary>
        /// The associated build configuation.
        /// </summary>
        public NMGenParams Config { get { return mConfig; } }

        /// <summary>
        /// The x-index of the tile within the tile grid. (x, z)
        /// </summary>
        public int TileX { get { return mTileX; } }

        /// <summary>
        /// The z-index of the tile within the tile grid. (x, z)
        /// </summary>
        public int TileZ { get { return mTileZ; } }

        /// <summary>
        /// The build has not produced a result.
        /// </summary>
        public bool NoResult
        {
            get { return mNoResult; }
            set { mNoResult = true; }
        }

        /// <summary>
        /// The heightfield.
        /// </summary>
        public Heightfield Heightfield
        {
            get { return mHeightfield; }
            set { mHeightfield = value; }
        }

        /// <summary>
        /// The compact field.
        /// </summary>
        public CompactHeightfield CompactField
        {
            get { return mCompactField; }
            set { mCompactField = value; }
        }

        /// <summary>
        /// The contour set.
        /// </summary>
        public ContourSet Contours
        {
            get { return mContours; }
            set { mContours = value; }
        }

        /// <summary>
        /// The polygon mesh.
        /// </summary>
        public PolyMesh PolyMesh
        {
            get { return mPolyMesh; }
            set { mPolyMesh = value; }
        }

        /// <summary>
        /// The detail mesh.
        /// </summary>
        public PolyMeshDetail DetailMesh
        {
            get { return mDetailMesh; }
            set { mDetailMesh = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="tx">The x-index of the tile within the tile grid. (tx, tz)</param>
        /// <param name="tz">The z-index of the tile within the tile grid. (tx, tz)</param>
        /// <param name="config">The build configuration.</param>
        public NMGenContext(int tx, int tz, NMGenParams config)
        {
            mTileX = tx;
            mTileZ = tz;

            mConfig = config;
        }

        /// <summary>
        /// Sets the context as having produced no result.
        /// </summary>
        public void SetAsNoResult()
        {
            mHeightfield = null;
            mCompactField = null;
            mContours = null;
            mPolyMesh = null;
            mDetailMesh = null;
            mNoResult = true;
        }
    }
}


text:
<?php
namespace jk204\SIMalliance\ASN1\Application\Instance;

use jk204\SIMalliance\ASN1\CommonTypes\applicationIdentifier;

class classAID extends applicationIdentifier
{

}


text:
package org.basex.query.expr.constr;

import static org.basex.query.QueryError.*;

import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.util.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;

/**
 * Abstract fragment constructor with a QName argument.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
abstract class CName extends CNode {
  /** Description. */
  private final String desc;
  /** QName. */
  Expr name;

  /**
   * Constructor.
   * @param desc description
   * @param sc static context
   * @param info input info
   * @param name name
   * @param v attribute values
   */
  CName(final String desc, final StaticContext sc, final InputInfo info, final Expr name,
      final Expr... v) {
    super(sc, info, v);
    this.name = name;
    this.desc = desc;
  }

  @Override
  public final void checkUp() throws QueryException {
    checkNoUp(name);
    super.checkUp();
  }

  @Override
  public Expr compile(final QueryContext qc, final VarScope scp) throws QueryException {
    name = name.compile(qc, scp);
    return super.compile(qc, scp);
  }

  /**
   * Returns the atomized value of the constructor.
   * @param qc query context
   * @param ii input info
   * @return resulting value
   * @throws QueryException query exception
   */
  final byte[] value(final QueryContext qc, final InputInfo ii) throws QueryException {
    final TokenBuilder tb = new TokenBuilder();
    for(final Expr e : exprs) {
      final Value v = qc.value(e);
      boolean m = false;
      for(final Item it : v.atomValue(ii)) {
        if(m) tb.add(' ');
        tb.add(it.string(ii));
        m = true;
      }
    }
    return tb.finish();
  }

  /**
   * Returns an updated name expression.
   * @param qc query context
   * @param elem element
   * @param ii input info
   * @return result
   * @throws QueryException query exception
   */
  final QNm qname(final QueryContext qc, final boolean elem, final InputInfo ii)
      throws QueryException {

    final Item it = checkNoEmpty(name.atomItem(qc, info), AtomType.QNM);
    final Type ip = it.type;
    if(ip == AtomType.QNM) return (QNm) it;
    if(!ip.isStringOrUntyped() || ip == AtomType.URI) throw STRQNM_X_X.get(info, ip, it);

    // create and update namespace
    final byte[] str = it.string(ii);
    if(XMLToken.isQName(str)) {
      return elem || Token.contains(str, ':') ? new QNm(str, sc) : new QNm(str);
    }
    throw INVNAME_X.get(info, str);
  }

  @Override
  public boolean removable(final Var var) {
    return name.removable(var) && super.removable(var);
  }

  @Override
  public final boolean has(final Flag flag) {
    return name.has(flag) || super.has(flag);
  }

  @Override
  public final boolean accept(final ASTVisitor visitor) {
    return name.accept(visitor) && visitAll(visitor, exprs);
  }

  @Override
  public final VarUsage count(final Var var) {
    return name.count(var).plus(super.count(var));
  }

  @Override
  public Expr inline(final QueryContext qc, final VarScope scp, final Var var, final Expr ex)
      throws QueryException {

    final boolean changed = inlineAll(qc, scp, exprs, var, ex);
    final Expr sub = name.inline(qc, scp, var, ex);
    if(sub != null) name = sub;
    return sub != null || changed ? optimize(qc, scp) : null;
  }

  @Override
  public final int exprSize() {
    int sz = 1;
    for(final Expr expr : exprs) sz += expr.exprSize();
    return sz + name.exprSize();
  }

  @Override
  public final void plan(final FElem plan) {
    addPlan(plan, planElem(), name, exprs);
  }

  @Override
  public final String description() {
    return info(desc);
  }

  @Override
  public final String toString() {
    return toString(desc + (name.seqType().eq(SeqType.QNM) ? " " + name : " { " + name + " }"));
  }
}


text:
<?php
namespace PolcodeProductBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class CategoryAdmin extends Admin
{
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
        ->add('name', 'text', array('label' => 'Category Name'))
        //->add('author', 'entity', array('class' => 'Acme\DemoBundle\Entity\User'))
        //->add('body') //if no type is specified, SonataAdminBundle tries to guess it
        ;
    }

    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
        ->add('name')
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
        ->addIdentifier('name')
        ;
    }
}


text:
// flowlint ambiguous-object-type:error

'use strict';

import type {IEnvironment} from 'relay-runtime';

const invariant = require('invariant');
const {useContext} = require('react');
const ReactRelayContext = require('react-relay/ReactRelayContext');

function useRelayEnvironment(): IEnvironment {
  const context = useContext(ReactRelayContext);
  invariant(
    context != null,
    'useRelayEnvironment: Expected to have found a Relay environment provided by ' +
      'a `RelayEnvironmentProvider` component. ' +
      'This usually means that useRelayEnvironment was used in a ' +
      'component that is not a descendant of a `RelayEnvironmentProvider`. ' +
      'Please make sure a `RelayEnvironmentProvider` has been rendered somewhere ' +
      'as a parent or ancestor of your component.',
  );
  return context.environment;
}

module.exports = useRelayEnvironment;


text:
#include "aggregation.h"
#include "util/algorithm.h"

template<typename T>
struct ClonableAggregationFunction:public AggregationFunction {
	virtual std::shared_ptr<AggregationFunction> clone() const {
		return std::make_shared<T>( dynamic_cast<const T&>(*this) );
	}
};
struct MaxFunction: public ClonableAggregationFunction<MaxFunction> {
	float v_=0;
	virtual void add( float v, float w=1 ){
		if(w>0)
			v_ = std::max( v_, v );
	}
	virtual float get() const{
		return v_;
	}
};
struct MinFunction: public ClonableAggregationFunction<MinFunction> {
	float v_=std::numeric_limits<float>::infinity();
	virtual void add( float v, float w=1 ){
		if(w>0)
			v_ = std::min( v_, v );
	}
	virtual float get() const{
		return v_;
	}
};
struct AvgFunction: public ClonableAggregationFunction<AvgFunction> {
	float v_=0, n_=0;
	virtual void add( float v, float w=1 ){
		v_ += w*v;
		n_ += w;
	}
	virtual float get() const{
		return v_ / (n_+1e-10);
	}
};
struct PercentileFunction: public ClonableAggregationFunction<PercentileFunction> {
	PercentileFunction( float p ):p_(p){
	}
	float p_;
	std::vector<float> v_;
	virtual void add( float v, float w=1 ){
		v_.push_back( v );
	}
	virtual float get() const{
		return quickSelect( v_, p_*(v_.size()-1)+0.5 );
	}
};
std::shared_ptr< AggregationFunction > AggregationFunction::create(const std::string &name) {
	std::string lname = name;
	std::transform( lname.begin(), lname.end(), lname.begin(), tolower );

	if( lname == "mean" || lname == "avg" )
		return std::make_shared<AvgFunction>();
	else if( lname == "min" )
		return std::make_shared<MinFunction>();
	else if( lname == "max" )
		return std::make_shared<MaxFunction>();
	else if( lname == "med" || lname == "median" )
		return std::make_shared<PercentileFunction>( 0.5 );
	else if( lname.length()>1 && lname[0] == 'p' )
		return std::make_shared<PercentileFunction>( std::stoi( lname.substr(1) ) / 100. );
	else
		throw std::invalid_argument( "Unknown aggregation function '"+name+"'!" );
}


text:
module Sherpa
  module UserstampBasic
    module MigrationHelper
      def self.included(base) # :nodoc:
        base.send(:include, InstanceMethods)
      end

      module InstanceMethods
        def userstamps(include_deleted_by = false)
          puts "creating userstamps"
          column(:creator_id, :integer)
          column(:updater_id, :integer)
          column(:deleter_id, :integer) if include_deleted_by
        end
      end
    end
  end
end
ActiveRecord::ConnectionAdapters::TableDefinition.send(:include, Sherpa::UserstampBasic::MigrationHelper)


text:
_"On heights all paths are paved with dagger -Old Seanchan saying"_

1. "a/dir/file_1.1.txt"
2. "a/dir/file_1.txt"

## Definitions:

### Array file features

#### file_paths:
Complete paths
- [0] "a/dir/file_1.1.txt"
- [1] "a/dir/file_1.txt"

#### file_suffixes:
Including first "." and everything after
- [0] ".1.txt"
- [1] ".txt"

#### file_path_prefixes:
Paths without suffix
- [0] "a/dir/file_1"
- [1] "a/dir/file_1"

#### file_names:
File names
- [0] "file_1.1.txt"
- [1] "file_1.txt"

#### file_name_prefixes:
File names without suffix
- [0] "file_1"
- [1] "file_1"

### Scalar file features

#### dir_path:
Directory path
- "a/dir/"

#### dir_path_prefix:
Directory name without trailing slash
- "a/dir"

##### file_suffix:
Everything after last "."
- ".txt"

### Constant file features

#### file_path_prefixes:
Paths without suffix
- "a/dir/file_1"

#### file_name_prefix:
File name without suffix
- "file_1"

##### file_constant_suffix:
Only for identical file_suffixes otherwise undef

For paths:
- [0] "a/dir/file.1.txt"
- [1] "a/dir/file.1.txt"

*file_constant_suffix*:
- ".1.txt"

### Hash file features

iterator: string between dots in file_suffixes, e.g. ".1.txt" => iterator = "1".

#### file_path_href:
Complete paths per iterator.
{ 1 => "a/dir/file_1.1.txt",
}

#### file_name_href:
File name per iterator.
{ 1 => "file_1.1.txt",
}


text:
1/3/17 -br

## What is it?

This is an early prototype of a real-time visualization tool
for social network data.

## Setup

1. Install node.js and npm

    Download and install procedure at http://nodejs.org

2. In a terminal window, download the software

    git clone https://github.com/billroy/jchart

3. Continuing in Terminal, install the dependencies:

    cd jchart
    npm install

## Running jchart

1. In a Terminal window, run jchart.js

    cd jchart
    node jchart.js

    (When you're done you can stop the program with Control-C)

2. Open a browser to see the application
    Open a browser to http://localhost:3000
    You should see the application start up with a blank chart

## Testing jchart

There is a simple python program that demonstrates posting a chart request
with randomized data to the server; run it a few times in a new terminal window with your eye on the browser window
to see how it works:

    cd jchart
    python test.py

For more points, run "testbig.py"

## Command Line Options

### --port=3000

Sets the http port for the jchart server.

### --logfile=none

Sets the log file name.

## Integration

### How and where to post

To generate a chart, POST an object of the following form, in JSON format,
to http://localhost:3000/xychart.  Be sure to specify the content type header
like this: "Content-type: application/json".

### JSON POST data format

Here is the general form of a chart request object:

    {
        title: "Sample data from test.py",
        banner: "job: joel26 iteration: 34 chi^2: 345.7",
        points: [
            {name: "alice", x: 100, y: 200, z: 300, color: "red"},
            {name: "bob", x: 200, y: 100, z: 300, color: "blue"},
            {name: "charlie", x: 400, y: 200, z: 300, color: "green"}
        ],
        connections: [[0,1],[0,2],[1,2]]
    }

The title is displayed by the chart module.

The banner is displayed in the web interface above the plot area; use it for
metadata about the plot.

Coordinates in the 'points' array should be in [-1000, 1000].

The connections array is optional.  If specified, it contains pairs of points
to connect with lines in the visualization.  A point is specified as 0-relative
index into the points array, so [0,1] means "connect Alice and Bob" in this
example.


text:
/**
 * Root Reducer
 */
import { combineReducers } from 'redux';

// Import Reducers
import app from './modules/App/AppReducer';
import posts from './modules/Post/PostReducer';
import intl from './modules/Intl/IntlReducer';
import series from './modules/Series/SeriesReducer';
import seriesDetail from './modules/SeriesDetail/SeriesDetailReducer';

// Combine all reducers into one root reducer
export default combineReducers({
  app,
  posts,
  intl,
  series,
  seriesDetail,
});


text:
package com.flipkart.foxtrot.core.datastore.impl.hbase;

import com.flipkart.foxtrot.common.Table;
import com.flipkart.foxtrot.core.exception.FoxtrotExceptions;
import com.flipkart.foxtrot.core.exception.FoxtrotException;
import com.flipkart.foxtrot.core.util.TableUtil;
import com.yammer.dropwizard.lifecycle.Managed;
import net.sourceforge.cobertura.CoverageIgnore;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.util.PoolMap;
import org.apache.hadoop.security.UserGroupInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * User: Santanu Sinha (santanu.sinha@flipkart.com)
 * Date: 13/03/14
 * Time: 7:35 PM
 */
@CoverageIgnore
public class HbaseTableConnection implements Managed {
    private static final Logger logger = LoggerFactory.getLogger(HbaseTableConnection.class.getSimpleName());

    private final HbaseConfig hbaseConfig;
    private HTablePool tablePool;
    private HBaseAdmin hBaseAdmin;

    public HbaseTableConnection(HbaseConfig hbaseConfig) {
        this.hbaseConfig = hbaseConfig;
    }

    public synchronized HTableInterface getTable(final Table table) throws FoxtrotException {
        try {
            if (hbaseConfig.isSecure() && UserGroupInformation.isSecurityEnabled()) {
                UserGroupInformation.getCurrentUser().reloginFromKeytab();
            }
            return tablePool.getTable(TableUtil.getTableName(hbaseConfig, table));
        } catch (Exception e) {
            throw FoxtrotExceptions.createConnectionException(table, e);
        }
    }

    public synchronized boolean isTableAvailable(final Table table) throws IOException {
        String tableName = TableUtil.getTableName(hbaseConfig, table);
        return hBaseAdmin.isTableAvailable(tableName);
    }

    public String getHBaseTableName(final Table table) throws IOException {
        return TableUtil.getTableName(hbaseConfig, table);
    }

    @Override
    public void start() throws Exception {
        logger.info("Starting HBase Connection");
        Configuration configuration = HBaseUtil.create(hbaseConfig);
        this.tablePool = new HTablePool(configuration, 10, PoolMap.PoolType.Reusable);
        this.hBaseAdmin = new HBaseAdmin(configuration);
        logger.info("Started HBase Connection");
    }

    @Override
    public void stop() throws Exception {
        tablePool.close();
    }

    public HbaseConfig getHbaseConfig() {
        return hbaseConfig;
    }
}


text:
import Properties from '../../core/ext/Properties';
import WebServer from './WebServer';
import { Request, Response, Application } from './WebServer';
declare class Endpoint extends Properties {
    type: string;
    method: string;
    children: Endpoint[];
    app: Application;
    server: WebServer;
    route: string;
    order: number;
    validate: (req: Request, res: Response) => any;
    handleAs: string;
    parserOptions: any;
    on(eventType: string, callback: (ev: any) => void): any;
    emit(eventType: string, data: any): any;
    handler(req: Request, res: Response, next?: () => void): void;
    constructor(args: any);
}
export { Endpoint };
export default Endpoint;


text:
using System;
using System.Collections.Generic;
using bv.common.Configuration;
using bv.common.Core;
using bv.model.Model.Core;
using eidss.model.Core;
using eidss.model.Enums;

namespace eidss.model.Reports.Common
{
    [Serializable]
    public class BaseModel
    {
        public BaseModel()
        {
            CanWorkWithArchive = true;
        }

        public BaseModel(string language, bool useArchive)
        {
            Utils.CheckNotNullOrEmpty(language, "lang");

            Language = language;
            UseArchive = useArchive;

            CanWorkWithArchive = true;
        }

        public BaseModel(string language, string exportFormat, bool useArchive, bool isOpenInNewWindow)
        {
            Utils.CheckNotNullOrEmpty(language, "lang");
            Utils.CheckNotNullOrEmpty(exportFormat, "exportFormat");

            Language = language;
            ExportFormat = exportFormat;
            UseArchive = useArchive;
            IsOpenInNewWindow = isOpenInNewWindow;
        }

        [LocalizedDisplayName("PreferredLanguage")]
        public string Language { get; set; }

        [LocalizedDisplayName("ExportTo")]
        public string ExportFormat { get; set; }

        public ReportExportType ExportFormatEnum
        {
            get
            {
                ReportExportType result;
                if (!Enum.TryParse(ExportFormat, out result))
                {
                    result = ReportExportType.Pdf;
                }
                return result;
            }
        }

        [LocalizedDisplayName("UseArchive")]
        public bool UseArchive { get; set; }

        public bool IsOpenInNewWindow { get; set; }

        public List<PersonalDataGroup> ForbiddenGroups { get; set; }

        public long? OrganizationId { get; set; }

        public bool CanWorkWithArchive { get; set; }

        public bool ShowUseArchiveDataCheckbox
        {
            get
            {
                bool hasPermission =
                    EidssUserContext.User.HasPermission(PermissionHelper.ExecutePermission(EIDSSPermissionObject.CanReadArchivedData));
                var credentials = new ConnectionCredentials(null, "Archive");

                return CanWorkWithArchive &&
                       !ModelUserContext.Instance.IsArchiveMode &&
                       hasPermission &&
                       credentials.IsCorrect;
            }
        }

        protected string CurrentCultureName
        {
            get
            {
                string cultureName = Localizer.SupportedLanguages.ContainsKey(Language)
                                         ? Localizer.SupportedLanguages[Language]
                                         : "en-US";
                return cultureName;
            }
        }

        public List<SelectListItemSurrogate> SupportedLanguages
        {
            get { return FilterHelper.GetSupportedLanguages(); }
        }

        public List<SelectListItemSurrogate> SupportedExportFormats
        {
            get { return FilterHelper.GetExportFormats(); }
        }

        public override string ToString()
        {
            return string.Format("Language:{0}, Format:{1}, UseArchive:{2}", Language, ExportFormatEnum, UseArchive);
        }
    }
}


text:
gokn
=========

A simple rest framework for developing go apps. ver 0.1

This framework is in the early stages and it subject to breaking changes as it evolves until it reaches a stable place.


text:
layout: default
title: Hank Quinlan, Horrible Cop
---

Hi there, I'm Hank Quinlan!

I'm best known as the horrible cop from A Touch of Evil Don't trust me. Read more about my life...

	from Jekyll build


text:
package com.guoxiaoxing.baselib.injection;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.inject.Scope;

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}


text:
#include <petscviewerhdf5.h>

#include <petibm/delta.h>
#include <petibm/io.h>

#include "ibpm.h"

IBPMSolver::IBPMSolver(const MPI_Comm &world,
                       const YAML::Node &node)
{
    init(world, node);
}  // IBPMSolver

IBPMSolver::~IBPMSolver()
{
    PetscErrorCode ierr;
    PetscBool finalized;

    PetscFunctionBeginUser;

    ierr = PetscFinalized(&finalized); CHKERRV(ierr);
    if (finalized) return;

    ierr = destroy(); CHKERRV(ierr);
}  // ~IBPMSolver

// manual destroy data
PetscErrorCode IBPMSolver::destroy()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    bodies.reset();
    ierr = ISDestroy(&isDE[0]); CHKERRQ(ierr);
    ierr = ISDestroy(&isDE[1]); CHKERRQ(ierr);
    ierr = VecResetArray(P); CHKERRQ(ierr);
    ierr = VecDestroy(&P); CHKERRQ(ierr);
    ierr = PetscViewerDestroy(&forcesViewer); CHKERRQ(ierr);
    ierr = NavierStokesSolver::destroy(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // destroy

PetscErrorCode IBPMSolver::init(const MPI_Comm &world, const YAML::Node &node)
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    // create a pack of immersed bodies
    PetscInt dim = node["mesh"].size();
    ierr = petibm::body::createBodyPack(
        world, dim, node, bodies); CHKERRQ(ierr);

    ierr = NavierStokesSolver::init(world, node); CHKERRQ(ierr);

    ierr = PetscLogStagePush(stageInitialize); CHKERRQ(ierr);

    // create an ASCII PetscViewer to output the body forces
    ierr = createPetscViewerASCII(
        config["output"].as<std::string>() +
        "/forces-" + std::to_string(ite) + ".txt",
        FILE_MODE_WRITE, forcesViewer); CHKERRQ(ierr);

    // register additional logging stage
    ierr = PetscLogStageRegister(
        "integrateForces", &stageIntegrateForces); CHKERRQ(ierr);

    ierr = PetscLogStagePop(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // init

// write solution fields, linear solvers info, and body forces to files
PetscErrorCode IBPMSolver::write()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    ierr = NavierStokesSolver::write(); CHKERRQ(ierr);

    // write body forces
    ierr = writeForcesASCII(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // write

// create the linear operators of the solver (PETSc Mat objects)
PetscErrorCode IBPMSolver::createOperators()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    Mat R, MHat, BN, GH[2], DE[2];  // temporary operators
    Vec RDiag, MHatDiag;            // temporary vectors
    IS is[2];                       // temporary index sets

    // create the divergence operator: D
    ierr = petibm::operators::createDivergence(
        mesh, bc, DE[0], DCorrection, PETSC_FALSE); CHKERRQ(ierr);

    // create the gradient operator: G
    ierr = petibm::operators::createGradient(
        mesh, GH[0], PETSC_FALSE); CHKERRQ(ierr);

    // create the Laplacian operator: L
    ierr = petibm::operators::createLaplacian(
        mesh, bc, L, LCorrection); CHKERRQ(ierr);

    // create the operator for the convective terms: N
    ierr = petibm::operators::createConvection(
        mesh, bc, N); CHKERRQ(ierr);

    // create the implicit operator for the velocity system: A
    ierr = MatDuplicate(L, MAT_COPY_VALUES, &A); CHKERRQ(ierr);
    ierr = MatScale(A, -diffCoeffs->implicitCoeff * nu); CHKERRQ(ierr);
    ierr = MatShift(A, 1.0 / dt); CHKERRQ(ierr);

    // create diagonal matrix R and hold the diagonal in a PETSc Vec object
    ierr = petibm::operators::createR(mesh, R); CHKERRQ(ierr);
    ierr = MatCreateVecs(R, nullptr, &RDiag); CHKERRQ(ierr);
    ierr = MatGetDiagonal(R, RDiag); CHKERRQ(ierr);

    // create diagonal matrix MHat and hold the diagonal in a PETSc Vec object
    ierr = petibm::operators::createMHead(mesh, MHat); CHKERRQ(ierr);
    ierr = MatCreateVecs(MHat, nullptr, &MHatDiag); CHKERRQ(ierr);
    ierr = MatGetDiagonal(MHat, MHatDiag); CHKERRQ(ierr);

    // create a Delta operator and its transpose (equal to H)
    ierr = bodies->updateMeshIdx(mesh); CHKERRQ(ierr);
    const YAML::Node &node = config["parameters"];
    std::string name = node["delta"].as<std::string>("ROMA_ET_AL_1999");
    petibm::delta::DeltaKernel kernel;
    PetscInt kernelSize;
    ierr = petibm::delta::getKernel(name, kernel, kernelSize); CHKERRQ(ierr);
    ierr = petibm::operators::createDelta(
        mesh, bc, bodies, kernel, kernelSize, DE[1]); CHKERRQ(ierr);
    ierr = MatTranspose(DE[1], MAT_INITIAL_MATRIX, &GH[1]); CHKERRQ(ierr);

    // create the regularization operator: E
    ierr = MatDiagonalScale(DE[1], nullptr, RDiag); CHKERRQ(ierr);
    ierr = MatDiagonalScale(DE[1], nullptr, MHatDiag); CHKERRQ(ierr);
    ierr = VecDestroy(&RDiag); CHKERRQ(ierr);
    ierr = VecDestroy(&MHatDiag); CHKERRQ(ierr);
    ierr = MatDestroy(&R); CHKERRQ(ierr);
    ierr = MatDestroy(&MHat); CHKERRQ(ierr);

    // create the opposite of the spreading operator: -H
    ierr = MatScale(GH[1], -1.0); CHKERRQ(ierr);

    // get combined operator G; R is used temporarily
    ierr = MatCreateNest(
        comm, 1, nullptr, 2, nullptr, GH, &R); CHKERRQ(ierr);
    ierr = MatConvert(R, MATAIJ, MAT_INITIAL_MATRIX, &G); CHKERRQ(ierr);
    ierr = MatDestroy(&R); CHKERRQ(ierr);
    ierr = MatDestroy(&GH[0]); CHKERRQ(ierr);
    ierr = MatDestroy(&GH[1]); CHKERRQ(ierr);

    // get combined operator D; R is used temporarily; also get ISs
    ierr = MatCreateNest(
        comm, 2, nullptr, 1, nullptr, DE, &R); CHKERRQ(ierr);
    ierr = MatConvert(R, MATAIJ, MAT_INITIAL_MATRIX, &D); CHKERRQ(ierr);
    ierr = MatNestGetISs(R, is, nullptr); CHKERRQ(ierr);
    ierr = ISDuplicate(is[0], &isDE[0]); CHKERRQ(ierr);
    ierr = ISDuplicate(is[1], &isDE[1]); CHKERRQ(ierr);
    ierr = ISCopy(is[0], isDE[0]); CHKERRQ(ierr);
    ierr = ISCopy(is[1], isDE[1]); CHKERRQ(ierr);
    ierr = MatDestroy(&R); CHKERRQ(ierr);
    ierr = MatDestroy(&DE[0]); CHKERRQ(ierr);
    ierr = MatDestroy(&DE[1]); CHKERRQ(ierr);

    // create the projection operator: BNG
    PetscInt N;  // order of the truncate Taylor series expansion
    N = config["parameters"]["BN"].as<PetscInt>(1);
    ierr = petibm::operators::createBnHead(
        L, dt, diffCoeffs->implicitCoeff * nu, N, BN); CHKERRQ(ierr);
    ierr = MatMatMult(
        BN, G, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &BNG); CHKERRQ(ierr);

    // create the modified Poisson operator
    ierr = MatMatMult(
        D, BNG, MAT_INITIAL_MATRIX, PETSC_DEFAULT, &DBNG); CHKERRQ(ierr);

    // set the nullspace of the modified Poisson system
    ierr = setNullSpace(); CHKERRQ(ierr);

    // destroy temporary operator
    ierr = MatDestroy(&BN); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // createOperators

// create the vectors of the solver (PETSc Vec objects)
PetscErrorCode IBPMSolver::createVectors()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    Vec temp;
    const PetscReal *data;

    // create the vector of the couple (pressure field, Lagrangian forces)
    ierr = MatCreateVecs(G, &P, nullptr); CHKERRQ(ierr);

    // swap pGlobal and P to reuse functions from the Navier-Stokes solver
    temp = solution->pGlobal;
    solution->pGlobal = P;
    P = temp;
    temp = PETSC_NULL;

    // destroy P's underlying raw array but keep all other information
    ierr = VecReplaceArray(P, nullptr); CHKERRQ(ierr);

    // reset the underlying data of P to the pressure portion in pGlobal
    ierr = VecGetSubVector(solution->pGlobal, isDE[0], &temp); CHKERRQ(ierr);
    ierr = VecGetArrayRead(temp, &data); CHKERRQ(ierr);
    ierr = VecPlaceArray(P, data); CHKERRQ(ierr);
    ierr = VecRestoreArrayRead(temp, &data); CHKERRQ(ierr);
    ierr = VecRestoreSubVector(
        solution->pGlobal, isDE[0], &temp); CHKERRQ(ierr);

    // create remaining vectors
    ierr = NavierStokesSolver::createVectors(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // createVectors

// set the nullspace of the modified Poisson system
PetscErrorCode IBPMSolver::setNullSpace()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    std::string type;
    ierr = pSolver->getType(type); CHKERRQ(ierr);

    if (type == "PETSc KSP")
    {
        Vec n, phiPortion;
        MatNullSpace nsp;
        ierr = MatCreateVecs(DBNG, &n, nullptr); CHKERRQ(ierr);
        ierr = VecSet(n, 0.0); CHKERRQ(ierr);
        ierr = VecGetSubVector(n, isDE[0], &phiPortion); CHKERRQ(ierr);
        ierr = VecSet(phiPortion, 1.0 / std::sqrt(mesh->pN)); CHKERRQ(ierr);
        ierr = VecRestoreSubVector(n, isDE[0], &phiPortion); CHKERRQ(ierr);
        ierr = MatNullSpaceCreate(
            comm, PETSC_FALSE, 1, &n, &nsp); CHKERRQ(ierr);
        ierr = MatSetNullSpace(DBNG, nsp); CHKERRQ(ierr);
        ierr = MatSetNearNullSpace(DBNG, nsp); CHKERRQ(ierr);
        ierr = VecDestroy(&n); CHKERRQ(ierr);
        ierr = MatNullSpaceDestroy(&nsp); CHKERRQ(ierr);
        isRefP = PETSC_FALSE;
    }
    else if (type == "NVIDIA AmgX")
    {
        PetscInt row[1] = {0};
        ierr = MatZeroRowsColumns(
            DBNG, 1, row, 1.0, nullptr, nullptr); CHKERRQ(ierr);
        isRefP = PETSC_TRUE;
    }
    else
    {
        SETERRQ1(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
                 "Could not recognize the type of linear solver: %s\n",
                 type.c_str());
    }

    PetscFunctionReturn(0);
}  // setNullSpace

// assemble the right-hand side vector of the modified Poisson system
PetscErrorCode IBPMSolver::assembleRHSPoisson()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    ierr = PetscLogStagePush(stageRHSPoisson); CHKERRQ(ierr);

    // compute the divergence of the intermediate velocity field
    ierr = MatMult(D, solution->UGlobal, rhs2); CHKERRQ(ierr);

    // note: bc2 is a subset of rhs2
    Vec bc2;
    ierr = VecGetSubVector(rhs2, isDE[0], &bc2); CHKERRQ(ierr);
    ierr = MatMultAdd(DCorrection, solution->UGlobal, bc2, bc2); CHKERRQ(ierr);
    ierr = VecRestoreSubVector(rhs2, isDE[0], &bc2); CHKERRQ(ierr);

    if (isRefP)  // if the pressure is pinned at one point
    {
        ierr = VecSetValue(rhs2, 0, 0.0, INSERT_VALUES); CHKERRQ(ierr);
        ierr = VecAssemblyBegin(rhs2); CHKERRQ(ierr);
        ierr = VecAssemblyEnd(rhs2); CHKERRQ(ierr);
    }

    ierr = PetscLogStagePop(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // assembleRHSPoisson

// write the solution fields into a HDF5 file
PetscErrorCode IBPMSolver::writeSolutionHDF5(const std::string &filePath)
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    Vec temp = PETSC_NULL;

    // let solution->pGlobal point to P, so that we can use solution->write
    temp = solution->pGlobal;
    solution->pGlobal = P;

    ierr = NavierStokesSolver::writeSolutionHDF5(filePath); CHKERRQ(ierr);

    // restore pointers
    solution->pGlobal = temp;
    temp = PETSC_NULL;

    PetscFunctionReturn(0);
}  // writeSolutionHDF5

// write all data required to restart a simulation into a HDF5 file
PetscErrorCode IBPMSolver::writeRestartDataHDF5(const std::string &filePath)
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    ierr = NavierStokesSolver::writeRestartDataHDF5(filePath); CHKERRQ(ierr);

    // write forces
    Vec f;
    ierr = VecGetSubVector(solution->pGlobal, isDE[1], &f); CHKERRQ(ierr);
    ierr = petibm::io::writeHDF5Vecs(
        comm, filePath, "/", {"force"}, {f}, FILE_MODE_APPEND); CHKERRQ(ierr);
    ierr = VecRestoreSubVector(solution->pGlobal, isDE[1], &f); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // writeRestartDataHDF5

// read all data required to restart a simulation into a HDF5 file
PetscErrorCode IBPMSolver::readRestartDataHDF5(const std::string &filePath)
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    Vec temp = PETSC_NULL;

    // let solution->pGlobal point to P, so that we can use solution->write
    temp = solution->pGlobal;
    solution->pGlobal = P;

    ierr = NavierStokesSolver::readRestartDataHDF5(filePath); CHKERRQ(ierr);

    // restore pointers
    solution->pGlobal = temp;
    temp = PETSC_NULL;

    // write forces
    std::vector<Vec> f(1);
    ierr = VecGetSubVector(solution->pGlobal, isDE[1], &f[0]); CHKERRQ(ierr);
    ierr = petibm::io::readHDF5Vecs(
        comm, filePath, "/", {"force"}, f); CHKERRQ(ierr);
    ierr = VecRestoreSubVector(
        solution->pGlobal, isDE[1], &f[0]); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // readRestartDataHDF5

// integrate the forces and output to ASCII file
PetscErrorCode IBPMSolver::writeForcesASCII()
{
    PetscErrorCode ierr;
    petibm::type::RealVec2D fAvg;

    PetscFunctionBeginUser;

    ierr = PetscLogStagePush(stageIntegrateForces); CHKERRQ(ierr);

    // get sub section f and calculate averaged forces
    Vec f;
    ierr = VecGetSubVector(solution->pGlobal, isDE[1], &f); CHKERRQ(ierr);
    ierr = bodies->calculateAvgForces(f, fAvg); CHKERRQ(ierr);
    ierr = VecRestoreSubVector(solution->pGlobal, isDE[1], &f); CHKERRQ(ierr);

    ierr = PetscLogStagePop(); CHKERRQ(ierr);

    ierr = PetscLogStagePush(stageWrite); CHKERRQ(ierr);

    // write the time value
    ierr = PetscViewerASCIIPrintf(forcesViewer, "%10.8e\t", t); CHKERRQ(ierr);

    // write forces for each immersed body
    for (int i = 0; i < bodies->nBodies; ++i)
    {
        for (int d = 0; d < mesh->dim; ++d)
        {
            ierr = PetscViewerASCIIPrintf(
                forcesViewer, "%10.8e\t", fAvg[i][d]); CHKERRQ(ierr);
        }
    }
    ierr = PetscViewerASCIIPrintf(forcesViewer, "\n"); CHKERRQ(ierr);

    ierr = PetscLogStagePop(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // writeForcesASCII


text:
Create a new flat-share

        <form class="form-horizontal" data-ng-submit="create()" novalidate>
            <fieldset>

                    Name

                        <input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>

                    Street

                        <input type="text" data-ng-model="street" id="street" class="form-control" placeholder="Street" required>

                    House number

                        <input type="text" data-ng-model="number" id="number" class="form-control" placeholder="Number" required>

                    ZIP code

                        <input type="text" data-ng-model="zip" id="zip" class="form-control" placeholder="ZIP Code" required>

                    City

                        <input type="text" data-ng-model="city" id="city" class="form-control" placeholder="City" required>

                    Country

                        <input type="text" data-ng-model="country" id="country" class="form-control" placeholder="Country" required>

                    <button type="submit" class="btn btn-primary">Create</button>

            </fieldset>
        </form>


text:
typedef unsigned int	hash_t;
// Must be unsigned, otherwise the hash algorithm won't be very useful!

// tree node structure type definition (for easy lookups)
struct node_t {
	node_t*		greater_than;	// pointer to sub-tree
	node_t*		less_than_or_equal;// pointer to sub-tree
	hash_t		hash_value;
	const char*	id_string;	// name, zero-terminated
	void*		body;		// bytes, handles or handler function
};

// tree node structure type definition (for macros/labels)
struct node_ra_t {
	node_ra_t*	greater_than;	// pointer to sub-tree
	node_ra_t*	less_than_or_equal;// pointer to sub-tree
	hash_t		hash_value;
	char*		id_string;	// name, zero-terminated
	void*		body;		// macro/label body
	unsigned int	id_number;	// zone number
};

// Prototypes
extern void	Tree_add_table(node_t** tree, node_t* table_to_add);
extern bool	Tree_easy_scan(node_t* tree, void** node_body, struct dynabuf_t* dyna_buf);
extern bool	Tree_hard_scan(node_ra_t**, node_ra_t**, int, bool);
extern void	Tree_dump_forest(node_ra_t**, int, void (*)(node_ra_t*, FILE*), FILE*);

#endif


text:
package app.domain.user;

import app.domain.Id;
import lombok.ToString;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.Objects;

/**
 * ユーザー.
 */
@Entity
@Table(name="users")
@ToString
public class User implements Serializable {
    @EmbeddedId
    private Id<User> id;
    @Embedded @Valid
    private LoginId loginId;
    @Embedded @Valid
    @AttributeOverride(name="value", column=@Column(name="name"))
    private UserName name;
    @Embedded @Valid
    private Password password;
    @Embedded @Valid
    private MailAddress mailAddress;

    public User(LoginId loginId, UserName name) {
        this.loginId = Objects.requireNonNull(loginId, "ログインIDに null は指定できません");
        this.name = Objects.requireNonNull(name, "ユーザー名に null は指定できません");
        this.password = Password.newPassword();
    }

    /**
     * このユーザが持つパスワードと指定した平文のパスワードが等しいか検証します.
     * @param plainPassword 平文のパスワード
     * @return パスワードが等しい場合は true
     */
    public boolean isValidPassword(String plainPassword) {
        return this.password.isEquals(plainPassword);
    }

    public void setMailAddress(MailAddress mailAddress) {
        this.mailAddress = mailAddress;
    }

    public void setName(UserName name) {
        this.name = Objects.requireNonNull(name);
    }

    public void setPassword(Password password) {
        this.password = Objects.requireNonNull(password);
    }

    @PrePersist
    private void setupId() {
        this.id = new Id<User>(-1L);
    }

    @Deprecated
    protected User() {}

    public String getLoginIdAsString() {
        return this.loginId.asString();
    }

    public String getUserNameAsString() {
        return this.name.asString();
    }
}


text:
require_relative "spacer"
require_relative "executioner"
require_relative "savior"
require_relative "hunter"
require_relative "connector"
require_relative "pusher"
require_relative "no_easy_prisoner"

class Heuristic
  def Heuristic.all_heuristics
    return [Spacer, Executioner, Savior, Hunter, Connector, Pusher, NoEasyPrisoner]
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Res. 100(12): 1493 (1996)

#### Original name
Trimmatostroma variabile Goh & Yipp

### Remarks
null


text:
"""
Command line object for PSICOV contact prediction application
"""

__author__ = "Felix Simkovic"
__date__ = "04 Aug 2016"
__version__ = "0.13.3"

from Bio.Application import _Argument
from Bio.Application import _Option
from Bio.Application import _Switch
from Bio.Application import AbstractCommandline

class PsicovCommandline(AbstractCommandline):
    """
    Command line object for PSICOV [#]_ contact prediction application

    http://bioinfadmin.cs.ucl.ac.uk/downloads/PSICOV/

    The PSICOV program is a Accurate Contact Prediction from large
    protein alignments.

    .. [#] Jones, D.T., Buchan, D.W., Cozzetto, D. & Pontil, M. (2012). PSICOV:
       Precise structural contact prediction using sparse inverse covariance
       estimation on large multiple sequence alignments. Bioinformatics. 28, 184-190.

    Examples
    --------
    To predict a contact map using a Multiple Sequence Alignment in
    JONES format, use:

    >>> from conkit.applications import PsicovCommandline
    >>> psicov_cline = PsicovCommandline(alnfile="test.aln")
    >>> print(ccmpred_cline)
    psicov test.aln

    You would typically run the command line with :func:`psicov_cline` or via
    the :mod:`~subprocess` module.

    """

    def __init__(self, cmd="psicov", **kwargs):
        self.parameters = [
            _Switch(["-a", "lasso"], "use approximate Lasso algorithm"),
            _Switch(["-n", "noshrink"], "don't pre-shrink the sample covariance matrix"),
            _Switch(["-f", "filter"], "filer low-scoring contacts"),
            _Switch(["-p", "ppv_output"], "output PPV estimates rather than raw scores"),
            _Switch(["-l", "noapc"], "don't apply APC to Lasso output"),
            _Option(["-r", "rho"], "set initial rho paramter", equate=False),
            _Option(
                ["-d", "sparsity"], "set target precision matrix sparsity [default: 0; not specified]", equate=False
            ),
            _Option(["-t", "convergence_threshold"], "set Lasso convergence threshold [default: 1e-4]", equate=False),
            _Option(
                ["-i", "blosum_weighting"],
                "select BLOSUM-like weighting with given identity threshold "
                "[default selects threshold automatically]",
                equate=False,
            ),
            _Option(["-c", "pseudocount"], "set pseudocount value [default: 1]", equate=False),
            _Option(["-j", "sequence_separation"], "set minimum sequence sparation [default: 5]", equate=False),
            _Option(["-g", "gap_fraction"], "set maximum fraction of gaps [default: 0.9]", equate=False),
            _Option(["-z", "nr_threads"], "set maximum number of threads", equate=False),
            _Option(["-b", "rho_parameter_file"], "read rho parameter file", filename=True, equate=False),
            _Argument(["alnfile"], "Input alignment file [JONES format]", filename=True, is_required=True),
        ]
        AbstractCommandline.__init__(self, cmd, **kwargs)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>MTurk Study</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="styles.css" rel="stylesheet" type="text/css">

Total Score: 0

Game Score: 0

  <canvas id="canvas" width="400" height="400" onclick="gamerun()"
  style="background-color: black; text-align: center;"></canvas>

You died! Click to restart.

New round! Click to restart.

  <button class="door" id="bedroom_door">Bedroom</button>
  <button class="door" id="kitchen_door">Kitchen</button>
  <button class="door" id="livingroom_door">Living Room</button>
  <button class="door" id="bathroom_door">Bathroom</button>

  <button class="backbutton" id="back_button"
 >Return to game</button>

Art thanks to
  Viscious-Speed

  <button class="roombutton" id="chestleft" onClick="falseTouch('chestLeft')"></button>
  <button class="roombutton" id="chestright" onClick="falseTouch('chestRight')"></button>
  <button class="roombutton" id="alarmclock" onClick="falseTouch('alarmclock')"></button>
  <button class="roombutton" id="bed" onClick="falseTouch('bed')"></button>
  <button class="roombutton" id="phone_bedroom" onClick="falseTouch('telephone')"></button>
  <button class="roombutton" id="window" onClick="falseTouch('window')"></button>
  <button class="roombutton" id="mirror" onClick="falseTouch('mirror')"></button>
  <button class="roombutton" id="luggage" onClick="falseTouch('luggage')"></button>

  <button class="roombutton" id="dishwasher" onClick="falseTouch('dishwasher')"></button>
  <button class="roombutton" id="cabinet" onClick="falseTouch('cabinet')"></button>
  <button class="roombutton" id="stove" onClick="falseTouch('stove')"></button>
  <button class="roombutton" id="cuttingboard" onClick="falseTouch('cuttingboard')"></button>
  <button class="roombutton" id="knife" onClick="falseTouch('knife')"></button>
  <button class="roombutton" id="fridge" onClick="falseTouch('fridge')"></button>
  <button class="roombutton" id="freezer" onClick="falseTouch('freezer')"></button>
  <button class="roombutton" id="plant1" onClick="falseTouch('plant1')"></button>
  <button class="roombutton" id="microwave" onClick="falseTouch('microwave')"></button>
  <button class="roombutton" id="toaster" onClick="falseTouch('toaster')"></button>
  <button class="roombutton" id="kettle" onClick="falseTouch('kettle')"></button>
  <button class="roombutton" id="sink" onClick="falseTouch('sink')"></button>
  <button class="roombutton" id="soap" onClick="falseTouch('soap')"></button>
  <button class="roombutton" id="littlepot" onClick="falseTouch('littlepot')"></button>
  <button class="roombutton" id="bigpot" onClick="falseTouch('bigpot')"></button>

  <button class="roombutton" id="grandfatherclock" onClick="falseTouch('grandfatherclock')"></button>
  <button class="roombutton" id="fire" onClick="touchTheFire()"></button>
  <button class="roombutton" id="pictureframe" onClick="falseTouch('pictureframe')"></button>
  <button class="roombutton" id="encyclopedia" onClick="falseTouch('encyclopedia')"></button>
  <button class="roombutton" id="speaker" onClick="falseTouch('speaker')"></button>
  <button class="roombutton" id="television" onClick="touchTelevision()"></button>
  <button class="roombutton" id="plant2" onClick="falseTouch('plant2')"></button>
  <button class="roombutton" id="plant3" onClick="falseTouch('plant3')"></button>

  <button class="roombutton" id="toiletbrush" onClick="falseTouch('toiletbrush')"></button>
  <button class="roombutton" id="toilet" onClick="falseTouch('toilet')"></button>
  <button class="roombutton" id="shampoo" onClick="falseTouch('shampoo')"></button>
  <button class="roombutton" id="bathtub" onClick="falseTouch('bathtub')"></button>
  <button class="roombutton" id="bathrobe" onClick="falseTouch('bathrobe')"></button>
  <button class="roombutton" id="toothbrush" onClick="falseTouch('toothbrush')"></button>
  <button class="roombutton" id="hairdryer" onClick="falseTouch('hairdryer')"></button>
  <button class="roombutton" id="leftsink" onClick="falseTouch('leftsink')"></button>
  <button class="roombutton" id="rightsink" onClick="falseTouch('rightsink')"></button>
  <button class="roombutton" id="medicine" onClick="falseTouch('medicine')"></button>
  <button class="roombutton" id="plant4" onClick="falseTouch('plant4')"></button>
  <button class="roombutton" id="plant5" onClick="falseTouch('plant5')"></button>
  <button class="roombutton" id="plant6" onClick="falseTouch('plant6')"></button>

  <input type="button" class="continueButton"
  onclick="location.href='game_round.html?session='+sessionID+'&code='+code+'&round=1';return false;" value="Continue" />


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"

       default-init-method="initialize"
       default-destroy-method="destroy">

    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"
        p:placeholderPrefix="%{" p:placeholderSuffix="}" />

    <bean class="net.shibboleth.ext.spring.config.IdentifiableBeanPostProcessor" />
    <bean class="net.shibboleth.idp.profile.impl.ProfileActionBeanPostProcessor" />

    <import resource="../../../conf/intercept/context-check-intercept-config.xml" />

    <alias name="shibboleth.context-check.Condition" alias="ContextCheckPredicate"/>

</beans>


text:
NS_ASSUME_NONNULL_BEGIN

@interface UIColor (TransformColor)

+ (nonnull UIColor *)colorTransformFrom:(nonnull UIColor *)fromColor to:(nonnull UIColor *)toColor progress:(CGFloat)progress;

@end

NS_ASSUME_NONNULL_END


text:
import Vue from 'vue'

import ListenersMixin from '../../mixins/listeners.js'

import { slot } from '../../utils/slot.js'

export default Vue.extend({
  name: 'QPage',

  mixins: [ ListenersMixin ],

  inject: {
    pageContainer: {
      default () {
        console.error('QPage needs to be child of QPageContainer')
      }
    },
    layout: {}
  },

  props: {
    padding: Boolean,
    styleFn: Function
  },

  computed: {
    style () {
      const offset =
        (this.layout.header.space === true ? this.layout.header.size : 0) +
        (this.layout.footer.space === true ? this.layout.footer.size : 0)

      if (typeof this.styleFn === 'function') {
        const height = this.layout.container === true
          ? this.layout.containerHeight
          : this.$q.screen.height

        return this.styleFn(offset, height)
      }

      return {
        minHeight: this.layout.container === true
          ? (this.layout.containerHeight - offset) + 'px'
          : (
            this.$q.screen.height === 0
              ? `calc(100vh - ${offset}px)`
              : (this.$q.screen.height - offset) + 'px'
          )
      }
    },

    classes () {
      if (this.padding === true) {
        return 'q-layout-padding'
      }
    }
  },

  render (h) {
    return h('main', {
      staticClass: 'q-page',
      style: this.style,
      class: this.classes,
      on: { ...this.qListeners }
    }, slot(this, 'default'))
  }
})


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Instructions</title>
<link href="../Learn_section.css" rel="stylesheet" type="text/css" />

    This is a sample study intended to be used to give examples of how to setup your own study.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace NBitcoin.Tests
{
    [JsonArray]
    public class TestCase : List<object>
    {
        public T GetValue<T>(int i)
        {
            return (T)Convert.ChangeType(this[i], typeof(T));
        }

        public dynamic GetDynamic(int i)
        {
            return this[i];
        }

        public static TestCase[] read_json(string fileName)
        {
            using(FileStream fs = File.Open(fileName, FileMode.Open))
            {
                var seria = new JsonSerializer();
                var result = (TestCase[])seria.Deserialize(new StreamReader(fs), typeof(TestCase[]));
                for(int i = 0; i < result.Length; i++)
                {
                    result[i].Index = i;
                }
                return result;
            }
        }

        public override string ToString()
        {
            return "[" + String.Join(",", this.Select(s => Convert.ToString(s)).ToArray()) + "]";
        }

        public int Index
        {
            get;
            set;
        }
    }
}


text:
package io.bootique.jersey.beanvalidation;

import io.bootique.ConfigModule;
import io.bootique.di.Binder;

/**
 * @since 2.0
 */
public class JerseyBeanValidationModule extends ConfigModule {

    public static JerseyBeanValidationModuleExtender extend(Binder binder) {
        return new JerseyBeanValidationModuleExtender(binder);
    }

    @Override
    public void configure(Binder binder) {
        extend(binder);
    }
}


text:
package org.jabref.logic.importer.fetcher.isbntobibtex;

import java.util.Optional;

import org.jabref.logic.importer.FetcherClientException;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.fetcher.AbstractIsbnFetcherTest;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.testutils.category.FetcherTest;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;

@FetcherTest
public class DoiToBibtexConverterComIsbnFetcherTest extends AbstractIsbnFetcherTest {

    @BeforeEach
    public void setUp() {
        bibEntryEffectiveJava = new BibEntry(StandardEntryType.Book)
                .withField(StandardField.TITLE, "Effective Java(TM) Programming Language Guide (2nd Edition) (The Java Series)")
                .withField(StandardField.PUBLISHER, "Prentice Hall PTR")
                .withField(StandardField.YEAR, "2007")
                .withField(StandardField.AUTHOR, "Bloch, Joshua")
                .withField(StandardField.ISBN, "9780321356680")
                .withField(StandardField.PAGES, "256");

        fetcher = new DoiToBibtexConverterComIsbnFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS));
    }

    @Test
    @Override
    public void testName() {
        assertEquals("ISBN (doi-to-bibtex-converter.herokuapp.com)", fetcher.getName());
    }

    @Test
    @Disabled
    @Override
    public void searchByIdSuccessfulWithShortISBN() {
        throw new UnsupportedOperationException();
    }

    @Test
    @Disabled
    @Override
    public void searchByIdSuccessfulWithLongISBN() {
        throw new UnsupportedOperationException();
    }

    @Test
    @Override
    public void authorsAreCorrectlyFormatted() throws Exception {
        BibEntry bibEntry = new BibEntry(StandardEntryType.Book)
                .withField(StandardField.TITLE, "Repository")
                .withField(StandardField.ISBN, "9783110702125")
                .withField(StandardField.AUTHOR, "Hans-Joachim Habermann and Frank Leymann")
                .withField(StandardField.PAGES, "294")
                .withField(StandardField.YEAR, "2020")
                .withField(StandardField.DAY, "12")
                .withField(StandardField.MONTH, "10");
        Optional<BibEntry> fetchedEntry = fetcher.performSearchById("9783110702125");
        assertEquals(Optional.of(bibEntry), fetchedEntry);
    }

    @Test
    public void testIsbnNeitherAvailable() {
        assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("9785646216541"));
    }

    @Test
    public void searchByIdFailedWithLongISBN() {
        assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("9780321356680"));
    }

    @Test
    public void searchByIdFailedWithShortISBN() throws FetcherException {
        assertThrows(FetcherClientException.class, () -> fetcher.performSearchById("0321356683"));
    }
}


text:
<navbar></navbar>

Sign in

        Not a member? Please register instead.

      <form ng-submit="vm.onSubmit()">

          Email address
          <input type="email"
            class="form-control"
            id="email"
            placeholder="Enter email"
            ng-model="vm.credentials.email">

          Password
          <input type="password"
            class="form-control"
            id="password"
            placeholder="Password"
            ng-model="vm.credentials.password">

        <button type="submit"
          class="btn btn-default">
          Sign in!
        </button>

      </form>


text:
Tasks which will be provided in the box in the new build system.

Also see the agent [here](https://github.com/Microsoft/vso-agent)

##Available Tasks
* Android
* Azure Cloud Deployment
* Azure PowerShell
* Azure WebSite Deployment
* CMake
* CmdScript
* Jake
* MSBuild
* PowerShell
* ProcessRunner
* ShellScript
* VSBuild
* VSTest
* Xcode Build

Coming Soon:

* Ant
* Maven
* Python

##Overview
Tasks are simply tool runners.  They know how to run MSBuild, VSTest, etc... in a first class way and handle return codes, how to treat std/err out, and how to write timeline records based on expected output.  Tasks also help you find an agent with the necessary tools (see demands below).

They also advertise what inputs they need in a first class way so the designer can take input.

Along with templates in the new build system, the goal is in many cases to simply do "New VS Build Definition", save and it just works.  Sometimes you may have to browse to a project file or supply a couple required inputs but it puts the user on rails for the common case.

##DevOps
We also have tasks for script runners such as PowerShell, cmd script, Shell Script, Jake (JavaScript) and Python is coming.  This allows users to run scripts *located in their source control system* ... the same scripts that devops run.  That is a key principle, devops == CI.

##Authoring
Tasks can be written in Powershell, ShellScript, javaScript or Python.  Tasks can carry multiple implementations for cases where you want to run PowerShell on Windows and a Shell Script for example on Linux or OSX.

##Capabilities and Demands
Tasks demand a tool or dependency that they run.  On configuration and startup, an agent registers it's capabilities with the server.  When you add a task to a definition it appends the demands for that definition.  When run, an agent is found with the corresponding capabilities from the configured pool of agents.


text:
"""empty message

Revision ID: 0037 add magazine_id to emails
Revises: 0036 add magazines
Create Date: 2020-01-30 00:09:30.416015

"""

# revision identifiers, used by Alembic.
revision = '0037 add magazine_id to emails'
down_revision = '0036 add magazines'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('emails', sa.Column('magazine_id', postgresql.UUID(as_uuid=True), nullable=True))
    op.create_foreign_key(None, 'emails', 'magazines', ['magazine_id'], ['id'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'emails', type_='foreignkey')
    op.drop_column('emails', 'magazine_id')
    # ### end Alembic commands ###


text:
var config = require('../config')
if(!config.tasks.favicons) return

var gulp = require('gulp');
var favicons = require('gulp-favicons');
var gutil = require("gulp-util");

gulp.task("favicons", function () {
	return gulp.src(config.root.src + config.tasks.favicons.src).pipe(favicons({
			appName: config.root.appName,
			appDescription: config.root.appDescription,
			developerName: null,
			developerURL: null,
			background: config.tasks.favicons.background,
			path: "",
			url: "",
			display: "standalone",
			orientation: "landscape",
			version: "1.0",
			logging: false,
			online: false,
			preferOnline: false,
			icons: {
					android: true,              // Create Android homescreen icon. `boolean`
					appleIcon: true,            // Create Apple touch icons. `boolean` or `{ offset: offsetInPercentage }`
					appleStartup: true,         // Create Apple startup images. `boolean`
					coast: { offset: 25 },      // Create Opera Coast icon with offset 25%. `boolean` or `{ offset: offsetInPercentage }`
					favicons: true,             // Create regular favicons. `boolean`
					firefox: true,              // Create Firefox OS icons. `boolean` or `{ offset: offsetInPercentage }`
					windows: true,              // Create Windows 8 tile icons. `boolean`
					yandex: true                // Create Yandex browser icon. `boolean`
			}
	}))
	.on("error", gutil.log)
	.pipe(gulp.dest(config.root.dest + config.tasks.favicons.dest));
});


text:
require 'rails_helper'

RSpec.describe "Meetings", type: :request do
  before(:each){create(:meeting)}
  let(:source_file){Meeting.last.source_file}
  describe "GET /meetings" do
    it "should return 200" do
      get meetings_path
      expect(response).to have_http_status(200)
    end
  end

  describe "POST /meetings" do
    let(:json_api_data) do
      {
        "data" =>  {
          "type" =>  "meetings",
          "attributes" =>  {
            "purpose" =>  "A test meeting",
            "year" => '2016',
            "month" => '3',
            "source-file-id" => source_file.id,
            "source-file-line-number" => 1
          }
        }
      }.to_json
    end
    let(:headers){{'HTTP_ACCEPT' => "application/vnd.api+json",'Content-Type' => "application/vnd.api+json"}}

    it 'returns a 201' do
      post api_v1_meetings_path,params: json_api_data, headers:headers
      expect(response).to have_http_status(201)
    end

    it 'returns a json-api response' do
      post api_v1_meetings_path,params: json_api_data, headers:headers
      expect(response.body).to be_jsonapi_response_for('meetings')
    end

    it 'should create a meeting record' do
      expect{post api_v1_meetings_path,params: json_api_data, headers:headers}.to change(Meeting, :count).by 1
    end

    it 'should create a meeting record with the right data' do
      post api_v1_meetings_path,params: json_api_data, headers:headers
      meeting = Meeting.last
      expect(meeting.purpose).to eq 'A test meeting'
      expect(meeting.year).to eq 2016
      expect(meeting.month).to eq 3
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/vaadin-osgi-addon"/>


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link href="asset/css/bootstrap.css" rel="stylesheet" />
		<link rel="stylesheet" href="asset/css/dexter.min.css" />
		<link rel="stylesheet" href="asset/css/font-awesome.min.css" />

		<link rel="stylesheet" href="asset/css/prettify.css" />

 Checker Code

					CD_CIRCULAR_DEPENDENCY

 Description

					Test for circular dependencies among classes

 Severity

					Critical

 Detector / Bug Pattern

					FindCircularDependencies / CD

 More Information

    This class has a circular dependency with other classes. This makes building these classes
    difficult, as each is dependent on the other to build correctly. Consider using interfaces
    to break the hard dependency.

 Bad Code

 Good Code

 CWE ID

				CWE-1001

 Code Review Asset

				N/A

 URLs

					FINDBUGS SITE  :

					STACKOVERFLOW SITE  :


text:
========================
Salt 0.9.0 Release Notes
========================

:release: 2011-08-27

Salt 0.9.0 is here. This is an exciting release, 0.9.0 includes the new network
topology features allowing peer salt commands and masters of masters via the
syndic interface.

0.9.0 also introduces many more modules, improvements to the API and
improvements to the ZeroMQ systems.

Download!
---------

The Salt source can be downloaded from the salt GitHub site:

:download:`salt-0.9.0.tar.gz`

Or from PyPI:

https://pypi.python.org/packages/source/s/salt/salt-0.9.0.tar.gz

Here is the md5sum:

9a925da04981e65a0f237f2e77ddab37

For instructions on how to set up Salt please see the :ref:`installation`
instructions.

New Features
------------

Salt Syndic
```````````

The new :ref:`Syndic interface <syndic>` allows a master to be
commanded via another higher level salt master. This is a powerful solution
allowing a master control structure to exist, allowing salt to scale to much
larger levels then before.

Peer Communication
``````````````````

0.9.0 introduces the capability for a minion to call a publication on the
master and receive the return from another set of minions. This allows salt
to act as a communication channel between minions and as a general
infrastructure message bus.

Peer communication is turned off by default but can be enabled via the ``peer``
option in the master configuration file. Documentation on the new :doc:`Peer
interface </ref/peer>`.

Easily Extensible API
`````````````````````

The minion and master classes have been redesigned to allow for specialized
minion and master servers to be easily created. An example on how this is done
for the master can be found in the ``master.py`` salt module:

:blob:`salt/master.py`

The ``Master`` class extends the ``SMaster`` class and set up the main master
server.

The minion functions can now also be easily added to another application via
the ``SMinion`` class, this class can be found in the ``minion.py`` module:

:blob:`salt/minion.py`

Cleaner Key Management
``````````````````````

This release changes some of the key naming to allow for multiple master keys
to be held based on the type of minion gathering the master key.

The -d option has also been added to the salt-key command allowing for easy
removal of accepted public keys.

The --gen-keys option is now available as well for salt-key, this allows
for a salt specific RSA key pair to be easily generated from the command line.

Improved 0MQ Master Workers
```````````````````````````

The 0MQ worker system has been further refined to be faster and more robust.
This new system has been able to handle a much larger load than the previous
setup. The new system uses the IPC protocol in 0MQ instead of TCP.

New Modules
-----------

Quite a few new modules have been made.

New Minion Modules
``````````````````

apache
~~~~~~

Work directly with apache servers, great for managing balanced web servers

cron
~~~~

Read out the contents of a systems crontabs

mdadm
~~~~~

Module to manage raid devices in Linux, appears as the ``raid`` module

mysql
~~~~~

Gather simple data from MySQL databases

ps
~~

Extensive utilities for managing processes

publish
~~~~~~~

Used by the peer interface to allow minions to make publications


text:
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="integrated_content.services.search.content.referenced" class="Integrated\Bundle\ContentBundle\Services\SearchContentReferenced" public="true">
            <argument type="service" id="doctrine_mongodb.odm.document_manager" />
        </service>

        <service id="Integrated\Bundle\ContentBundle\Services\ContentTypeInformation">
            <argument type="service" id="doctrine_mongodb.odm.document_manager" />
        </service>

    </services>
</container>


text:
#include "src/core/lib/iomgr/port.h"

#ifdef GRPC_LINUX_SOCKETUTILS

#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/socket_utils_posix.h"

#include <grpc/support/log.h>

#include <sys/socket.h>
#include <sys/types.h>

int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock,
                 int cloexec) {
  int flags = 0;
  GPR_ASSERT(sizeof(socklen_t) <= sizeof(size_t));
  GPR_ASSERT(resolved_addr->len <= (socklen_t)-1);
  flags |= nonblock ? SOCK_NONBLOCK : 0;
  flags |= cloexec ? SOCK_CLOEXEC : 0;
  return accept4(sockfd,
                 reinterpret_cast<struct sockaddr*>(resolved_addr->addr),
                 reinterpret_cast<socklen_t*>(&resolved_addr->len), flags);
}

#endif


text:
layout: post
published: true
title: How to Check if a Server Needs a Reboot
date: '2017-02-22'
---
## Using Powershell

If you're trying to determine which of your servers require reboots, you'll love this PowerShell script to check the status. It turns out that a simple way to identify **servers that are pending reboot** is to check the registry. This information is stored in the HKeyLocalMachine hive of the registry.
PowerShell is born and bred for working with the registry. Registry is one of the built-in PowerShell providers. There's even already a PSDrive connected to that registry hive! You can browse around the registry just like you can the filesystem.

```
#Change to the registry drive.
#Set-Location can also be invoked through its aliases - CD and SL
#Get-ChildItem can also be invoked through its aliases - Dir and LS

Set-Location HKLM:
Get-ChildItem
```
Wow! Super easy, right?
Now you just need to know where the "pending reboot" location is. There are a couple of places to check.

> HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired

Is where patches installed through automatic updates register the need to reboot.

> HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending

Is another place where pending reboots can be identified.

> HKLM\SYSTEM\CurrentControlSet\Control\Session Manager

Is yet another. Finally, there is Configuration Manager which, if present, can be queried via WMI.

I found a function that I really like to check all four locations. I'll need to wrap it up with some parameters to check remote computers, but in general it was a great start. I've adapted the function to return $true on the first condition that satisfies, since I only care about whether the computer is pending a reboot, and not where the source of the reboot is comping from.

```
#Adapted from https://gist.github.com/altrive/5329377
#Based on <http://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542>
function Test-PendingReboot
{
 if (Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -EA Ignore) { return $true }
 if (Get-Item "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -EA Ignore) { return $true }
 if (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -EA Ignore) { return $true }
 try {
   $util = [wmiclass]"\\.\root\ccm\clientsdk:CCM_ClientUtilities"
   $status = $util.DetermineIfRebootPending()
   if(($status -ne $null) -and $status.RebootPending){
     return $true
   }
 }catch{}

 return $false
}
```