//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <EventKitUI/EKEditItemViewController.h>

#import <EventKitUI/EKEventAttachmentCellControllerDelegate-Protocol.h>
#import <EventKitUI/UITableViewDataSource-Protocol.h>
#import <EventKitUI/UITableViewDelegate-Protocol.h>

@class NSArray, NSString, UITableView;
@protocol EKEventAttachmentEditViewControllerDelegate;

__attribute__((visibility("hidden")))
@interface EKEventAttachmentEditViewController : EKEditItemViewController <UITableViewDataSource, UITableViewDelegate, EKEventAttachmentCellControllerDelegate>
{
    UITableView *_table;
    NSArray *_cellControllers;
    id <EKEventAttachmentEditViewControllerDelegate> _delegate;
}

@property(nonatomic) __weak id <EKEventAttachmentEditViewControllerDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (id)owningEventForAttachmentCellController:(id)arg1;
- (id)parentViewControllerForAttachmentCellController:(id)arg1;
- (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2;
- (double)tableView:(id)arg1 heightForRowAtIndexPath:(id)arg2;
- (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2;
- (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2;
- (void)viewDidLoad;
- (void)loadView;
- (id)initWithFrame:(struct CGRect)arg1 attachments:(id)arg2 sourceIsManaged:(_Bool)arg3;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


}
}
<reponame>Reshurum/notch<filename>src/memory.rs
use super::byteorder::{BigEndian, ByteOrder};

// Size of the memory map of a CHIP-8 interpreter is 4kB.
pub const RAM_SIZE: usize = 4096;

// Memory map constraints for CHIP-8 virtual machines.
pub const END_RESERVED: usize = 0x200;

// Here are some additional unused constrains for documentation purposes. These
// are defined in the CHIP-8 spec but are not referenced in code for this
// specific implementation.
//
//     pub const START_RESERVED: usize = 0x000;
//     pub const END_PROGRAM_SPACE: usize = 0xFFF;

// Font size constants.
const CHARACTER_SIZE: usize = 5;
const CHARACTER_COUNT: usize = 16;

// Where fonts are stored in interpreter memory.
const FONT_OFFSET: usize = 0;

pub struct Memory {
    // Memory allocated for the running CHIP-8 application.
    ram: Vec<u8>,
}

impl Memory {
    /// Allocate some memory for ram and load a rom into it.
    pub fn new(rom: Vec<u8>) -> Memory {
        // Allocate 4kB of memory as defined in the many specifications.
        let mut ram = vec![0; RAM_SIZE];

        Memory::dump_rom(&mut ram, &rom);
        Memory::dump_fonts(&mut ram);

        Memory {
            ram: ram,
        }
    }

    /// Simply returns an 8-bit word at the specified address.
    #[inline(always)]
    pub fn read(&self, addr: usize) -> u8 {
        self.ram[addr]
    }

    /// Write an 8-bit byte at a specific address. There is no concern over
    /// endianess since this function operates on single bytes.
    #[inline(always)]
    pub fn write(&mut self, addr: usize, byte: u8) {
        self.ram[addr] = byte;
    }

    /// Reads a 16-bit word from ram. This function is used mainly to read and
    /// execute instructions as their word size is 16 bits.
    #[inline(always)]
    pub fn read_word(&self, addr: u16) -> u16 {
        BigEndian::read_u16(&self.ram[addr as usize..])
    }

    /// Find the memory address of the requested character.
    #[inline(always)]
    pub fn get_font(&self, font: u8) -> u16 {
        FONT_OFFSET as u16 + font as u16 * CHARACTER_SIZE as u16
    }

    /// Dumps a passed rom containing executable code into ram starting at
    /// program space (right after reserved space ends).
    fn dump_rom(ram: &mut Vec<u8>, rom: &Vec<u8>) {
        // Dump the rom containing the executable code of the program into ram
        // starting at the start of the program space.
        for i in 0..rom.len() {
            ram[i + END_RESERVED] = rom[i];
        }
    }

    /// Dumps the standard CHIP-8 fonts to ram. The fonts are stored at the
    /// start of reserved memory and this is fine since the fonts are the only
    /// thing being stored in reserved memory.
    fn dump_fonts(ram: &mut Vec<u8>) {
        // The characters 0-F to be stored in ram as a font for chip 8 programs.
        // Nested vectors are used for ease of reading.
        //
        // Hopefully this is optimized by the compiler, but it's no problem
        // since this is run only once.
        let fonts = vec![
            vec![0xF0, 0x90, 0x90, 0x90, 0xF0], // 0
            vec![0x20, 0x60, 0x20, 0


using System;

namespace BarcodeStandard.Symbologies
{
    /// <summary>
    ///  EAN-8 encoding
    ///  Written by: Brad Barnhill
    /// </summary>
    internal class EAN8 : BarcodeCommon, IBarcode
    {
        private readonly string[] EAN_CodeA = ["0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011"];
        private readonly string[] EAN_CodeC = ["1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100"];

        internal EAN8(string input)
        {
            RawData = input;

            //check numeric only
            if (!IsNumericOnly(RawData))
                Error("EEAN8-2: Numeric only.");

            CheckDigit();
        }
        /// <summary>
        /// Encode the raw data using the EAN-8 algorithm.
        /// </summary>
        private string Encode_EAN8()
        {
            //check length
            if (RawData.Length != 8 && RawData.Length != 7) Error("EEAN8-1: Invalid data length. (7 or 8 numbers only)");

            //encode the data
            string result = "101";

            //first half (Encoded using left hand / odd parity)
            for (int i = 0; i < RawData.Length / 2; i++)
            {
                result += EAN_CodeA[Int32.Parse(RawData[i].ToString())];
            }

            //center guard bars


anvil.Window
	err = httpApi.GetInto(fmt.Sprintf("/wins/%d/info", notif.WinId), &info)
	if err != nil {
		// Parsing notification failed.
		fmt.Fprintf(os.Stderr, "awatch: getting info for window %d failed: %v\n", notif.WinId, err)
		return
	}

	e := os.Getenv("ANVIL_WIN_LOCAL_DIR")
	localDir, err := filepath.Abs(e)
	if err != nil {
		fmt.Fprintf(os.Stderr, "awatch: getting absolute path of %s failed: %v\n", e, os.Getenv("ANVIL_WIN_LOCAL_DIR"))
		return
	}

	winPath, err := filepath.Abs(info.Path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "awatch: getting absolute path of %s failed: %v\n", info.Path, err)
		return
	}

	if !strings.HasPrefix(winPath, localDir) {
		debug("awatch: %s doesn't match our dir %s\n", winPath, localDir)
		return
	}

	updateCmdsFromWindow()
	runCmdsAndUpdateWindow()
}

func runCmdsAndUpdateWindow() {
	output := runCmds()
	httpApi.Put(fmt.Sprintf("/wins/%d/body", watchWin.Id), output)
}

// updateCmdsFromWindow reads all the lines from the window body that begin with '% ' and
// treat them as commands to run.
func updateCmdsFromWindow() {
	body, err := httpApi.WindowBody(watchWin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "awatch: reading watch window failed: %v\n", err)
		return
	}

	cmds = cmds[:0]
	scanner := bufio.NewScanner(body)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "% ") {
			cmds = append(cmds, line[2:])
		}
	}
}

func runCmds() (output *bytes.Buffer) {
	buf := new(bytes.Buffer)

	for _, c := range cmds {
		fmt.Fprintf(buf, "%% %s\n", c)
		debug("awatch: running command: %s\n", c)
		output, err := run(c)
		if err != nil {
			fmt.Fprintf(buf, "(execution error: %v)\n", err)
		}
		buf.Write(output)
	}

	return buf
}
package main

import (
	"bytes"
	"encoding/csv"
	"io/ioutil"
	"log"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestGetTopic(t *testing.T) {
	log.SetOutput(ioutil.Discard)
	defer log.SetOutput(os.Stdout)

	reader := bytes.NewBufferString(`{"a": 1, "b": "asdf\n"}
{"a" : null}`)
	buf := bytes.NewBuffer([]byte{})
	writer := csv.NewWriter(buf)

	json2csv(reader, writer, []string{"a", "c"}, false)

	output := buf.String()
	assert.Equal(t, output, "1,\n,\n")
}

func TestGetLargeInt(t *testing.T) {
	log.SetOutput(ioutil.Discard)
	defer log.SetOutput(os.Stdout)

	reader := bytes.NewBufferString(`{"a": 1356998399}`)
	buf := bytes.NewBuffer([]byte{})
	writer := csv.NewWriter(buf)

	json2csv(reader, writer, []string{"a"}, false)

	output := buf.String()
	assert.Equal(t, output, "1356998399\n")
}

func TestGetFloat(t *testing.T) {
	log.SetOutput(ioutil.Discard)
	defer log.SetOutput(os


vices.GetService(typeof(ExpressionParserOptions));
            DecimalLiteralElement element = new DecimalLiteralElement();

            try
            {
                decimal value = options.ParseDecimal(image);
                return new DecimalLiteralElement(value);
            }
            catch (OverflowException ex)
            {
                element.OnParseOverflow(image);
                return null;
            }
        }

        public override void Emit(FleeILGenerator ilg, IServiceProvider services)
        {
            int index = ilg.GetTempLocalIndex(typeof(decimal));
            Utility.EmitLoadLocalAddress(ilg, index);

            int[] bits = decimal.GetBits(_myValue);
            EmitLoad(bits[0], ilg);
            EmitLoad(bits[1], ilg);
            EmitLoad(bits[2], ilg);

            int flags = bits[3];

            EmitLoad((flags >> 31) == -1, ilg);

            EmitLoad(flags >> 16, ilg);

            ilg.Emit(OpCodes.Call, OurConstructorInfo);

            Utility.EmitLoadLocal(ilg, index);
        }

        public override System.Type ResultType => typeof(decimal);
    }
}


 super.text = text;
  }

  get rawSrc() {
    return super.rawSrc;
  }

  set rawSrc(rawSrc) {
    this._consumer = undefined;
    super.rawSrc = rawSrc;
  }

  generatedPositionFor(position) {
    return this.consumer.generatedPositionFor(position);
  }

  originalPositionFor(position) {
    return this.consumer.originalPositionFor(position);
  }

  markDirty() {
    super.markDirty();
    this._consumer = undefined;
  }

  findOutgoingRelationsInParseTree() {
    const outgoingRelations = super.findOutgoingRelationsInParseTree();
    if (!this.isLoaded) {
      return outgoingRelations;
    }
    const parseTree = this.parseTree;
    if (parseTree.file) {
      outgoingRelations.push({
        type: 'SourceMapFile',
        href: parseTree.file,
      });
    }
    if (Array.isArray(parseTree.sources)) {
      for (const [index, href] of parseTree.sources.entries()) {
        // Skip bogus webpack entries:
        if (
          !/^\/webpack\/bootstrap [0-9a-f]+$|^\/\(webpack\)\/buildin\/module\.js$/.test(
            href
          )
        ) {
          outgoingRelations.push({
            type: 'SourceMapSource',
            index, // This isn't too robust
            href,
          });
        }
      }
    }
    return outgoingRelations;
  }
}

Object.assign(SourceMap.prototype, {
  contentType: 'application/json',

  notDefaultForContentType: true, // Avoid reregistering application/json

  supportedExtensions: ['.map'],
});

module.exports = SourceMap;
module.exports = (queryObj) => {
  return function removeEmptyJavaScripts(assetGraph) {
    for (const asset of assetGraph.findAssets({
      type: 'JavaScript',
      isLoaded: true,
      isEmpty: true,
      ...queryObj,
    })) {
      let everyIncomingRelationRemoved = true;
      for (const incomingRelation of asset.incomingRelations) {
        let safeToRemove = true;
        if (incomingRelation.type === 'HtmlScript') {
          for (const attribute of Array.from(
            incomingRelation.node.attributes
          )) {
            if (
              attribute.name !== 'src' &&
              (attribute.name !== 'defer' || attribute.value !== 'defer') &&
              (attribute.name !== 'async' || attribute.value !== 'async') &&
              (attribute.name !== 'type' ||
                attribute.value !== 'text/javascript')
            ) {
              safeToRemove = false;
              break; // Don't bother checking the remaining attributes
            }
          }
        }
        if (safeToRemove) {
          incomingRelation.detach();
        } else {
          everyIncomingRelationRemoved = false;
        }
      }
      if (everyIncomingRelationRemoved) {
        assetGraph.removeAsset(asset);
      }
    }
  };
};
module.exports = (queryObj, media) => {
  const includeByMedium = {};
  if (!media) {
    includeByMedium.all = true;
  } else {
    for (const medium of media.split(',')) {
      includeByMedium[medium.replace(/^\s+|\s+$/g, '')] = true;
    }
  }
  function includeMedia(media) {
    return (
      includeByMedium.all ||
      media.some((medium) => {
        medium = medium.replace(/^\s+|\s+$/g, '');
        return medium === 'all' || includeByMedium[medium];
      })
    );
  }

  return function convertStylesheetsToInlineStyles(assetGraph) {
    for (const htmlAsset of assetGraph.findAssets({
      isHtml: true,


不用喊代驾，事实上我曾经有过喝一杯啤酒没吹出来的历史，大伙请勿模仿。需求本身不够刚，就容易被竞争对手侵入，本质原因还在于用户的惰性，没事装那么多 APP 干嘛？一类有一个就够了。

当然并不是所有行业的横向延展都这么容易，否则腾讯就把所有互联网服务全做了，移动出行这个行业有他固有的行业特点。

这个特点就是移动出行类产品服务的标准化程度太高了。这既是好事，也是坏事。好事是前期容易发挥互联网的优势，就像国内外电商都是先从卖书开始。但坏处是你做两年，我做两个月，咱俩的产品体验基本一样。滴滴做代驾，体验和e 代驾差不多，但优势就是我流量比你大，司机也比你多（理论上白天开专车的晚上都能开代驾），何况我还肯花钱做补贴，你说这仗怎么打？！

标准化程度高的另一种说法就是“护城河太浅”，不像很多互联网行业，要么有很多的技术 know-how，像搜索；要么有很强的网络效应，像 SNS。你先做了两年，优势会非常明显，我自己做，很长时间内体验恐怕都赶不上你。

BAT 的核心业务搜索、SNS、电商平台，都有极强的护城河，事实上百度也做了百度 Hi 和有啊，腾讯做了搜搜和拍拍，阿里也做了来往，但结果咱就不讲了。事实上，不光是移动出行领域，绝大多数 O2O 领域都有” 护城河太浅"的问题。导致本来你一小滩生意做得挺滋润，一不小心就被竞争对手延展进来了，没办法，护城河太浅！

`从用户的角度来看，标准化程度高意味着产品差异化不足，那么补贴就变成硬道理`。拿专车举例，等车、进车、坐车、离开的体验其实差不多，无非就是车内干净点，司机态度好一点，帮你开门帮你拿箱子，后排有瓶水。我就没听说有谁讨论过是 Uber 的服务好还是滴滴的服务好，只听说过大伙讨论哪个更便宜。甚至连每一家自己的宣传也都是强调补贴！

神州专车试图打差异化，但手法比较初级。说�


Request)
		})

		Convey("ActivateSegment()", func() {
			// TODO(james.yin):
			srv.EXPECT().ActivateSegment(Any(), Any(), Any(), Any()).Return(nil)

			req := &segpb.ActivateSegmentRequest{
				EventlogId:     snowflake.NewTestID().Uint64(),
				ReplicaGroupId: snowflake.NewTestID().Uint64(),
				Replicas: map[uint64]string{
					1: "127.0.0.1:11811",
				},
			}
			resp, err := ss.ActivateSegment(context.Background(), req)
			So(err, ShouldBeNil)
			So(resp, ShouldNotBeNil)
		})

		Convey("InactivateSegment()", func() {
			// TODO(james.yin):
			// srv.EXPECT().InactivateSegment(Any(), Any()).Return(nil)

			req := &segpb.InactivateSegmentRequest{}
			_, err := ss.InactivateSegment(context.Background(), req)
			So(err, ShouldBeNil)
		})

		Convey("AppendToBlock()", func() {
			srv.EXPECT().AppendToBlock(Any(), Not(vanus.EmptyID()), Not(Len(0))).Return([]int64{1}, nil)
			srv.EXPECT().AppendToBlock(Any(), Eq(vanus.EmptyID()), Any()).Return(nil, errors.ErrInvalidRequest)
			srv.EXPECT().AppendToBlock(Any(), Any(), Len(0)).Return(nil, errors.ErrInvalidRequest)

			req := &segpb.AppendToBlockRequest{
				BlockId: snowflake.NewTestID().Uint64(),
				Events: &cepb.CloudEventBatch{
					Events: make([]*cepb.CloudEvent, 1),
				},
			}
			resp, err := ss.AppendToBlock(context.Background(), req)
			So(err, ShouldBeNil)
			So(resp.Offsets, ShouldResemble, []int64{1})

			req = &segpb.AppendToBlockRequest{
				BlockId: 0,
				Events: &cepb.CloudEventBatch{
					Events: make([]*cepb.CloudEvent, 1),
				},
			}
			_, err = ss.AppendToBlock(context.Background(), req)
			So(err, ShouldEqual, errors.ErrInvalidRequest)

			req = &segpb.AppendToBlockRequest{
				BlockId: snowflake.NewTestID().Uint64(),
				Events:  &cepb.CloudEventBatch{},
			}
			_, err = ss.AppendToBlock(context.Background(), req)
			So(err, ShouldEqual, errors.ErrInvalidRequest)
		})

		Convey("ReadFromBlock()", func() {
			id := snowflake.NewTestID()
			srv.EXPECT().ReadFromBlock(Any(), Not(vanus.EmptyID()), Any(), Not(0),
				Any()).Return(make([]*cepb.CloudEvent, 1), nil)
			srv.EXPECT().ReadFromBlock(Any(), Eq(vanus.EmptyID()), Any(), Any(),
				Any()).Return(nil, errors.ErrInvalidRequest)
			srv.EXPECT().ReadFromBlock(Any(), Any(), Any(), Eq(0), Any()).Return(nil, errors.ErrResourceNotFound)

			req := &segpb.ReadFromBlockRequest{
				BlockId: id.Uint64(),
				Number:  1,
			}
			resp, err := ss.ReadFromBlock(context.Background(), req)
			So(err, ShouldBeNil)
			So(resp.GetEvents().GetEvents(), ShouldResemble, []*cepb.CloudEvent{nil})

			req = &segpb.ReadFromBlockRequest{
				BlockId: 0,
			}
			_, err = ss.ReadFromBlock(context.Background(), req)
			So(err, ShouldEqual, errors.ErrInvalidRequest)

			req = &segpb.ReadFromBlockRequest{
				BlockId: snowflake.NewTestID().Uint64(),
			}
			_, err = ss.ReadFromBlock(context.Background(), req)
			So(err, ShouldEqual, errors.ErrResourceNotFound)
		})
	})
}
// Copyright 2023 Linkall Inc.
//
// Licensed under the Apache License, Version 2.0 (t


