text:
REGISTER_GENERATE_PASS(generate_fc_fuse) {
  paddle::framework::ir::PassPairs pass_pairs;
  for (bool with_relu : {true, false}) {
    // pattern
    SUBGRAPH_(pattern) = [subgraph = &pattern, with_relu](
                             VAR_(x), VAR_(y), VAR_(z)) {
      VLOG(3) << "exec lambda func.";
      auto mul = OP_(mul)({{"X", x}, {"Y", y}}).Out("Out");
      auto ewadd = OP_(elementwise_add)({{"X", mul}, {"Y", z}}).Out("Out");
      if (with_relu) {
        return OP_(relu)({"X", ewadd}).Out("Out");
      } else {
        return ewadd;
      }
    };
    // replace
    SUBGRAPH_(replace) = [subgraph = &replace, with_relu](
                             VAR_(x), VAR_(y), VAR_(z)) {
      auto& fc = OP_(fc)({{"Input", x}, {"W", y}, {"Bias", z}});
      return fc.Out("Out");
    };
    pass_pairs.AddPassDesc(pattern, replace);
  }
  return pass_pairs;
}

REGISTER_GENERATE_PASS(generate_multi_add_to_addn) {
  // pattern
  SUBGRAPH_(pattern) = [subgraph = &pattern](VAR_(x), VAR_(y), VAR_(z)) {
    auto ewadd1 = OP_(elementwise_add)({{"X", x}, {"Y", y}}).Out("Out");
    auto ewadd2 = OP_(elementwise_add)({{"X", ewadd1}, {"Y", z}}).Out("Out");
    return ewadd2;
  };
  // replace
  SUBGRAPH_(replace) = [subgraph = &replace](VAR_(x), VAR_(y), VAR_(z)) {
    return OP_(sum)({"X", {x, y, z}}).Out("Out");
  };
  return {pattern, replace};
}

REGISTER_GENERATE_PASS(generate_combine_matmul) {
  // pattern
  SUBGRAPH_(pattern) = [subgraph = &pattern](VAR_(x), VAR_(y), VAR_(z)) {
    auto matmul1 = OP_(matmul)({{"X", x}, {"Y", y}}).Out("Out");
    auto matmul2 = OP_(matmul)({{"X", x}, {"Y", z}}).Out("Out");
    return std::make_tuple(matmul1, matmul2);
  };
  // replace
  SUBGRAPH_(replace) = [subgraph = &replace](VAR_(x), VAR_(y), VAR_(z)) {
    auto concat = OP_(concat)({"X", {y, z}}).Out("Out");
    auto matmul = OP_(matmul)({{"X", x}, {"Y", concat}}).Out("Out");
    auto slice1 = OP_(slice)({"X", matmul}).Out("Out");
    auto slice2 = OP_(slice)({"X", matmul}).Out("Out");
    return std::make_tuple(slice1, slice2);
  };
  return {pattern, replace};
}