ved a copy of the GNU Lesser General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using Remora.Discord.API.Abstractions.Gateway.Events;
using Remora.Discord.API.Tests.TestBases;

namespace Remora.Discord.API.Tests.Gateway.Events;

/// <summary>
/// Tests the Hello event.
/// </summary>
public class InviteDeleteTests : GatewayEventTestBase<IInviteDelete>
{
    /// <summary>
    /// Initializes a new instance of the <see cref="InviteDeleteTests"/> class.
    /// </summary>
    /// <param name="fixture">The test fixture.</param>
    public InviteDeleteTests(JsonBackedTypeTestFixture fixture)
        : base(fixture)
    {
    }
}


        try {
            MinecraftClient mc = MinecraftClient.getInstance();
            if (mc != null) {
                if (mc.world != null) {
                    String dim = mc.world.getRegistryKey().getValue().toString(); // e.g., "minecraft:overworld"
                    obs.addProperty("dimension", dim);
                }
                PlayerEntity p = mc.player;
                if (p != null) {
                    JsonObject coords = new JsonObject();
                    coords.addProperty("x", p.getX());
                    coords.addProperty("y", p.getY());
                    coords.addProperty("z", p.getZ());
                    obs.add("coords", coords);
                    obs.addProperty("health", (double) p.getHealth());
                    obs.addProperty("hunger", p.getHungerManager().getFoodLevel());
                    obs.addProperty("saturation", p.getHungerManager().getSaturationLevel());
                }
            }
        } catch (Throwable ignored) { /* never fail on telemetry */ }

        out.add("obs", obs);
        bus.publish(cfg.evtTopic, out.toString());
    }

    /* =========================
       Live-setting update API
       ========================= */

    /** Enable / disable publishing received chat to MQTT */
    public void setAllowChatRx(boolean v) {
        cfg.allowChatRx = v;
        // if needed: chatBridge.setAllowRx(v);
    }

    /** Enable / disable sending chat from MQTT to the server */
    public void setAllowChatTx(boolean v) {
        cfg.allowChatTx = v;
        // if needed: chatBridge.setAllowTx(v);
    }

    /** Enable / disable telemetry publishing */
    public void setAllowTelemetry(boolean v) {
        cfg.allowTelemetry = v;
        try { telemetryBridge.setAllowTelemetry(v); } catch (Throwable ignored) {}
    }

    /** Enable / disable acceptance of Baritone commands from MQTT */
    public void setAllowBaritone(boolean v) {
        cfg.allowBaritone = v;
        // if needed: baritoneBridge.setEnabled(v);
    }

    /** Update telemetry cadence in milliseconds. Also nudges the bridge if it has an internal scheduler. */
    public void setTelemetryIntervalMs(int ms) {
        if (ms < 50) ms = 50; // basic safety
        cfg.telemetryIntervalMs = ms;
        try { telemetryBridge.setIntervalMs(ms); } catch (Throwable ignored) {}
    }
}
/*
 * $Id: BadElementException.java 4784 2011-03-15 08:33:00Z blowagie $
 *
 * This file is part of the iText (R) project.
 * Copyright (c) 1998-2011 1T3XT BVBA
 * Authors: Bruno Lowagie, Paulo Soares, et al.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License version 3
 * as published by the Free Software Foundation with the addition of the
 * following permission added to Section 15 as permitted in Section 7(a):
 * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY 1T3XT,
 * 1T3XT DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA, 02110-1301 USA, or download the license from the following URL:
 * http://itextpdf.com/terms-of-use/
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public Licen


sCoverWidth = 90.0;
const _historiesCoverHeight = _historiesCoverWidth / vCoverRatio;

class HistoriesFragment2 extends StatelessWidget {
  Function() _handleRemove(BuildContext context, History history) =>
      () => BlocProvider.of<HistoriesBloc>(context)
          .add(HistoriesRemoveEvent(history: history));

  Function() _handleOpenHistory(BuildContext context, History history) =>
      () async {
        var platform =
            platformList.firstWhere((p) => p.domain == history.source.domain);
        if (platform != null) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ReadPage(
                platform: platform,
                comic: history.asComic(),
                initChapterReadAt: 0,
                chapters: [history.asChapter()],
              ),
            ),
          ).then((_) {
            // 返回后恢复系统 UI 并重新请求数据
            restoreStatusBarColor();
            showSystemUI();
            BlocProvider.of<HistoriesBloc>(context)
                .add(HistoriesRequestEvent());
          });
        }
      };

  Widget _buildEmptyView() {
    return Center(
      child: TextHint('没有阅读记录'),
    );
  }

  final cardShape = const RoundedRectangleBorder(
      borderRadius: BorderRadiusDirectional.all(Radius.circular(1)));

  Widget _buildListView(BuildContext context, List<History> histories) {
    return ListView(
      children: histories
          .map(
            (history) => Card(
              shape: cardShape,
              elevation: 1.5,
              child: Row(
                children: [
                  ExtendedImage.network(
                    history.cover,
                    headers: history.headers,
                    fit: BoxFit.cover,
                    height: _historiesCoverHeight,
                    width: _historiesCoverWidth,
                    cache: true,
                    loadStateChanged: (state) {
                      switch (state.extendedImageLoadState) {
                        case LoadState.failed:
                          return Center(
                            child: Text(
                              '无图',
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 18),
                            ),
                          ); // 加载失败显示标题文本
                          break;
                        default:
                          return null;
                          break;
                      }
                    },
                  ),
                  Expanded(
                    child: Column(
                      children: [
                        ListTile(
                          title: Text(
                            history.title,
                            maxLines: 2,
                            overflow: TextOverflow.clip,
                            style: TextStyle(
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          subtitle: Wrap(
                            children: [
                              Text(
                                '${history.source.name}',
                                style: TextStyle(color: Colors.black),
                              ),
                            ],
                          ),
                        ),
                        ButtonBar(
                          buttonPadding: EdgeInsets.zero,
                          alignment: MainAxisAlignment.start,
                          children: [
                            FlatButton(
                              child: const Text(
                                '移除',
                                style: TextStyle(color: Colors.redAccent),
                              ),
                              onPressed: _handleRemove(context, history),
                            ),
                            FlatButton(
                              child: const Text(
                                '继续阅读',
                                style: TextStyle(color: Colors.blueAccent),


ms Illuminated: Part II, Graph Algorithms and Data Structures](https://drive.google.com/open?id=13txnsORZO60P-RqOKJ-LrCffmuvgJ9hd) | Tim Roughgarden | 2017 |
| [The Algorithm Design Manual](https://drive.google.com/open?id=1Eg5vwyDqkWFV7lz_5JCZmWEmFoY1imXT) | Skiena | 2nd (2008) |
| [Introduction To The Design & Analysis of Algorithms](https://drive.google.com/open?id=1K5wdR2czW-CIRUAGgTLZnTP6m2zu9fyU) | Anany Levitin | 3rd (2012) |
| [Foundations of Algorithms](https://drive.google.com/open?id=1gDln3tWIpcV82LP7AjRG4oQCUpJhhXRZ) | Richard Neopolitan | 5th (2015) |

## Code

*   [Algorithms & Data Structures Project, *William Fiset*](https://github.com/williamfiset/Algorithms)
*   [WhatsAlgo, *Mohammed Shoaib*](https://github.com/Mohammed-Shoaib/WhatsAlgo)

## Videos
*	[Algorithms Specialization, *Stanford University*](https://www.coursera.org/specializations/algorithms)
*	[Algorithms, *Abdul Bari*](https://www.youtube.com/watch?v=0IAPZzGSbME&list=PLDN4rrl48XKpZkf03iYFl-O29szjTrs_O)
*	[Design and Analysis of Algorithms, *MIT Spring 2015*](https://www.youtube.com/playlist?list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp)
*	[Quick Sort, *Michael Sambol*](https://www.youtube.com/watch?v=Hoixgm4-P4M&feature=youtu.be)
*	[Four Color Theorem, *Up and Atom*](https://www.youtube.com/watch?v=42-ws3bkrKM&feature=youtu.be)
*	[Approximation Algorithms, *UHMICSAlgorithms*](https://www.youtube.com/watch?v=hdch8ioLRqE&feature=youtu.be)
*	[Network Flow, *UC Davis*](https://www.youtube.com/watch?v=_G6_-ljgmXE&feature=youtu.be)
*	[Design and Analysis of Algorithms, *Gate Smashers - Hindi*](https://www.youtube.com/watch?v=u8JZ9gU5o4g&list=PLxCzCOWd7aiHcmS4i14bI0VrMbZTUvlTa)

## Websites
*	[TOC Directory, *KR Chowdhary*](http://www.krchowdhary.com/toc/)
*	[P v NP, *Brilliant.Org*](https://brilliant.org/wiki/p-versus-np/)
*	[Vertex Cover Problem, *Brilliant.Org*](https://brilliant.org/wiki/vertex-cover/)
*	[Travelling Salesman Problem, *Brilliant.Org*](https://brilliant.org/wiki/traveling-salesperson-problem/)
*	[Ford Fulkerson Algorithm, *Brilliant.Org*](https://brilliant.org/wiki/ford-fulkerson-algorithm/)
*	[Introduction and Sorting Algorithms (T1 Notes), *lecturenotes.in*](https://lecturenotes.in/notes/17784-note-for-design-and-analysis-of-algorithm-daa-by-shekharesh-barik?reading=true)
*	[Recurrence Relation, *Stanford University*](https://web.stanford.edu/class/archive/cs/cs161/cs161.1168/lecture3.pdf)

## Apps
*   [Algorithms: Explained and Animated](http://algorithm.wiki/en/app/)
# Artificial Intelligence

## Overview

AI introduces students to basic concepts and methods of Artificial Intelligence from a computer science perspective.


          this._eatBits(12);
          if (this.encoding > 0) {
            this._lookBits(1);
            this._eatBits(1);
          }
          if (this.encoding >= 0) {
            for (i = 0; i < 4; ++i) {
              code1 = this._lookBits(12);
              if (code1 !== 1) {
                info("bad rtc code: " + code1);
              }
              this._eatBits(12);
              if (this.encoding > 0) {
                this._lookBits(1);
                this._eatBits(1);
              }
            }
          }
          this.eof = true;
        }
      } else if (this.err && this.eoline) {
        while (true) {
          code1 = this._lookBits(13);
          if (code1 === ccittEOF) {
            this.eof = true;
            return -1;
          }
          if (code1 >> 1 === 1) {
            break;
          }
          this._eatBits(1);
        }
        this._eatBits(12);
        if (this.encoding > 0) {
          this._eatBits(1);
          this.nextLine2D = !(code1 & 1);
        }
      }
      this.outputBits = codingLine[0] > 0 ? codingLine[this.codingPos = 0] : codingLine[this.codingPos = 1];
      this.row++;
    }
    let c;
    if (this.outputBits >= 8) {
      c = this.codingPos & 1 ? 0 : 0xff;
      this.outputBits -= 8;
      if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
        this.codingPos++;
        this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
      }
    } else {
      bits = 8;
      c = 0;
      do {
        if (typeof this.outputBits !== "number") {
          throw new FormatError('Invalid /CCITTFaxDecode data, "outputBits" must be a number.');
        }
        if (this.outputBits > bits) {
          c <<= bits;
          if (!(this.codingPos & 1)) {
            c |= 0xff >> 8 - bits;
          }
          this.outputBits -= bits;
          bits = 0;
        } else {
          c <<= this.outputBits;
          if (!(this.codingPos & 1)) {
            c |= 0xff >> 8 - this.outputBits;
          }
          bits -= this.outputBits;
          this.outputBits = 0;
          if (codingLine[this.codingPos] < columns) {
            this.codingPos++;
            this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
          } else if (bits > 0) {
            c <<= bits;
            bits = 0;
          }
        }
      } while (bits);
    }
    if (this.black) {
      c ^= 0xff;
    }
    return c;
  }
  _addPixels(a1, blackPixels) {
    const codingLine = this.codingLine;
    let codingPos = this.codingPos;
    if (a1 > codingLine[codingPos]) {
      if (a1 > this.columns) {
        info("row is wrong length");
        this.err = true;
        a1 = this.columns;
      }
      if (codingPos & 1 ^ blackPixels) {
        ++codingPos;
      }
      codingLine[codingPos] = a1;
    }
    this.codingPos = codingPos;
  }
  _addPixelsNeg(a1, blackPixels) {
    const codingLine = this.codingLine;
    let codingPos = this.codingPos;
    i


pace(string(gopath)))
	wd, err := os.Getwd()
	if err != nil {
		return err
	}

	if out, err := exec.Command(
		tern,
		"migrate",
		"--conn-string",
		jobqueuetest.TestDbURL(),
		"-m",
		fmt.Sprintf("%s/../../pkg/jobqueue/dbjobqueue/schemas", wd),
		"-d",
		migration,
	).CombinedOutput(); err != nil {
		fmt.Println("tern output:", string(out))
		return err
	}
	return nil
}

func TestJobQueueInterface(t *testing.T) {
	makeJobQueue := func(migration string, clean bool) (jobqueue.JobQueue, func(), error) {
		err := migrate(migration)
		if err != nil {
			return nil, nil, err
		}

		if clean {
			conn, err := pgx.Connect(context.Background(), jobqueuetest.TestDbURL())
			if err != nil {
				return nil, nil, err
			}
			defer conn.Close(context.Background())
			for _, table := range []string{"job_dependencies", "heartbeats", "jobs"} {
				_, err = conn.Exec(context.Background(), fmt.Sprintf("DELETE FROM %s", table))
				if err != nil {
					return nil, nil, err
				}
			}
			err = conn.Close(context.Background())
			if err != nil {
				return nil, nil, err
			}
		}

		q, err := dbjobqueue.New(jobqueuetest.TestDbURL())
		if err != nil {
			return nil, nil, err
		}
		stop := func() {
			q.Close()
		}
		return q, stop, nil
	}

	// run first, as migrations aren't reversible
	testMigrationPath(t, makeJobQueue)

	jobqueuetest.TestJobQueue(t, func () (jobqueue.JobQueue, func(), error) {
		return makeJobQueue("last", true)
	})
}

func testMigrationPath(t *testing.T, makeJobQueue func(migration string, clean bool) (jobqueue.JobQueue, func(), error)) {
	q, stop, err := makeJobQueue("8", false)
	defer stop()
	require.NoError(t, err)

	id, err := q.Enqueue("test", "{\"arg\": \"impormtanmt\"}", nil, "")
	require.NoError(t, err)
	require.NotEmpty(t, id)
	id, tok, _, _, _, err := q.Dequeue(context.Background(), uuid.Nil, []string{"test"}, []string{""})
	require.NoError(t, err)
	require.NotEmpty(t, id)
	require.NotEmpty(t, tok)

	// make sure entering escaped nullbytes fails in 8
	_, err = q.RequeueOrFinishJob(id, 0, &jobqueuetest.TestResult{Logs: []byte("{\"blegh\\u0000\": \"\\u0000reallyimportant stuff!\"}")})
	require.Error(t, err)

	tr := jobqueuetest.TestResult{Logs: []byte("{\"blegh\": \"really important stuff!\"}")}
	_, err = q.RequeueOrFinishJob(id, 0, &tr)
	require.NoError(t, err)

	require.NoError(t, migrate("last"))

	// reopen the connection to the db, as the old connection will still treat the result column as jsonb
	stop()
	db_q, err := dbjobqueue.New(jobqueuetest.TestDbURL())
	require.NoError(t, err)
	defer db_q.Close()
	require.NoError(t, err)

	// make sure entering escaped nullbytes works in last
	id2, err := db_q.Enqueue("test", "{\"arg\": \"impormtanmt\"}", nil, "")
	require.NoError(t, err)
	require.NotEmpty(t, id2)


76 6.5537194 24 6.0488281 z M 19.990234 18.990234 A 1.0001 1.0001 0 0 0 19.292969 20.707031 L 23.585938 25 L 19.292969 29.292969 A 1.0001 1.0001 0 1 0 20.707031 30.707031 L 25 26.414062 L 29.292969 30.707031 A 1.0001 1.0001 0 1 0 30.707031 29.292969 L 26.414062 25 L 30.707031 20.707031 A 1.0001 1.0001 0 0 0 29.980469 18.990234 A 1.0001 1.0001 0 0 0 29.292969 19.292969 L 25 23.585938 L 20.707031 19.292969 A 1.0001 1.0001 0 0 0 19.990234 18.990234 z"/></svg>',I8='<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>',T8='<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 50 50" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M 21 3 C 11.621094 3 4 10.621094 4 20 C 4 29.378906 11.621094 37 21 37 C 24.710938 37 28.140625 35.804688 30.9375 33.78125 L 44.09375 46.90625 L 46.90625 44.09375 L 33.90625 31.0625 C 36.460938 28.085938 38 24.222656 38 20 C 38 10.621094 30.378906 3 21 3 Z M 21 5 C 29.296875 5 36 11.703125 36 20 C 36 28.296875 29.296875 35 21 35 C 12.703125 35 6 28.296875 6 20 C 6 11.703125 12.703125 5 21 5 Z M 13 12 L 13 18 L 15.28125 15.71875 L 19.5625 20 L 15.28125 24.28125 L 13 22 L 13 28 L 19 28 L 16.71875 25.71875 L 21 21.4375 L 25.28125 25.71875 L 23 28 L 29 28 L 29 22 L 26.71875 24.28125 L 22.4375 20 L 26.71875 15.71875 L 29 18 L 29 12 L 23 12 L 25.28125 14.28125 L 21 18.5625 L 16.71875 14.28125 L 19 12 Z"/></svg>',_8='<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="11" y1="8" x2="11" y2="14"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>',P8=(t,a,c)=>{let r=t.settings.folderIcon,e=Jt,h=


еан",
        "IQ": "Ирак",
        "IR": "Иран",
        "IS": "Исландия",
        "IT": "Италия",
        "JE": "Джърси",
        "JM": "Ямайка",
        "JO": "Йордания",
        "JP": "Япония",
        "KE": "Кения",
        "KG": "Киргизстан",
        "KH": "Камбоджа",
        "KI": "Кирибати",
        "KM": "Коморски острови",
        "KN": "Сейнт Китс и Невис",
        "KP": "Северна Корея",
        "KR": "Южна Корея",
        "KW": "Кувейт",
        "KY": "Кайманови острови",
        "KZ": "Казахстан",
        "LA": "Лаос",
        "LB": "Ливан",
        "LC": "Сейнт Лусия",
        "LI": "Лихтенщайн",
        "LK": "Шри Ланка",
        "LR": "Либерия",
        "LS": "Лесото",
        "LT": "Литва",
        "LU": "Люксембург",
        "LV": "Латвия",
        "LY": "Либия",
        "MA": "Мароко",
        "MC": "Монако",
        "MD": "Молдова",
        "ME": "Черна гора",
        "MF": "Сен Мартен",
        "MG": "Мадагаскар",
        "MH": "Маршалови острови",
        "MK": "Македония",
        "ML": "Мали",
        "MM": "Мианмар (Бирма)",
        "MN": "Монголия",
        "MO": "Макао, САР на Китай",
        "MP": "Северни Мариански острови",
        "MQ": "Мартиника",
        "MR": "Мавритания",
        "MS": "Монтсерат",
        "MT": "Малта",
        "MU": "Мавриций",
        "MV": "Малдиви",
        "MW": "Малави",
        "MX": "Мексико",
        "MY": "Малайзия",
        "MZ": "Мозамбик",
        "NA": "Намибия",
        "NC": "Нова Каледония",
        "NE": "Нигер",
        "NF": "остров Норфолк",
        "NG": "Нигерия",
        "NI": "Никарагуа",
        "NL": "Нидерландия",
        "NO": "Норвегия",
        "NP": "Непал",
        "NR": "Науру",
        "NU": "Ниуе",
        "NZ": "Нова Зеландия",
        "OM": "Оман",
        "PA": "Панама",
        "PE": "Перу",
        "PF": "Френска Полинезия",
        "PG": "Папуа-Нова Гвинея",
        "PH": "Филипини",
        "PK": "Пакистан",
        "PL": "Полша",
        "PM": "Сен Пиер и Микелон",
        "PN": "Острови Питкерн",
        "PR": "Пуерто Рико",


i] and pLeft[(4+i)*kiStride]
    ld1     {v0.b}[0], [x2], #1
    ld1     {v0.b}[1], [x2], #1
    ld1     {v0.b}[2], [x2], #1
    ld1     {v0.b}[3], [x2], #1
    ld1     {v0.b}[4], [x3], x1
    ld1     {v0.b}[5], [x3], x1
    ld1     {v0.b}[6], [x3], x1
    ld1     {v0.b}[7], [x3], x1

    uxtl    v1.8h, v1.8b
    uxtl    v0.8h, v0.8b
    ldr     q2, intra_1_to_4
    ldr     q3, intra_m3_to_p4
    dup     v4.8h, v0.h[3]
    dup     v5.8h, v0.h[7]
    add     v4.8h, v4.8h, v5.8h
    sub     v0.8h, v0.8h, v1.8h
    shl     v4.8h, v4.8h, #4 // v4.8h is a
    mul     v0.8h, v0.8h, v2.8h // v0.h[0-3] is H, v0.h[4-7] is V
    saddlp  v0.4s, v0.8h
    addp    v0.4s, v0.4s, v0.4s // v0.s[0] is H, v0.s[1] is V
    sqrshrn v0.4h, v0.4s, #5
    dup     v1.8h, v0.h[0]      // v1.8h is b
    dup     v0.8h, v0.h[1]      // v0.8h is c
    mla     v4.8h, v1.8h, v3.8h
    mla     v4.8h, v0.8h, v3.h[0]
    sqrshrun v1.8b, v4.8h, #5
    st1     {v1.8b}, [x0], x1
.rept 7
    add     v4.8h, v4.8h, v0.8h
    sqrshrun v1.8b, v4.8h, #5
    st1     {v1.8b}, [x0], x1
.endr
WELS_ASM_AARCH64_FUNC_END

//for Luma 16x16
WELS_ASM_AARCH64_FUNC_BEGIN WelsDecoderI16x16LumaPredV_AArch64_neon
    sxtw    x1, w1
    sub     x2, x0, x1
    ld1     {v0.16b}, [x2]
.rept 16
    st1     {v0.16b}, [x0], x1
.endr
WELS_ASM_AARCH64_FUNC_END

WELS_ASM_AARCH64_FUNC_BEGIN WelsDecoderI16x16LumaPredH_AArch64_neon
    sxtw    x1, w1
    sub     x2, x0, #1
.rept 16
    ld1r    {v0.16b}, [x2], x1
    st1     {v0.16b}, [x0], x1
.endr
WELS_ASM_AARCH64_FUNC_END

WELS_ASM_AARCH64_FUNC_BEGIN WelsDecoderI16x16LumaPredDc_AArch64_neon
    sxtw    x1, w1
    sub     x2, x0, x1
    sub     x3, x0, #1
    ld1     {v0.16b}, [x2]
    ld1     {v1.b}[0], [x3], x1
    ld1     {v1.b


an_list, ner_types, ner_type, re_id_list, correct_tokens, total_tokens, order_id = re_identify_one_span(file_to_re_id, retriever, query_tokenizer, doc_encodings, chunks, reader, reader_tokenizer, 1, span_list, ner_types, re_id_list, order_id, device)
        except:
            print("Could not re-identify!")
            continue
        num_correct += correct
        total_per_ner_type[ner_type] += 1
        correct_per_ner_type[ner_type] += correct
        correct_pred_tokens += correct_tokens
        total_pred_tokens += total_tokens
        correct_pred_tokens_per_ner_type[ner_type] += correct_tokens
        total_pred_tokens_per_ner_type[ner_type] += total_tokens

    progress_bar.update()

    total_correct += num_correct

    files_re_identified.append(file_to_re_id)

    re_identified_spans = []
    j = -1
    for pos in order_id[::-1]:
        re_identified_spans.insert(pos, re_id_list[j])
        j -= 1

    re_identified_spans_per_doc.append(re_identified_spans)

    raws[i]["re-identified_file"] = file_to_re_id
    raws[i]["re-identifed_spans"] = re_identified_spans

progress_bar.close()

print(f"Exact Match: {(total_correct / total_num_masks) * 100:.2f}")
print(f"Token Recall: {(correct_pred_tokens / total_pred_tokens) * 100:.2f}")

for k, i in total_per_ner_type.items():
    print(f"Exact Match ({k}): {(correct_per_ner_type[k] / float(i)) * 100:.2f}")

for k, i in total_pred_tokens_per_ner_type.items():
    print(f"Token Recall ({k}): {(correct_pred_tokens_per_ner_type[k] / float(i)) * 100:.2f}")

with open("results_clinical_all_run_3.txt", "w") as f:
    f.write(f"Exact Match: {(total_correct / total_num_masks) * 100:.2f}\n")
    f.write(f"Token Recall: {(correct_pred_tokens / total_pred_tokens) * 100:.2f}\n")
    f.write("\n")

    for k, i in total_per_ner_type.items():
        f.write(f"Exact Match ({k}): {(correct_per_ner_type[k] / float(i)) * 100:.2f}\n")

    for k, i in total_pred_tokens_per_ner_type.items():
        f.write(f"Token Recall ({k}): {(correct_pred_tokens_per_ner_type[k] / float(i)) * 100:.2f}\n")

with open("../datasets/Re-identified_clinical_all.jsonl", "w") as fo:
    for datapoint in raws:
        fo.write(json.dumps(datapoint))
        fo.write("\n")


mut dom_updater;

    {
        let mut input = make_input_component(Rc::clone(&text));
        input
            .as_velement_mut()
            .expect("Not an element")
            .attrs
            .insert("id".into(), "old-input-elem".into());

        let mount = document.create_element("div").unwrap();
        mount.set_id("mount");
        document.body().unwrap().append_child(&mount).unwrap();

        dom_updater = Some(DomUpdater::new_replace_mount(input, mount));

        let dom_updater = dom_updater.as_mut().unwrap();

        // Input VirtualNode from above gets dropped at the end of this block,
        // yet that element held Rc's to the Closure's that power the oninput event.
        //
        // We're patching the DOM with a new vdom, but since our new vdom doesn't contain any
        // new elements, `.create_element` won't get called and so no new Closures will be
        // created.
        //
        // So, we're testing that our old Closure's still work. The reason that they work is
        // that dom_updater maintains Rc's to those Closures.
        let mut new_node = make_input_component(Rc::clone(&text));
        new_node
            .as_velement_mut()
            .expect("Not an element")
            .attrs
            .insert("id".into(), "new-input-elem".into());

        dom_updater.update(new_node);
    }

    let dom_updater = dom_updater.as_ref().unwrap();

    let input: HtmlInputElement = document
        .get_element_by_id("new-input-elem")
        .expect("Input element")
        .dyn_into()
        .unwrap();
    let input_event = InputEvent::new("input").unwrap();

    assert_eq!(&*text.borrow(), "Start Text");

    // After dispatching the oninput event our `text` should have a value of the input elements value.
    web_sys::EventTarget::from(input)
        .dispatch_event(&input_event)
        .unwrap();

    assert_eq!(&*text.borrow(), "End Text");

    assert_eq!(
        dom_updater.active_closures.get(&1).as_ref().unwrap().len(),
        1
    );
}

// We're just making sure that things compile - other tests give us confidence that the closure
// will work just fine.
//
// https://github.com/chinedufn/percy/issues/81
//
//#[wasm_bindgen_test]
//fn closure_with_no_params_compiles() {
//    let _making_sure_this_works = html! {
//

//    };
//}

fn make_input_component(text_clone: Rc<RefCell<String>>) -> VirtualNode {
    html! {
        <input
           // On input we'll set our Rc<RefCell<String>> value to the input elements value
           oninput=move |event: InputEvent| {
              let input_elem = event.target().unwrap();
              let input_elem = input_elem.dyn_into::<HtmlInputElement>().unwrap();
              *text_clone.borrow_mut() = input_elem.value();
           }
           value="End Text"
        >
    }
}
fn main() {
    cc::Build::new()
        .cpp(true)
        .file("cc/AudioInterface.cc")
        .file("cc/AudioPlayer.cc")
        .compile("libezaudio.a");
}
<gh_stars>10-100
use std::io::Result;
use std::net::{SocketAddr, ToSocketAddrs};

pub fn resolve(addr: &str, port: u16) -> Result<SocketAddr> {
    (addr, port)


/B>
Constant Field Values

MONO_TABLE_IMPLMAP

static final int MONO_TABLE_IMPLMAP

See Also:
Constant Field Values

MONO_TABLE_FIELDRVA

static final int MONO_TABLE_FIELDRVA

See Also:
Constant Field Values

MONO_TABLE_UNUSED6

static final int MONO_TABLE_UNUSED6

See Also:
Constant Field Values

MONO_TABLE_UNUSED7

static final int MONO_TABLE_UNUSED7

See Also:
Constant Field Values

MONO_TABLE_ASSEMBLY

static final int MONO_TABLE_ASSEMBLY

See Also:
Constant Field Values

MONO_TABLE_ASSEMBLYPROCESSOR

static final int MONO_TABLE_ASSEMBLYPROCESSOR

See Also:
Constant Field Values

MONO_TABLE_ASSEMBLYOS

static final int MONO_TABLE_ASSEMBLYOS

See Also:
<A HREF="../../../constant-values.html#com.nativelibs4


tiveUnits = "NativeUnits.";

        /// <summary>
        /// As advertised value for the measurement.
        /// </summary>
        public const string Nominal = "As advertised value for the measurement.";

        /// <summary>
        /// Number of significant digits in the reported value.
        /// </summary>
        public const string SignificantDigits = "Number of significant digits in the reported value.";

        /// <summary>
        /// Units.
        /// </summary>
        public const string Units = "Units.";

        /// <summary>
        ///
        /// </summary>
        public const string Value = "";
    }
}


			State: State{
				ChainID("consu"): ChainState{
					ConsumerCommissionRates: &map[ValidatorID]float64{
						ValidatorID("alice"): 0.1,
						ValidatorID("bob"):   0.123,
						ValidatorID("carol"): 0.1,
					},
				},
			},
		},
		{
			Action: UpdateConsumerChainAction{
				Chain:         ChainID("provi"),
				From:          ValidatorID("alice"),
				ConsumerChain: ChainID("consu"),
				InitParams: &InitializationParameters{
					InitialHeight: clienttypes.Height{RevisionNumber: 0, RevisionHeight: 1},
					SpawnTime:     0, // launch now
				},
				PowerShapingParams: &PowerShapingParameters{
					TopN: 0,
				},
			},
			State: State{},
		},
		{
			// we start all the validators but only "alice" and "bob" have opted in and hence
			// only "alice" and "bob" are validating blocks
			Action: StartConsumerChainAction{
				ConsumerChain: ChainID("consu"),
				ProviderChain: ChainID("provi"),
				Validators: []StartChainValidator{
					{Id: ValidatorID("alice"), Stake: 100000000, Allocation: 10000000000},
					{Id: ValidatorID("bob"), Stake: 200000000, Allocation: 10000000000},
					{Id: ValidatorID("carol"), Stake: 300000000, Allocation: 10000000000},
				},
			},
			State: State{
				ChainID("consu"): ChainState{
					ValPowers: &map[ValidatorID]uint{
						ValidatorID("alice"): 100,
						ValidatorID("bob"):   200,
						// carol has not yet opted in
						ValidatorID("carol"): 0,
					},
				},
			},
		},
		{
			Action: AddIbcConnectionAction{
				ChainA:  ChainID("consu"),
				ChainB:  ChainID("provi"),
				ClientA: 0,
				ClientB: 0,
			},
			State: State{},
		},
		{
			Action: AddIbcChannelAction{
				ChainA:      ChainID("consu"),
				ChainB:      ChainID("provi"),
				ConnectionA: 0,
				PortA:       "consumer",
				PortB:       "provider",
				Order:       "ordered",
			},
			State: State{},
		},
		{
			Action: OptInAction{
				Chain:     ChainID("consu"),
				Validator: ValidatorID("carol"),
			},
			State: State{
				ChainID("consu"): ChainState{
					ValPowers: &map[ValidatorID]uint{
						ValidatorID("alice"): 100,
						ValidatorID("bob"):   200,
						// "carol" has opted in, but the VSCPacket capturing the opt-in was not relayed yet
						ValidatorID("carol"): 0,
					},
				},
				ChainID("provi"): ChainState{
					HasToValidate: &map[ValidatorID][]ChainID{
						ValidatorID("alice"): {"consu"},
						ValidatorID("bob"):   {"consu"},
						ValidatorID("carol"): {"consu"},
					},
				},
			},
		},
		{
			// assign the consumer key "carol" is using on the consumer chain to be the one "carol" uses when opting in
			Action: AssignConsumerPubKeyAction{
				Chain:     ChainID("consu"),
				Validator: ValidatorID("carol"),
				// reconfigure the node -> validator was using provider key
				// until this point -> key matches config.consumerValPubKey for "carol"
				ConsumerPubkey:  getDefaultValidators()[ValidatorID("carol")].ConsumerValPubKey,
				ReconfigureNode: true,
			},
			State: State{},
		},
		{
			Action: RelayPacketsAction{
				ChainA:  ChainID("provi"),
				ChainB:  ChainID("consu"),
				Port:    "


 middle" + highlightSuffix;
        }

        beginText(end, "highlight end" + highlightSuffix);
      }

      prevEnd = end;
    }

    if (prevEnd) {
      appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
    }
  }

  _updateMatches() {
    if (!this.renderingDone) {
      return;
    }

    const {
      findController,
      matches,
      pageIdx,
      textContentItemsStr,
      textDivs
    } = this;
    let clearedUntilDivIdx = -1;

    for (let i = 0, ii = matches.length; i < ii; i++) {
      const match = matches[i];
      const begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);

      for (let n = begin, end = match.end.divIdx; n <= end; n++) {
        const div = textDivs[n];
        div.textContent = textContentItemsStr[n];
        div.className = "";
      }

      clearedUntilDivIdx = match.end.divIdx + 1;
    }

    if (!findController || !findController.highlightMatches) {
      return;
    }

    const pageMatches = findController.pageMatches[pageIdx] || null;
    const pageMatchesLength = findController.pageMatchesLength[pageIdx] || null;
    this.matches = this._convertMatches(pageMatches, pageMatchesLength);

    this._renderMatches(this.matches);
  }

  _bindMouse() {
    const div = this.textLayerDiv;
    let expandDivsTimer = null;
    div.addEventListener("mousedown", evt => {
      if (this.enhanceTextSelection && this.textLayerRenderTask) {
        this.textLayerRenderTask.expandTextDivs(true);

        if (expandDivsTimer) {
          clearTimeout(expandDivsTimer);
          expandDivsTimer = null;
        }

        return;
      }

      const end = div.querySelector(".endOfContent");

      if (!end) {
        return;
      }

      let adjustTop = evt.target !== div;
      adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue("-moz-user-select") !== "none";

      if (adjustTop) {
        const divBounds = div.getBoundingClientRect();
        const r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
        end.style.top = (r * 100).toFixed(2) + "%";
      }

      end.classList.add("active");
    });
    div.addEventListener("mouseup", () => {
      if (this.enhanceTextSelection && this.textLayerRenderTask) {
        expandDivsTimer = setTimeout(() => {
          if (this.textLayerRenderTask) {
            this.textLayerRenderTask.expandTextDivs(false);
          }

          expandDivsTimer = null;
        }, EXPAND_DIVS_TIMEOUT);
        return;
      }

      const end = div.querySelector(".endOfContent");

      if (!end) {
        return;
      }

      end.style.top = "";
      end.classList.remove("active");
    });
  }

}

exports.TextLayerBuilder = TextLayerBuilder;

class DefaultTextLayerFactory {
  createTextLayerBuilder(textLayerDiv, pageIndex, viewport, enhanceTextSelection = false, eventBus) {
    return new TextLayerBuilder({
      textLayerDiv,
      pageIndex,
      viewport,
      enhanceTextSelection,
      eventBus
    });
  }

}

exports.DefaultTextLayerFactory = DefaultTextLayerFactory;

/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SecondaryToolbar = void 0;

var _ui_utils = __webpack_require__(2);

var _pdf_cursor_tools = __webpack_require__(6);

var _pdf_single_


) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.SecurityDataContract.(*_SecurityData).getLengthInBits(ctx))

	return lengthInBits
}

func (m *_SecurityDataTamperOn) GetLengthInBytes(ctx context.Context) uint16 {
	return m.GetLengthInBits(ctx) / 8
}

func (m *_SecurityDataTamperOn) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_SecurityData) (__securityDataTamperOn SecurityDataTamperOn, err error) {
	m.SecurityDataContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("SecurityDataTamperOn"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for SecurityDataTamperOn")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	if closeErr := readBuffer.CloseContext("SecurityDataTamperOn"); closeErr != nil {
		return nil, errors.Wrap(closeErr, "Error closing for SecurityDataTamperOn")
	}

	return m, nil
}

func (m *_SecurityDataTamperOn) Serialize() ([]byte, error) {
	wb := utils.NewWriteBufferByteBased(utils.WithInitialSizeForByteBasedBuffer(int(m.GetLengthInBytes(context.Background()))))
	if err := m.SerializeWithWriteBuffer(context.Background(), wb); err != nil {
		return nil, err
	}
	return wb.GetBytes(), nil
}

func (m *_SecurityDataTamperOn) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("SecurityDataTamperOn"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for SecurityDataTamperOn")
		}

		if popErr := writeBuffer.PopContext("SecurityDataTamperOn"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for SecurityDataTamperOn")
		}
		return nil
	}
	return m.SecurityDataContract.(*_SecurityData).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_SecurityDataTamperOn) IsSecurityDataTamperOn() {}

func (m *_SecurityDataTamperOn) DeepCopy() any {
	return m.deepCopy()
}

func (m *_SecurityDataTamperOn) deepCopy() *_SecurityDataTamperOn {
	if m == nil {
		return nil
	}
	_SecurityDataTamperOnCopy := &_SecurityDataTamperOn{
		m.SecurityDataContract.(*_SecurityData).deepCopy(),
	}
	_SecurityDataTamperOnCopy.SecurityDataContract.(*_SecurityData)._SubType = m
	return _SecurityDataTamperOnCopy
}

func (m *_SecurityDataTamperOn) String() string {
	if m == nil {
		return "<nil>"
	}
	wb := utils.NewWriteBufferBoxBased(
		utils.WithWriteBufferBoxBasedMergeSingleBoxes(),
		utils.WithWriteBufferBoxBasedOmitEmptyBoxes(),
		utils.WithWriteBufferBoxBasedPrintPosLengthFooter(),
	)
	if err := wb.WriteSerializable(context.Background(), m); err != nil {
		return err.Error()
	}
	return wb.GetBox().String()
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *


                   }
                    else if ((dr["ek3"].ToString() == "-") && (dr["ek2"].ToString() != "-") && (dr["ek1"].ToString() != "-"))
                    {
                        string Query = "update musteriler set ek3='" + mk_ekücret.Text + " TL - " + mk_ekislem.Text + "' where musteri='" + a1 + "' AND arac='" + a3 + "';";
                        MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
                        MySqlDataReader MyReader2;
                        MyReader2 = MyCommand2.ExecuteReader();
                        while (MyReader2.Read())
                        {
                        }
                        con.Close();
                    }
                    else if ((dr["ek2"].ToString() == "-") && (dr["ek1"].ToString() != "-"))
                    {
                        string Query = "update musteriler set ek2='" + mk_ekücret.Text + " TL - " + mk_ekislem.Text + "' where musteri='" + a1 + "' AND arac='" + a3 + "';";
                        MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
                        MySqlDataReader MyReader2;
                        MyReader2 = MyCommand2.ExecuteReader();
                        while (MyReader2.Read())
                        {
                        }
                        con.Close();
                    }
                    else
                    {
                        string Query = "update musteriler set ek1='" + mk_ekücret.Text + " TL - " + mk_ekislem.Text + "' where musteri='" + a1 + "' AND arac='" + a3 + "';";
                        MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
                        MySqlDataReader MyReader2;
                        MyReader2 = MyCommand2.ExecuteReader();
                        while (MyReader2.Read())
                        {
                        }
                        con.Close();
                    }
                }
                mk_ekislem.Text = "EK İŞLEM";
                mk_ekücret.Text = "EK İŞLEM ÜCRETİ";
                mk_bul.SelectedIndex = -1;
                mk_bul.SelectedIndex = mk_bul.FindStringExact(a1 + " - " + a2 + " * " + a3);
                con.Close();
            }
            else
            {
                MessageBox.Show("Lütfen bütün alanları doldurunuz!");
            }
            con.Close();
        }

        private void kayitsil_Click(object sender, EventArgs e)
        {
            if (mk_bul.SelectedIndex >= 0)
            {
                if ((MessageBox.Show("Seçilen veriyi kalıcı olarak silmek istediğinize emin misiniz?", "UYARI", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes))
                {
                    string a1 = mk_bul.SelectedItem.ToString().Split('-')[0].Remove(mk_bul.SelectedItem.ToString().Split('-')[0].Length - 1);
                    string aa = mk_bul.SelectedItem.ToString().Split('-')[1].Remove(0, 1);
                    string a2 = aa.ToString().Split('*')[0].Remove(aa.ToString().Split('*')[0].Length - 1);
                    string a3 = aa.ToString().Split('*')[1].Remove(0, 1);
                    string Query = "delete from musteriler where musteri='" + a1 + "' AND arac='" + a3 + "' AND yil='" + a2 + "';";
                    MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
                    MySqlDataReader MyReader2;
                    con.Open();
                    MyReader2 = MyCommand2.ExecuteReader();
                    con.Close();
                    musteribul();
                }
            }
            else
            {
                MessageBox.Show("Lütfen önce bir kayıt


         this@CustomWarningParent,
                screen
            ) as CustomFlexBox
        }
        val heights = FloatArray(3) //max nbr of frames till it works //TODO VERY ugly
        delayUntil {
            if (current?.height == 0F) return@delayUntil false
            val old = heights.clone()
            for (i in 1 until heights.size) heights[i] = old[i - 1]
            heights[0] = current!!.height
//            current?.invalidate()
            heights.none { it != old[old.size - 1] }
        }
        action {
            curShown.add(current!!)
            includeAction(getInitialTimeline(current!!, title.length * 2 + body.length, permanentIndex).asAction())
        }
    }

    private fun moveUpTimeline(current: CustomFlexBox): Timeline {
        return Timeline.timeline {
            var startTime = 0L
            val duration = 200F
            action {
                percentageOfNewestHeight = 0F
                startTime = System.currentTimeMillis()
            }
            delayUntil {
                percentageOfNewestHeight = min((System.currentTimeMillis() - startTime) / duration, 1F)
                percentageOfNewestHeight == 1F
            }
        }
    }

    private fun getInitialTimeline(target: CustomFlexBox, textLength: Int, permanentIndex: Int): Timeline {
        return Timeline.timeline {
            action {
                target.offsetX = -target.width
                //this might be the ugliest but best possible solution ever //TODO ugly
                val label = ((target.children[1] as CustomFlexBox).children[2] as CustomLabel)
                val lastRowHeight = label.glyphLayout.runs.first().glyphs[0].height * label.fontScaleX
                val data = YogaValue(target.height + DIST_BETWEEN_BLOCKS + lastRowHeight, YogaUnit.POINT)
                val dataClass = data::class
                val instruction = StyleInstruction(data, 10, StyleCondition.Always, dataClass)
                @Suppress("UNCHECKED_CAST")
                instruction as StyleInstruction<Any>
                target.styleManager?.addInstruction("height", instruction, dataClass)
            }
            val action = CustomMoveByAction(
                target,
                Interpolation.exp10Out,
                relX = target.width,
                duration = 200F
            )
            parallelActions(
                moveUpTimeline(target).asAction(),
                Timeline.timeline {
                    action {
                        target.addAction(action)
                        if (permanentIndex == -1) {
                            curDeadTimers[target] =
                                System.currentTimeMillis() + INITIAL_DISPLAYED_TIME + ADDITIONAL_DISPLAYED_TIME_PER_CHAR * textLength
                        } else {
                            permanentsShown[permanentIndex] = target
                        }
                    }
                    delayUntil { action.isComplete }
                }.asAction()
            )
        }
    }

    companion object {
        fun getWarning(screen: OnjScreen): CustomWarningParent { //name from template
            return screen.namedActorOrError("WARNING_PARENT") as CustomWarningParent
        }

        private const val ADDITIONAL_DISPLAYED_TIME_PER_CHAR = 60 //TODO in settings change this option

        private const val INITIAL_DISPLAYED_TIME = 500

        private const val DIST_BETWEEN_BLOCKS = 10

        private const val TIME_BETWEEN_LIMIT = 500
    }
}package com.fourinachamber.fortyfive.game.enemy

import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com


.ProceduresPopulating() {
		return scope, nil
	}
	referencesProcedures := hasProcedureCall(n)
	if !referencesProcedures {
		return scope, nil
	}
	scope = scope.WithProcedureCache(plan.NewProcedureCache())
	scope.Procedures.IsPopulating = true
	defer func() {
		scope.Procedures.IsPopulating = false
	}()

	allDatabases := a.Catalog.AllDatabases(ctx)
	for _, database := range allDatabases {
		if pdb, ok := database.(sql.StoredProcedureDatabase); ok {
			procedures, err := pdb.GetStoredProcedures(ctx)
			if err != nil {
				return nil, err
			}

			for _, procedure := range procedures {
				var procToRegister *plan.Procedure
				var parsedProcedure sql.Node
				b := planbuilder.New(ctx, a.Catalog, nil, nil)
				b.DisableAuth()
				b.SetParserOptions(sql.NewSqlModeFromString(procedure.SqlMode).ParserOptions())
				parsedProcedure, _, _, _, err = b.Parse(procedure.CreateStatement, nil, false)
				if err != nil {
					procToRegister = &plan.Procedure{
						CreateProcedureString: procedure.CreateStatement,
					}
					procToRegister.ValidationError = err
				} else if cp, ok := parsedProcedure.(*plan.CreateProcedure); !ok {
					return nil, sql.ErrProcedureCreateStatementInvalid.New(procedure.CreateStatement)
				} else {
					procToRegister = cp.Procedure
				}

				procToRegister.CreatedAt = procedure.CreatedAt
				procToRegister.ModifiedAt = procedure.ModifiedAt

				err = scope.Procedures.Register(database.Name(), procToRegister)
				if err != nil {
					return nil, err
				}
			}
		}
	}
	return scope, nil
}

// analyzeCreateProcedure checks the plan.CreateProcedure and returns a valid plan.Procedure or an error
func analyzeCreateProcedure(ctx *sql.Context, a *Analyzer, cp *plan.CreateProcedure, scope *plan.Scope, sel RuleSelector, qFlags *sql.QueryFlags) (*plan.Procedure, error) {
	err := validateStoredProcedure(ctx, cp.Procedure)
	if err != nil {
		return nil, err
	}
	var analyzedNode sql.Node
	analyzedNode, _, err = analyzeProcedureBodies(ctx, a, cp.Procedure, false, scope, sel, qFlags)
	if err != nil {
		return nil, err
	}
	analyzedProc, ok := analyzedNode.(*plan.Procedure)
	if !ok {
		return nil, fmt.Errorf("analyzed node %T and expected *plan.Procedure", analyzedNode)
	}
	return analyzedProc, nil
}

func hasProcedureCall(n sql.Node) bool {
	referencesProcedures := false
	transform.Inspect(n, func(n sql.Node) bool {
		if _, ok := n.(*plan.Call); ok {
			referencesProcedures = true
			return false
		} else if rt, ok := n.(*plan.ResolvedTable); ok {
			_, rOk := rt.Table.(RoutineTable)
			if rOk {
				referencesProcedures = true
				return false
			}
		}
		return true
	})
	return referencesProcedures
}

// analyzeProcedureBodies analyzes each statement in a procedure's body individually, as the analyzer is designed to
// inspect single statements rather than a collection of statements, which is usually the body of a stored procedure.
func analyzeProcedureBodies(ctx *sql.Context, a *Analyzer, node sql.Node, skipCall bool, scope *plan.Scope, sel RuleSelector, qFlags *sql.QueryFlags) (sql.Node, transform.TreeIdentity, error) {
	children := node.Children()
	newChildren := make([]sql.Node, len(children))
	var err error
	procSel := NewProcRuleSelector(sel)
	for i, child :=


18.0);
    public static final double singleSubstationLowZ = Units.inchesToMeters(27.125);
    public static final double singleSubstationCenterZ =
        singleSubstationLowZ + (singleSubstationHeight / 2.0);
    public static final double singleSubstationHighZ =
        singleSubstationLowZ + singleSubstationHeight;
  }

  // Locations of staged game pieces
  public static final class StagingLocations {
    public static final double centerOffsetX = Units.inchesToMeters(47.36);
    public static final double positionX = fieldLength / 2.0 - Units.inchesToMeters(47.36);
    public static final double firstY = Units.inchesToMeters(36.19);
    public static final double separationY = Units.inchesToMeters(48.0);
    public static final Translation2d[] translations = new Translation2d[4];

    static {
      for (int i = 0; i < translations.length; i++) {
        translations[i] = new Translation2d(positionX, firstY + (i * separationY));
      }
    }
  }

  // AprilTag locations (do not flip for red alliance)
  public static final Map<Integer, Pose3d> aprilTags =
      Map.of(
          1,
          new Pose3d(
              Units.inchesToMeters(610.77),
              Units.inchesToMeters(42.19),
              Units.inchesToMeters(18.22),
              new Rotation3d(0.0, 0.0, Math.PI)),
          2,
          new Pose3d(
              Units.inchesToMeters(610.77),
              Units.inchesToMeters(108.19),
              Units.inchesToMeters(18.22),
              new Rotation3d(0.0, 0.0, Math.PI)),
          3,
          new Pose3d(
              Units.inchesToMeters(610.77),
              Units.inchesToMeters(174.19), // FIRST's diagram has a typo (it says 147.19)
              Units.inchesToMeters(18.22),
              new Rotation3d(0.0, 0.0, Math.PI)),
          4,
          new Pose3d(
              Units.inchesToMeters(636.96),
              Units.inchesToMeters(265.74),
              Units.inchesToMeters(27.38),
              new Rotation3d(0.0, 0.0, Math.PI)),
          5,
          new Pose3d(
              Units.inchesToMeters(14.25),
              Units.inchesToMeters(265.74),
              Units.inchesToMeters(27.38),
              new Rotation3d()),
          6,
          new Pose3d(
              Units.inchesToMeters(40.45),
              Units.inchesToMeters(174.19), // FIRST's diagram has a typo (it says 147.19)
              Units.inchesToMeters(18.22),
              new Rotation3d()),
          7,
          new Pose3d(
              Units.inchesToMeters(40.45),
              Units.inchesToMeters(108.19),
              Units.inchesToMeters(18.22),
              new Rotation3d()),
          8,
          new Pose3d(
              Units.inchesToMeters(40.45),
              Units.inchesToMeters(42.19),
              Units.inchesToMeters(18.22),
              new Rotation3d()));

  // TODO we need to move the positions to be where the robot -should- be and not where the april
  // tags actually are

  public static P


urce.name,
        "kind": match &resource.kind {
            GenericResourceDescriptorKind::Indices(_) => "indices",
            GenericResourceDescriptorKind::Sum(_) => "sum",
        },
        "params": match &resource.kind {
            GenericResourceDescriptorKind::Indices(params) => json!({
                "start": params.start,
                "end": params.end
            }),
            GenericResourceDescriptorKind::Sum(params) => json!({
                "size": params.size
            }),
        }
    })
}

fn format_duration(duration: Duration) -> serde_json::Value {
    let value = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;
    json!(value)
}
fn format_datetime<T: Into<DateTime<Utc>>>(time: T) -> serde_json::Value {
    json!(time.into())
}
<filename>src/day01/solution.rs
pub fn part1(input: String) -> i64 {
    let depths: Vec<i32> = input.lines().map(|line| line.trim().parse().unwrap()).collect();
    depths
        .windows(2)
        .map(|pair| pair[0] < pair[1])
        .filter(|increase| *increase)
        .count()  as i64
}

pub fn part2(input: String) -> i64 {
    let depths: Vec<i32> = input.lines().map(|line| line.trim().parse().unwrap()).collect();
    depths
        .windows(3)
        .map(|window| window[0] + window[1] + window[2])
        .collect::<Vec<i32>>()
        .windows(2)
        .map(|pair| pair[0] < pair[1])
        .filter(|increase| *increase)
        .count() as i64
}
<filename>src/libos/crates/async-rt/src/task/locals.rs
// This file is adapted from async_std

use core::cell::UnsafeCell;

use crate::prelude::*;

#[derive(Debug)]
pub struct LocalKey<T: Send + 'static> {
    init: fn() -> T,
    key: AtomicU32,
}

impl<T: Send + 'static> LocalKey<T> {
    pub const fn new(init: fn() -> T) -> Self {
        let key = AtomicU32::new(0);
        Self { init, key }
    }
}

impl<T: Send + 'static> LocalKey<T> {
    /// Attempts to get a reference to the task-local value with this key.
    ///
    /// This method will panic if not called within the context of a task.
    pub fn with<F, R>(&'static self, f: F) -> R
    where
        F: FnOnce(&T) -> R,
    {
        self.try_with(f).unwrap()
    }

    /// Attempts to get a reference to the task-local value with this key.
    ///
    /// This method will not invoke the closure and return an `None` if not
    /// called within the context of a task.
    pub fn try_with<F, R>(&'static self, f: F) -> Option<R>
    where
        F: FnOnce(&T) -> R,
    {
        let current = match crate::task::current::try_get() {
            Some(current) => current,
            None => return None,
        };

        // Prepare the numeric key, initialization function, and the map of task-locals.
        let key = self.key();
        let init = || Box::new((self.init)()) as Box<dyn Send>;

        // Get the value in the map of task-locals, or initialize and insert one.
        let value: *const dyn Send = current.locals().get_or_insert(key, init);

        // Call the closure with the value passed as an argument.
        let retval = unsafe { f(&*(value as *const T)) };
        Some(retval)
    }

    /// Returns the numeric key associated with this task-local.
    #[inline]
    pub fn key(&self) -> u32 {
        #[cold]
        fn init(key: &AtomicU32) -> u32 {


 that point. Click the **Choose** button.

This will bring up the **Choose a pattern** modal. In this modal, your pattern will appear and can be selected:

[![Modal overlaying the post editor that shows three options of different patterns for showing a list or grid of posts.](https://i0.wp.com/developer.wordpress.org/files/2024/04/query-loop-modal.webp?resize=2048%2C1064&ssl=1)](https://i0.wp.com/developer.wordpress.org/files/2024/04/query-loop-modal.webp?ssl=1)Once selected, your pattern will be inserted into the canvas of the page or template that you are editing:

[![WordPress post editor with a two-column grid of posts shown in the content area.](https://i0.wp.com/developer.wordpress.org/files/2024/04/query-loop-inserted.webp?resize=2048%2C1064&ssl=1)](https://i0.wp.com/developer.wordpress.org/files/2024/04/query-loop-inserted.webp?ssl=1)The second method of using Query Loop patterns is much the same. You can replace an existing pattern (even the one you just inserted) by clicking the **Replace** button in the toolbar. It will bring up the same **Choose a pattern** modal, and the process of choosing a pattern is the same.

## Template Part patterns

Because [template parts](#themes/templates/template-parts) are technically blocks themselves, you can also use them as a pattern’s block types. There is one limitation: only parts that use the Header and Footer [template part areas](#themes/templates/template-parts#template-part-areas) are supported. But these are the most common types anyway.

When targeting a specific template part, its block type name will have a third component: the template part area. So if you want to target the Header part, you will pass a block type of `core/template-part/header`. And for the Footer part, use `core/template-part/footer`.

Let’s create a basic Header template part with a centered logo, title, and nav menu. You will use this to replace the existing header on your site.

Create a new file named `header-centered.php` in your theme’s `/patterns` folder. Then copy and paste this code into it:

```php
<?php
/**
 * Title: Header: Centered
 * Slug: themeslug/header-centered
 * Categories: header
 * Block Types: core/template-part/header
 * Viewport Width: 1376
 */
?>
<!-- wp:group {"align":"wide","layout":{"type":"flex","orientation":"vertical","justifyContent":"center"}} -->
<div class="wp-block-group alignwide">
	<!-- wp:site-logo {"width":60} /-->
	<!-- wp:site-title {"level":0} /-->
	<!-- wp:navigation {"layout":{"type":"flex","justifyContent":"right","orientation":"horizontal"},"style":{"spacing":{"margin":{"top":"0"},"blockGap":"var:preset|spacing|20"},"layout":{"selfStretch":"fit","flexSize":null}}} /-->
</div>
<!-- /wp:group -->
```

Once you save this file, go to **Appearance > Editor** in your WordPress admin and select the on the Header block.

Now click the **Options** button (**⋮** icon) in the toolbar. You should see a **Replace** option in the dropdown:

[![WordPress Site Editor with the Header Template Part selected in the content area. The Options dropdown shows the "Replace" item highlighted.](https://i0.wp.com/developer.wordpress.org/files/2024/04/header-part-replace-dropdown.webp?resize=2048%2C1064&ssl=1)](https://i0.wp.com/developer.wordpress.org/files/2024/04/header-part-replace-dropdown.webp?ssl=1)Once you click the **Replace** dropdown menu item, a new modal titled **Choose a header** will appear, and you should see your **Header: Centered** pattern in the available patterns grid:

[![A modal overlaying the Site Editor screen that reads "Choose a header." Below, it shows a grid of various site header designs to choose from.](https://i0.wp.com/developer.wordpress.org/files/2024/04/hea


ey := bsonutil.GetDottedKeyName(TaskRuntimeInfoKey, TaskRuntimeInfoRunningTaskIDKey)
	runningTaskExecutionKey := bsonutil.GetDottedKeyName(TaskRuntimeInfoKey, TaskRuntimeInfoRunningTaskExecutionKey)
	query := bson.M{
		IDKey:                   p.ID,
		StatusKey:               StatusRunning,
		runningTaskIDKey:        nil,
		runningTaskExecutionKey: nil,
	}
	update := bson.M{
		"$set": bson.M{
			runningTaskIDKey:        taskID,
			runningTaskExecutionKey: taskExecution,
			// Decommissioning ensures that the pod cannot run another task.
			// TODO (PM-2618): adjust this to handle cases such as
			// single-container task groups, where the pod may be reused.
			StatusKey: StatusDecommissioned,
		},
	}

	res, err := env.DB().Collection(Collection).UpdateOne(ctx, query, update)
	if err != nil {
		return err
	}
	if res.ModifiedCount == 0 {
		return errors.New("pod was not updated")
	}

	p.TaskRuntimeInfo.RunningTaskID = taskID
	p.TaskRuntimeInfo.RunningTaskExecution = taskExecution
	p.Status = StatusDecommissioned

	event.LogPodStatusChanged(ctx, p.ID, string(StatusRunning), string(StatusDecommissioned), "pod has been assigned a task and will not be reused")

	return nil
}

// ClearRunningTask clears the current task dispatched to the pod, if one is set.
func (p *Pod) ClearRunningTask(ctx context.Context) error {
	if p.TaskRuntimeInfo.RunningTaskID == "" {
		return nil
	}

	runningTaskIDKey := bsonutil.GetDottedKeyName(TaskRuntimeInfoKey, TaskRuntimeInfoRunningTaskIDKey)
	runningTaskExecutionKey := bsonutil.GetDottedKeyName(TaskRuntimeInfoKey, TaskRuntimeInfoRunningTaskExecutionKey)
	query := bson.M{
		IDKey:            p.ID,
		runningTaskIDKey: p.TaskRuntimeInfo.RunningTaskID,
	}
	if p.TaskRuntimeInfo.RunningTaskExecution == 0 {
		query["$or"] = []bson.M{
			{runningTaskExecutionKey: p.TaskRuntimeInfo.RunningTaskExecution},
			{runningTaskExecutionKey: bson.M{"$exists": false}},
		}
	} else {
		query[runningTaskExecutionKey] = p.TaskRuntimeInfo.RunningTaskExecution
	}

	if err := UpdateOne(ctx, query, bson.M{
		"$unset": bson.M{
			runningTaskIDKey:        1,
			runningTaskExecutionKey: 1,
		},
	}); err != nil {
		return errors.Wrap(err, "clearing running task")
	}

	event.LogPodRunningTaskCleared(ctx, p.ID, p.TaskRuntimeInfo.RunningTaskID, p.TaskRuntimeInfo.RunningTaskExecution)

	p.TaskRuntimeInfo.RunningTaskID = ""
	p.TaskRuntimeInfo.RunningTaskExecution = 0

	return nil
}

// UpdateAgentStartTime updates the time when the pod's agent started to now.
func (p *Pod) UpdateAgentStartTime(ctx context.Context) error {
	ts := utility.BSONTime(time.Now())
	if err := UpdateOne(ctx, ByID(p.ID), bson.M{
		"$set": bson.M{
			bsonutil.GetDottedKeyName(TimeInfoKey, TimeInfoAgentStartedKey): ts,
		},
	}); err != nil {
		return err
	}

	p.TimeInfo.AgentStarted = ts

	return nil
}

// UpdateLastCommunicated updates the last time that the pod and app server
// successfully communicated to now, indicating that the pod is currently alive.
func (p *Pod) UpdateLastCommunicated(ctx context.Context) error {
	ts := utility.BSONTime(time.Now())
	if err := UpdateOne(ctx, ByID(p.ID), bson.M{
		"$set": bson.M{
			bsonutil.GetDottedKeyName(TimeInfoKey, TimeInfoLastCommunicatedKey


)) {
            insertLocalTemp(actual);
          }
        }
      }
    }
  }
}

// In every move:
//   if the lhs type has the WIDE or REF flag
//   and its value type is a wide class
//   and the rhs type is the same as the contents of the wide pointer:
//     Create a temp copy of the rhs, and
//     replace the rhs of the move with the temp.
static void moveAddressSourcesToTemp()
{
  forv_Vec(CallExpr, call, gCallExprs) {
    if (call->isPrimitive(PRIM_MOVE) || call->isPrimitive(PRIM_ASSIGN)) {
      if (call->get(1)->isRefOrWideRef() &&
          valIsWideClass(call->get(1)) &&
          call->get(2)->typeInfo() == getNarrowType(call->get(1)->getValType()).type()) {
        //
        // widen rhs class
        //
        SET_LINENO(call);
        VarSymbol* tmp = newTemp(call->get(1)->getValType());
        call->insertBefore(new DefExpr(tmp));
        call->insertBefore(new CallExpr(PRIM_MOVE, tmp, call->get(2)->remove()));
        call->insertAtTail(tmp);
        DEBUG_PRINTF("Made move temp: %d\n", tmp->id);
      }
    }
  }
}

//
// Nearly the same as addUseOrDef, but 'exp' may not be a SymExpr representing
// 'field'. It may instead be a literal or a runtime value as we sometimes see
// in star tuples.
//
static void addTupleDefOrUse(Map<Symbol*, Vec<SymExpr*>*>& ses, Symbol* field, Expr* exp) {
  SymExpr* se = toSymExpr(exp);
  INT_ASSERT(se);
  DEBUG_PRINTF("SymExpr %d in call %d is a use of field %s (%d)\n", se->id, se->parentExpr->id, field->cname, field->id);
  Vec<SymExpr*>* sev = ses.get(field);
  if (sev) {
    sev->add(se);
  } else {
    sev = new Vec<SymExpr*>();
    sev->add(se);
    ses.put(field, sev);
  }
}

//
// buildDefUseMaps does not handle tuple fields correctly, star tuples
// especially. This function tries to do a better job.
//
static void buildTupleDefsUses() {
  // TODO: The incorrect defs/uses from buildDefUseMaps may still
  // exist, can we do anything about that?
  forv_Vec(CallExpr, call, gCallExprs) {
    if (call->isPrimitive(PRIM_GET_SVEC_MEMBER) ||
        call->isPrimitive(PRIM_GET_SVEC_MEMBER_VALUE) ||
        call->isPrimitive(PRIM_SET_SVEC_MEMBER)) {
      Symbol* field = getSvecSymbol(call);
      if (field) {
        if (call->isPrimitive(PRIM_SET_SVEC_MEMBER)) {
          addTupleDefOrUse(defMap, field, call->get(2));
        } else {
          addTupleDefOrUse(useMap, field, call->get(2));
        }
      } else {
        // indexed by a runtime value, need to add all fields.
        AggregateType* ag = toAggregateType(call->get(1)->getValType());
        for_fields(fi, ag) {
          if (call->isPrimitive(PRIM_SET_SVEC_MEMBER)) {
            addTupleDefOrUse(defMap, fi, call->get(2));
          } else {
            addTupleDefOrUse(useMap, fi, call->get(2));
          }
        }
      }
    }
  }
}

void handleIsWidePointer() {
  forv_Vec(CallExpr, call, gCallExprs) {
    if (call->isPrimitive(PRIM_IS_WIDE_PTR)) {
      SET_LINENO(call->getStmtExpr());
      VarSymbol* isWide;
      if (hasSomeWideness(ca


M_L2x8_SUB1

CGEMM_L2x8_SUB0:

	andi.		L,	K,	7

	KERNEL2x8_SUBI1

	addic.		L,	L,	-1
	ble		CGEMM_L2x8_SAVE
	b		CGEMM_L2x8_SUB2

CGEMM_L2x8_SUB1:

	andi.		L,	K,	7
	ble		CGEMM_L2x8_SAVE

CGEMM_L2x8_SUB2:

	KERNEL2x8_SUB1

	addic.		L,	L,	-1
	bgt		CGEMM_L2x8_SUB2

CGEMM_L2x8_SAVE:

	SAVE2x8

	addic.		I,	I,	-1
	bgt		CGEMM_L2x8_BEGIN

CGEMM_L2x8_END:

CGEMM_L2x4_BEGIN:

	andi.		T2,	M,	7
	ble		CGEMM_L2x1_END

	andi.		T1,	M,	4
	ble		CGEMM_L2x4_END
	mr		BO,	BBUFFER
	srawi.		L,	K,	3
	ble		CGEMM_L2x4_SUB0
	cmpwi		cr0,	L,	1
	ble		CGEMM_L2x4_SUB4

CGEMM_L2x4_LOOP_START:

	LOAD2x4_1
	KERNEL2x4_I1
	KERNEL2x4_2
	KERNEL2x4_1
	KERNEL2x4_2

	KERNEL2x4_1
	KERNEL2x4_2
	KERNEL2x4_1
	KERNEL2x4_2

	addic.		L,	L,	-2
	ble		CGEMM_L2x4_LOOP_END

	.align 5

CGEMM_L2x4_LOOP:

	KERNEL2x4_1
	KERNEL2x4_2
	KERNEL2x4_1
	KERNEL2x4_2

	KERNEL2x4_1
	KERNEL2x4_2
	KERNEL2x4_1
	KERNEL2x4_2

	addic.		L,	L,	-1
	bgt		CGEMM_L2x4_LOOP

CGEMM_L2x4_LOOP_END:

	KERNEL2x4_1
	KERNEL2x4_2
	KERNEL2x4_1
	KERNEL2x4_2

	KERNEL2x4_1
	KERNEL2x4_2
	KERNEL2x4_1
	KERNEL2x4_E2

	b		CGEMM_L2x4_SUB1

CGEMM_L2x4_SUB4:

	KERNEL2x4_SUBI1
	KERNEL2x4_SUB1
	KERNEL2x4_SUB1
	KERNEL2x4_SUB1

	KERNEL2x4_SUB1
	KERNEL2x4_SUB1
	KERNEL2x4_SUB1
	KERNEL2x4_SUB1

	b		CGEMM_L2x4_SUB1

CGEMM_L2x4_SUB0:

	andi.		L,	K,	7

	KERNEL2x4_SUBI1

	addic.		L,	L,	-1
	ble		CGEMM_L2x4_SAVE
	b		CGEMM_L2x4_SUB2

CGEMM_L2x4_SUB1:

	andi.		L,	K,	7
	ble		CGEMM_L2x4_SAVE

CGEMM_L2x4_SUB2:

	KERNEL2x4_SUB1

	addic.		L,	L,	-1
	bgt		CG


. Your e-mail address will not be used for any other purpose and is disposed of after the issue you report is resolved. While working to resolve the issue that you report, you may be contacted via e-mail to get further details or clarification on the feedback you sent. After the issue you report has been addressed, you may receive an e-mail to let you know that your feedback has been addressed.");
        HT_mailLink.innerHTML = HT_mailLinkText;
        </script>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="shortcut icon" href="../icons/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="../styles/branding.css" />
    <link rel="stylesheet" type="text/css" href="../styles/branding-en-US.css" />

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>ModelRoot.InheritanceStrategy Property </title>
    <meta name="Language" content="en-us" />
    <meta name="System.Keywords" content="InheritanceStrategy property" />
    <meta name="System.Keywords" content="ModelRoot.InheritanceStrategy property" />
    <meta name="Microsoft.Help.F1" content="Sawczyn.EFDesigner.EFModel.ModelRoot.InheritanceStrategy" />
    <meta name="Microsoft.Help.F1" content="Sawczyn.EFDesigner.EFModel.ModelRoot.get_InheritanceStrategy" />
    <meta name="Microsoft.Help.F1" content="Sawczyn.EFDesigner.EFModel.ModelRoot.set_InheritanceStrategy" />
    <meta name="Microsoft.Help.Id" content="P:Sawczyn.EFDesigner.EFModel.ModelRoot.InheritanceStrategy" />
    <meta name="Description" content="Gets or sets the value of InheritanceStrategy domain property. How tables will be created/used to handle inheritance" />
    <meta name="Microsoft.Help.ContentType" content="Reference" />
    <meta name="BrandingAware" content="true" />

    <meta name="container" content="Sawczyn.EFDesigner.EFModel" />
    <meta name="file" content="P_Sawczyn_EFDesigner_EFModel_ModelRoot_InheritanceStrategy" />
    <meta name="guid" content="P_Sawczyn_EFDesigner_EFModel_ModelRoot_InheritanceStrategy" />

    <link rel="stylesheet" type="text/css" href="../styles/branding-Website.css" />

    <input type="hidden" id="userDataCache" class="userDataStyle" />

Entity Framework Designer T4 API<form id="SearchForm" method="get" action="#" onsubmit="javascript:TransferToSearchPage(); return false;"><input id="SearchTextBox" type="text" maxlength="200" /><button id="SearchButton" type="submit"></button></form>

<a data-tochassubtree="true" href="../html/ed2e64f5-b23e-43ae


ring) {
    super.warn(`[WARN] ${message}`, context);
  }
  verbose(context: string, message: string) {
    if (process.env.NODE_ENV !== 'production') {
      super.verbose(`[VERBOSE] ${message}`, context);
    }
  }
}
import takor from '../..'
import { INVALID_VALUE_TYPES } from '../testResources'

describe('not.arrayOf', () => {
    describe('basic', () => {
        it('succeeds', () => {
            const enforcer = takor.not.arrayOf(Array, String, Set)
            const actual = enforcer([10])
            expect(actual).toEqual(true)
        })
        it('fails', () => {
            const enforcer = takor.not.arrayOf(Array, String, Set)
            const actual = enforcer([[]])
            expect(actual).toEqual(false)
        })
    })
    describe('complex', () => {
        it('succeeds', () => {
            const enforcer = takor.not.arrayOf(Array, takor.shape({ key: Number }), Set)
            const actual = enforcer(['', { key: '' }])
            expect(actual).toEqual(true)
        })
        it('fails', () => {
            const enforcer = takor.not.arrayOf(Array, takor.shape({ key: takor.pojo }), Set)
            const actual = enforcer(['', { key: {} }])
            expect(actual).toEqual(false)
        })
    })
    describe('non-array values', () => {
        INVALID_VALUE_TYPES.arrayOf.forEach(([type, value]) => {
            it(`is true for type ${type} of value ${value}`, () => {
                const enforcer = takor.not.arrayOf(takor.any)
                expect(enforcer(value)).toEqual(true)
            })
        })
    })
})
import { BaseObject } from '../engine/base-object';
import { Spritesheet } from '../engine/spritesheet';
import {AudioEffect} from './audio-effect';

export enum PlayerState {
    Idle,
    IdleMirrored,
    Jump,
    JumpMirrored,
    Fall,
    FallMirrored,
    Run,
    RunMirrored,
    Attack,
    AttackMirrored,
};

export enum PlayerAudio {
    Jump,
    Attack,
}

export class BasePlayer extends BaseObject {
    protected static spritesheets = new Map([
        [PlayerState.Idle, new Spritesheet(require('../assets/player/HeroKnight_Idle.png').default, 8)],
        [PlayerState.IdleMirrored, new Spritesheet(require('../assets/player/HeroKnight_Idle_Mirrored.png').default, 8)],
        [PlayerState.Jump, new Spritesheet(require('../assets/player/HeroKnight_Jump.png').default, 3)],
        [PlayerState.JumpMirrored, new Spritesheet(require('../assets/player/HeroKnight_Jump_Mirrored.png').default, 3)],
        [PlayerState.Run, new Spritesheet(require('../assets/player/HeroKnight_Run.png').default, 10)],
        [PlayerState.RunMirrored, new Spritesheet(require('../assets/player/HeroKnight_Run_Mirrored.png').default, 10)],
        [PlayerState.Fall, new Spritesheet(require('../assets/player/HeroKnight_Fall.png').default, 4)],
        [PlayerState.FallMirrored, new Spritesheet(require('../assets/player/HeroKnight_Fall_Mirrored.png').default, 4)],
        [PlayerState.Attack, new Spritesheet(require('../assets/player/HeroKnight_Attack.png').default, 8)],
        [PlayerState.AttackMirrored, new Spritesheet(require('../assets/player/HeroKnight_Attack_Mirrored.png').default


pe == self.dtype

        frame = av.VideoFrame.from_ndarray(
            img, format=self.input_pix_fmt)
        for i in range(n_repeats):
            for packet in self.stream.encode(frame):
                self.container.mux(packet)

    def stop(self):
        if not self.is_ready():
            return

        # Flush stream
        for packet in self.stream.encode():
            self.container.mux(packet)

        # Close the file
        self.container.close()

        # reset runtime parameters
        self._reset_state()


Punctuation

Converts ellipses and m-dashes to AsciiDoc syntax.

Ensures that all m-dashes are represented by exactly 2 dashes.

AsciiDoctor can’t handle the normal m-dash notation at the end of a quotation, so an HTML entity is used instead.

Ensures exactly one space before and after ellipses and m-dashes that are mid-sentence (between words).

Undoes Word-style smart quotes, making sure to distinguish a possessive apostrophe from a closing quote.

Smartens dumb quotes (i.e. using AsciiDoc typographic quote notation).

Lists

Ensures bullet point syntax (exactly one space following).

Paragraphs

Breaks up paragraphs so that each sentence is on its own line (for version control support).

Converts scene breaks to the AsciiDoc horizontal-rule syntax ('''). A scene break line is defined as having one of these symbols: - (minus), # (hash), * (asterisk),  \~ (tilde), . (period), + (plus), _ (underscore), or ' (apostrophe). That one symbol can be repeated and any spaces in the line are ignored. Thus, "", "   \+   ", " * * * * * ", and "+\+\\\+" are all considered scene breaks, but " - #" is not (since a second symbol is involved).

Anchors

Replaces Word-style figure captions with AsciiDoc block ID and block title syntax.

Replaces Word-style references to figures with AsciiDoc xref syntax.

Deletes any block IDs automatically inserted (by PanDoc).

Common Manuscript Errors

Fixes misplaced commas near parentheticals.

Fixes transposed end-of-quotation punctuation — i.e. moves the punctuation to inside the quotes.

Misc.

Converts HTML Entities to AsciiDoc attribute notation.

See: Converting a Manuscript for a step-by-step guide on how to turn a Word document into a full-fledged AsciiDoc document
(with this Fix Up Converted Prose command being just one of the steps).

Renumber Chapters

<


      SELECT * FROM v3 ORDER BY c1;
        ]]
    end, {
        -- <triggerA-1.4>
        "1", "10", "2", "3", "4", "5", "6", "7", "8", "9", "eight", "five", "four", "nine", "one", "seven", "six", "ten", "three", "two"
        -- </triggerA-1.4>
    })

test:do_test(
    "triggerA-1.5",
    function()
        return test:execsql [[
            CREATE VIEW v4 AS
               SELECT CAST(x AS TEXT) AS c1 FROM t1
               UNION SELECT y FROM t1 WHERE x BETWEEN 3 and 5;
            SELECT * FROM v4 ORDER BY 1;
        ]]
    end, {
        -- <triggerA-1.5>
        "1", "10", "2", "3", "4", "5", "6", "7", "8", "9", "five", "four", "three"
        -- </triggerA-1.5>
    })

test:do_test(
    "triggerA-1.6",
    function()
        return test:execsql [[
            CREATE VIEW v5 AS SELECT x, b FROM t1, t2 WHERE y=c;
            SELECT * FROM v5 ORDER BY x DESC;
        ]]
    end, {
        -- <triggerA-1.6>
        10, 1003, 9, 904, 8, 805, 7, 705, 6, 603, 5, 504, 4, 404, 3, 305, 2, 203, 1, 103
        -- </triggerA-1.6>
    })

-- Create INSTEAD OF triggers on the views.  Run UPDATE and DELETE statements
-- using those triggers.  Verify correct operation.
--
test:do_test(
    "triggerA-2.1",
    function()
        return test:execsql [[
            CREATE TABLE result2(id INTEGER PRIMARY KEY, a TEXT,b INT);
            CREATE TRIGGER r1d INSTEAD OF DELETE ON v1 FOR EACH ROW BEGIN
              INSERT INTO result2(id, a,b) VALUES((SELECT COALESCE(MAX(id),0) + 1 FROM result2),
                                                  old.y, old.x);
            END;
            DELETE FROM v1 WHERE x=5;
            SELECT a, b FROM result2;
        ]]
    end, {
        -- <triggerA-2.1>
        "five", 5
        -- </triggerA-2.1>
    })

test:do_test(
    "triggerA-2.2",
    function()
        return test:execsql [[
            CREATE TABLE result4(id INTEGER PRIMARY KEY, a TEXT,b INT,c TEXT,d INT);
            CREATE TRIGGER r1u INSTEAD OF UPDATE ON v1 FOR EACH ROW BEGIN
              INSERT INTO result4(id, a,b,c,d) VALUES((SELECT COALESCE(MAX(id),0) + 1 FROM result4),
                                                      old.y, old.x, new.y, new.x);
            END;
            UPDATE v1 SET y=y||'-extra' WHERE x BETWEEN 3 AND 5;
            SELECT a,b,c,d FROM result4 ORDER BY a;
        ]]
    end, {
        -- <triggerA-2.2>
        "five", 5, "five-extra", 5, "four", 4, "four-extra", 4, "three", 3, "three-extra", 3
        -- </triggerA-2.2>
    })

test:do_test(
    "triggerA-2.3",
    function()
        return test:execsql [[
            DELETE FROM result2;
            CREATE TRIGGER r2d INSTEAD OF DELETE ON v2 FOR EACH ROW BEGIN
              INSERT INTO result2(id, a,b) VALUES((SELECT COALESCE(MAX(id),0) + 1 FROM result2),
                                                  old.y, old.x);
            END;
            DELETE FROM v2 WHERE x=5;
            SELECT a, b FROM result2;
        ]]
    end, {
        -- <triggerA-2.3>
        "five", 5
        -- </triggerA-2.3>


 be
            // lost when the joiner reactor's event queue is purged as we transition to the
            // participating reactor.  This workaround should no longer be required once the reactor
            // transitions are handled properly.
            let deploy_accepted =
                match time::timeout(GET_DEPLOY_TIMEOUT, deploy_getter.get(deploy_hash)).await {
                    Ok(maybe_deploy) => maybe_deploy?,
                    Err(_) => {
                        info!("timed out getting deploy for event stream");
                        deploy_getter.get(deploy_hash).await?
                    }
                };

            Some(Ok(WarpServerSentEvent::default()
                .json_data(&DeployAccepted { deploy_accepted })
                .unwrap_or_else(|error| {
                    warn!(%error, "failed to jsonify sse event");
                    WarpServerSentEvent::default()
                })
                .id(event.id.unwrap().to_string())))
        }
    }
}

/// Converts the final URL path element to a slice of `EventFilter`s.
pub(super) fn get_filter(path_param: &str) -> Option<&'static [EventFilter]> {
    match path_param {
        SSE_API_MAIN_PATH => Some(&MAIN_FILTER[..]),
        SSE_API_DEPLOYS_PATH => Some(&DEPLOYS_FILTER[..]),
        SSE_API_SIGNATURES_PATH => Some(&SIGNATURES_FILTER[..]),
        _ => None,
    }
}

/// Extracts the starting event ID from the provided query, or `None` if `query` is empty.
///
/// If `query` is not empty, returns a 422 response if `query` doesn't have exactly one entry,
/// "starts_from" mapped to a value representing an event ID.
fn parse_query(query: HashMap<String, String>) -> Result<Option<Id>, Response> {
    if query.is_empty() {
        return Ok(None);
    }

    if query.len() > 1 {
        return Err(create_422());
    }

    match query
        .get(QUERY_FIELD)
        .and_then(|id_str| id_str.parse::<Id>().ok())
    {
        Some(id) => Ok(Some(id)),
        None => Err(create_422()),
    }
}

/// Creates a 404 response with a useful error message in the body.
fn create_404() -> Response {
    let mut response = Response::new(Body::from(format!(
        "invalid path: expected '/{root}/{main}', '/{root}/{deploys}' or '/{root}/{sigs}'\n",
        root = SSE_API_ROOT_PATH,
        main = SSE_API_MAIN_PATH,
        deploys = SSE_API_DEPLOYS_PATH,
        sigs = SSE_API_SIGNATURES_PATH
    )));
    *response.status_mut() = StatusCode::NOT_FOUND;
    response
}

/// Creates a 422 response with a useful error message in the body for use in case of a bad query
/// string.
fn create_422() -> Response {
    let mut response = Response::new(Body::from(format!(
        "invalid query: expected single field '{}=<EVENT ID>'\n",
        QUERY_FIELD
    )));
    *response.status_mut() = StatusCode::UNPROCESSABLE_ENTITY;
    response
}

/// Creates a 503 response (Service Unavailable) to be returned if the server has too many
/// subscribers.
fn create_503() -> Response {
    let mut response = Response::new(Body::from("server has reached limit of subscribers"));
    *response.status_mut() = StatusCode::SERVICE_UNAVAILABLE;
    response
}

pub(super) struct ChannelsAndFilter {
    pub(super) event_broadcaster: broadcast::Sender<BroadcastChannelMessage>,
    pub(super) new_subscriber_info_receiver: mpsc::UnboundedReceiver<NewSubscriberInfo>,
    pub(super) sse_filter: BoxedFilter<(Response,)>,
}

impl ChannelsAndFilter {
    /// Creates the message-passing channels required to run the event-stream server and the warp
    /// filter for the event-stream server.
    pub(super) fn new(
        broadcast_channel_size: usize,
        max_concurrent_subscribers: u32,
        deploy_getter: DeployGetter,
    ) -> Self {
        // Create a channel to broadcast new ev