namespace paddle {
namespace framework {
namespace ir {

TEST(GeneratePass, construct_with_string) {
  std::string binary_str;
  register_generate_fc_fuse().MultiPassDesc().SerializeToString(&binary_str);
  GeneratePass generate_pass(binary_str);
}

TEST(GeneratePass, generate_fc_fuse) {
  // inputs                     operator            output
  // --------------------------------------------------------
  // (a, filters_0 bias_0)      conv2d           -> conv2d_out
  // conv2d_out                 relu             -> relu_out_0
  // (relu_out_0, weights_0)    mul              -> mul_out_0
  // (mul_out_0, bias_1)        elementwise_add  -> add_out_0
  // add_out_0                  relu             -> relu_out_1
  // (relu_out_1, weights_1)    mul              -> mul_out_1
  // (mul_out_1, bias_2)        elementwise_add  -> add_out_1
  Layers layers;
  auto* a = layers.data("a");
  auto* filters_0 = layers.data("conv2d_filters_0", {}, true);
  auto* bias_0 = layers.data("conv2d_bias_0", {}, true);
  auto* conv2d_out = layers.conv2d(a, filters_0, bias_0, false);
  auto* relu_out_0 = layers.relu(conv2d_out);
  auto* weights_0 = layers.data("weights_0", {}, true);
  auto* mul_out_0 = layers.mul(relu_out_0, weights_0);
  auto* bias_1 = layers.data("bias_1", {}, true);
  auto* add_out_0 = layers.elementwise_add(mul_out_0, bias_1, nullptr, 1);
  auto* relu_out_1 = layers.relu(add_out_0);
  auto* weights_1 = layers.data("weights_1", {}, true);
  auto* mul_out_1 = layers.mul(relu_out_1, weights_1);
  auto* bias_2 = layers.data("bias_2", {}, true);
  auto* add_out_1 = layers.elementwise_add(mul_out_1, bias_2, nullptr, 1);
  VLOG(4) << add_out_1;

  std::unique_ptr<ir::Graph> graph(new ir::Graph(layers.main_program()));
  auto pass = PassRegistry::Instance().Get("generate_fc_fuse");
  int num_nodes_before = graph->Nodes().size();
  int num_mul_nodes_before = GetNumOpNodes(graph, "mul");
  VLOG(3) << DebugString(graph);

  graph.reset(pass->Apply(graph.release()));
  int num_nodes_after = graph->Nodes().size();
  int num_fc_nodes_after = GetNumOpNodes(graph, "fc");
  VLOG(3) << DebugString(graph);

  PADDLE_ENFORCE_EQ(num_nodes_before,
                    num_nodes_after + 6,
                    platform::errors::InvalidArgument(
                        "num_nodes_before=%d, num_nodes_after=%d.",
                        num_nodes_before,
                        num_nodes_after));
  PADDLE_ENFORCE_EQ(num_fc_nodes_after,
                    2,
                    platform::errors::InvalidArgument("num_fc_nodes_after=%d.",
                                                      num_fc_nodes_after));
  PADDLE_ENFORCE_EQ(num_mul_nodes_before,
                    num_fc_nodes_after,
                    platform::errors::InvalidArgument(
                        "num_mul_nodes_before=%d, num_fc_nodes_after=%d.",
                        num_mul_nodes_before,
                        num_fc_nodes_after));
}

TEST(GeneratePass, generate_multi_add_to_addn) {
  // inputs                     operator            output
  // --------------------------------------------------------
  // (a, b)                     elementwise_add  -> add_out_0
  // (add_out_0, c)             elementwise_add  -> add_out_1
  Layers layers;
  auto* a = layers.data("a");
  auto* b = layers.data("b");
  auto* c = layers.data("c");
  auto* add_out_0 = layers.elementwise_add(a, b);
  layers.elementwise_add(add_out_0, c);

  std::unique_ptr<ir::Graph> graph(new ir::Graph(layers.main_program()));
  auto pass = PassRegistry::Instance().Get("generate_multi_add_to_addn");
  int num_nodes_before = graph->Nodes().size();
  int num_add_nodes_before = GetNumOpNodes(graph, "elementwise_add");
  VLOG(3) << DebugString(graph);

  graph.reset(pass->Apply(graph.release()));
  int num_nodes_after = graph->Nodes().size();
  int num_addn_nodes_after = GetNumOpNodes(graph, "sum");
  VLOG(3) << DebugString(graph);

  PADDLE_ENFORCE_EQ(num_nodes_before,
                    num_nodes_after + 2,
                    platform::errors::InvalidArgument(
                        "num_nodes_before=%d, num_nodes_after=%d.",
                        num_nodes_before,
                        num_nodes_after));
  PADDLE_ENFORCE_EQ(num_addn_nodes_after,
                    1,
                    platform::errors::InvalidArgument(
                        "num_addn_nodes_after=%d.", num_addn_nodes_after));
  PADDLE_ENFORCE_EQ(num_add_nodes_before,
                    num_addn_nodes_after + 1,
                    platform::errors::InvalidArgument(
                        "num_add_nodes_before=%d, num_addn_nodes_after=%d.",
                        num_add_nodes_before,
                        num_addn_nodes_after));
}

TEST(GeneratePass, generate_combine_matmul) {
  // inputs                     operator            output
  // --------------------------------------------------------
  // (a, b)                     matmul           -> matmul_out_0
  // (a, c)                     matmul           -> matmul_out_1
  Layers layers;
  auto* a = layers.data("a");
  auto* b = layers.data("b");
  auto* c = layers.data("c");
  layers.matmul(a, b);
  layers.matmul(a, c);

  std::unique_ptr<ir::Graph> graph(new ir::Graph(layers.main_program()));
  auto pass = PassRegistry::Instance().Get("generate_combine_matmul");
  int num_nodes_before = graph->Nodes().size();
  int num_matmul_nodes_before = GetNumOpNodes(graph, "matmul");
  VLOG(3) << DebugString(graph);

  graph.reset(pass->Apply(graph.release()));
  int num_nodes_after = graph->Nodes().size();
  int num_matmul_nodes_after = GetNumOpNodes(graph, "matmul");
  VLOG(3) << DebugString(graph);

  PADDLE_ENFORCE_EQ(num_nodes_before,
                    num_nodes_after - 4,
                    platform::errors::InvalidArgument(
                        "num_nodes_before=%d, num_nodes_after=%d.",
                        num_nodes_before,
                        num_nodes_after));
  PADDLE_ENFORCE_EQ(num_matmul_nodes_after,
                    1,
                    platform::errors::InvalidArgument(
                        "num_matmul_nodes_after=%d.", num_matmul_nodes_after));
  PADDLE_ENFORCE_EQ(
      num_matmul_nodes_before,
      num_matmul_nodes_after + 1,
      platform::errors::InvalidArgument(
          "num_matmul_nodes_before=%d, num_matmul_nodes_after=%d.",
          num_matmul_nodes_before,
          num_matmul_nodes_after));
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle


text:
title: Life in C#
description: Conway's Game of Life implemented using C#
date: 2020-05-10
weight: 1
---

**Conway's _Game of Life_ is a zero-player video game that uses a few basic rules to determine if cells live or die based on the density of their neighbors.** In this project we create _Life_ using C# and System.Drawing and display the animated graphics model using Windows Forms.

## Code

We divide this project into two libraries, one for the graphics model (containing classes for `Cell` and `Booard`) and another that handles the graphical environment and rendering.

### Cell Model

I decided not to make cells position-aware. Instead each cell simply tracks its own `IsAlive` state, and knows about its 8 neighbors.

When `DetermineNextLiveState()` is called, the neighbors are inspected to determine how many are alive, then _Life_ rules are used to determine if this cell will be alive or not after advancement.

```cs
public class Cell
{
    public bool IsAlive;
    public readonly List<Cell> neighbors = new List<Cell>();

    private bool IsAliveNext;
    public void DetermineNextLiveState()
    {
        // Live cells with fewer than two live neighbors die
        // Live cells with more than three live neighbors die
        // Dead cells with three live neighbors comes alive

        int liveNeighbors = neighbors.Where(x => x.IsAlive).Count();

        if (IsAlive)
            IsAliveNext = liveNeighbors == 2 || liveNeighbors == 3;
        else
            IsAliveNext = liveNeighbors == 3;
    }

    public void Advance()
    {
        IsAlive = IsAliveNext;
    }
}
```

### Board Model

The `Board` holds a 2D array of `Cell` objects and advances the board whenever the `Advance()` method is called.

```cs
public readonly Cell[,] Cells;
public readonly int CellSize;

public int Columns { get { return Cells.GetLength(0); } }
public int Rows { get { return Cells.GetLength(1); } }
public int Width { get { return Columns * CellSize; } }
public int Height { get { return Rows * CellSize; } }

public Board(int width, int height, int cellSize, double liveDensity = .1)
{
    CellSize = cellSize;

    Cells = new Cell[width / cellSize, height / cellSize];
    for (int x = 0; x < Columns; x++)
        for (int y = 0; y < Rows; y++)
            Cells[x, y] = new Cell();

    ConnectNeighbors();
    Randomize(liveDensity);
}

readonly Random rand = new Random();
public void Randomize(double liveDensity)
{
    foreach (var cell in Cells)
        cell.IsAlive = rand.NextDouble() < liveDensity;
}

public void Advance()
{
    foreach (var cell in Cells)
        cell.DetermineNextLiveState();
    foreach (var cell in Cells)
        cell.Advance();
}
```

I separated this method because it's easier to assess in isolation. It's in charge of populating the `Neighbors` property of each `Cell`. Every cell should have 8 neighbors. This design wraps neighbors around the edge of the board.

```cs
private void ConnectNeighbors()
{
    for (int x = 0; x < Columns; x++)
    {
        for (int y = 0; y < Rows; y++)
        {
            // determine X of left and right cells
            int xL = (x > 0) ? x - 1 : Columns - 1;
            int xR = (x < Columns - 1) ? x + 1 : 0;

            // determine Y of top and bottom cells
            int yT = (y > 0) ? y - 1 : Rows - 1;
            int yB = (y < Rows - 1) ? y + 1 : 0;

            // add the 8 neighbors surrounding this cell
            Cells[x, y].neighbors.Add(Cells[xL, yT]);
            Cells[x, y].neighbors.Add(Cells[x, yT]);
            Cells[x, y].neighbors.Add(Cells[xR, yT]);
            Cells[x, y].neighbors.Add(Cells[xL, y]);
            Cells[x, y].neighbors.Add(Cells[xR, y]);
            Cells[x, y].neighbors.Add(Cells[xL, yB]);
            Cells[x, y].neighbors.Add(Cells[x, yB]);
            Cells[x, y].neighbors.Add(Cells[xR, yB]);
        }
    }
}
```

### Creating the GUI

#### Resetting the Board

The board is stored at the class-level and is reset whenever settings are changed or the board is resized.

```cs
Board board;
private void Reset()
{
    board = new Board(
        width: pictureBox1.Width,
        height: pictureBox1.Height,
        cellSize: (int)SizeNud.Value,
        liveDensity: (double)DensityNud.Value / 100);
}
```

#### Advancement

A `Timer` triggers board advancement and rendering
```cs
private void timer1_Tick(object sender, EventArgs e)
{
    board.Advance();
    Render();
}
```

#### Rendering

This is pretty straightforward drawing with System.Drawing in Windows Forms. A `Bitmap` is created in memory, drawn on, and applied to a `Picturebox` (used here because its built-in double-buffering prevents flickering as the image is rapidly updated).

```cs
private void Render()
{
    using (var bmp = new Bitmap(board.Width, board.Height))
    using (var gfx = Graphics.FromImage(bmp))
    using (var cellBrush = new SolidBrush(Color.LightGreen))
    {
        gfx.Clear(Color.Black);

        var cellSize = (GridCheckbox.Checked && board.CellSize > 1) ?
                        new Size(board.CellSize - 1, board.CellSize - 1) :
                        new Size(board.CellSize, board.CellSize);

        for (int col = 0; col < board.Columns; col++)
        {
            for (int row = 0; row < board.Rows; row++)
            {
                var cell = board.Cells[col, row];
                if (cell.IsAlive)
                {
                    var cellLocation = new Point(col * board.CellSize, row * board.CellSize);
                    var cellRect = new Rectangle(cellLocation, cellSize);
                    gfx.FillRectangle(cellBrush, cellRect);
                }
            }
        }

        pictureBox1.Image = (Bitmap)bmp.Clone();
    }
}
```

## Defining Starting Conditions

Special starting patterns in _Game of Life_ can produce intriguing animations. There are many websites dedicated to exploring these phenomena, and in this example we will take a look a starting pattern which infinitely produces self-propelling "gliders".

### Defining Initial State

I found it useful to define the starting condition as a multi-line string, then write a method to translate the string into a _Life_ starting condition.

```cs
private void StartWithPattern(string pattern)
{
    board.KillAll();

    string[] lines = pattern.Split('\n');
    int yOffset = (board.Rows - lines.Length) / 2;
    int xOffset = (board.Columns - lines[0].Length) / 2;

    for (int y = 0; y < lines.Length; y++)
        for (int x = 0; x < lines[y].Length; x++)
            board.Cells[x + xOffset, y + yOffset].IsAlive = lines[y].Substring(x, 1) == "X";
}
```

Now I can design patterns visually in code.

```cs
private void GunButton_Click(object sender, EventArgs e)
{
    string gliderGun =
        "-------------------------X----------\n" +
        "----------------------XXXX----X-----\n" +
        "-------------X-------XXXX-----X-----\n" +
        "------------X-X------X--X---------XX\n" +
        "-----------X---XX----XXXX---------XX\n" +
        "XX---------X---XX-----XXXX----------\n" +
        "XX---------X---XX--------X----------\n" +
        "------------X-X---------------------\n" +
        "-------------X----------------------";
    StartWithPattern(gliderGun);
}
```

This "glider gun" starting pattern could run infinitely, but since our universe wraps around the edges the gliders eventually wrap around and destroy the gun.

## Source Code

* GitHub: [game-of-life C# project](https://github.com/swharden/Csharp-Data-Visualization/tree/main/dev/old/drawing/game-of-life)

## Resources

* [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) (Wikipedia)
* [Game of Life News](http://pentadecathlon.com/lifeNews/2006/06/single_glider_collision_survey.html)
* [ConwayLife](https://www.conwaylife.com/wiki/Spaceship) (Wiki)

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * AiryMVC Framework
 *
 * @category AiryMVC
 * @license New BSD license - at this URL: http://opensource.org/licenses/BSD-3-Clause
 * @author: Hung-Fu Aaron Chang
 */

/**
 * This is the controller class that is used for intializing the instance and set variables.
 *
 * @package framework\app\AppModel
 * @license New BSD license - at this URL: http://opensource.org/licenses/BSD-3-Clause
 */
class AppModel extends AbstractModel {

    /**
     * To deal with the database config(s)
     *
     * @return object database
     */
    public function initialDB() {
        $this->multiDb = DbConfig::getConfig();
        $this->db = $this->multiDb[0];
        return $this->db;
    }

	/**
	 * Sets the database config variables
	 *
 	 * @param array $config
 	 */
    public function setDb($config) {
    	$this->multiDb = DbConfig::getConfig();
    	$this->db = DbConfig::assignDbAccess(0, $config);
    }

	/**
	 * Sets multiple databases configs.
 	 *
 	 * @param int $databaseId
 	 * @param array $config
 	 */
    public function setMultiDb($databaseId, $config) {
    	$this->multiDb = DbConfig::getConfig();
    	$this->db = DbConfig::assignDbAccess($databaseId, $config);
    }

}

?>


text:
package org.springframework.security.web.server.header;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;

/**
 * @author Rob Winch
 * @since 5.0
 */
public class XFrameOptionsServerHttpHeadersWriterTests {

	ServerWebExchange exchange = exchange(MockServerHttpRequest.get("/"));

	XFrameOptionsServerHttpHeadersWriter writer;

	@Before
	public void setup() {
		writer = new XFrameOptionsServerHttpHeadersWriter();
	}

	@Test
	public void writeHeadersWhenUsingDefaultsThenWritesDeny() {
		writer.writeHttpHeaders(exchange);

		HttpHeaders headers = exchange.getResponse().getHeaders();
		assertThat(headers).hasSize(1);
		assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
	}

	@Test
	public void writeHeadersWhenUsingExplicitDenyThenWritesDeny() {
		writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.DENY);

		writer.writeHttpHeaders(exchange);

		HttpHeaders headers = exchange.getResponse().getHeaders();
		assertThat(headers).hasSize(1);
		assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
	}

	@Test
	public void writeHeadersWhenUsingSameOriginThenWritesSameOrigin() {
		writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN);

		writer.writeHttpHeaders(exchange);

		HttpHeaders headers = exchange.getResponse().getHeaders();
		assertThat(headers).hasSize(1);
		assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("SAMEORIGIN");
	}

	@Test
	public void writeHeadersWhenAlreadyWrittenThenWritesHeader() {
		String headerValue = "other";
		exchange.getResponse().getHeaders().set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, headerValue);

		writer.writeHttpHeaders(exchange);

		HttpHeaders headers = exchange.getResponse().getHeaders();
		assertThat(headers).hasSize(1);
		assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly(headerValue);
	}

	private static MockServerWebExchange exchange(MockServerHttpRequest.BaseBuilder<?> request) {
		return MockServerWebExchange.from(request.build());
	}
}