(map[string]struct{})
		for _, test := range tests {
			if _, ok := seenBinary[test.args[0]]; !ok {
				binaries = append(binaries, test.args[0])
				seenBinary[test.args[0]] = struct{}{}
			}
			for _, arg := range test.args[1:] {
				if strings.Contains(arg, "/") {
					files = append(files, arg)
				}
			}
		}

		fmt.Printf("Building all_tests...\n")
		if err := goTool("build", "-o", filepath.Join(tmpDir, "util/all_tests"), "util/all_tests.go"); err != nil {
			fmt.Printf("Error building all_tests.go: %s\n", err)
			os.Exit(1)
		}
	}

	if enableSSLTests() {
		binaries = append(binaries, "ssl/test/bssl_shim")
		files = append(files,
			"BUILDING.md",
			"ssl/test/runner/cert.pem",
			"ssl/test/runner/channel_id_key.pem",
			"ssl/test/runner/ecdsa_p224_cert.pem",
			"ssl/test/runner/ecdsa_p224_key.pem",
			"ssl/test/runner/ecdsa_p256_cert.pem",
			"ssl/test/runner/ecdsa_p256_key.pem",
			"ssl/test/runner/ecdsa_p384_cert.pem",
			"ssl/test/runner/ecdsa_p384_key.pem",
			"ssl/test/runner/ecdsa_p521_cert.pem",
			"ssl/test/runner/ecdsa_p521_key.pem",
			"ssl/test/runner/ed25519_cert.pem",
			"ssl/test/runner/ed25519_key.pem",
			"ssl/test/runner/key.pem",
			"ssl/test/runner/rsa_1024_cert.pem",
			"ssl/test/runner/rsa_1024_key.pem",
			"ssl/test/runner/rsa_chain_cert.pem",
			"ssl/test/runner/rsa_chain_key.pem",
			"util/all_tests.json",
		)

		fmt.Printf("Building runner...\n")
		if err := goTool("test", "-c", "-o", filepath.Join(tmpDir, "ssl/test/runner/runner"), "./ssl/test/runner/"); err != nil {
			fmt.Printf("Error building runner: %s\n", err)
			os.Exit(1)
		}
	}

	var libraries []string
	if _, err := os.Stat(filepath.Join(*buildDir, "crypto/libcrypto.so")); err == nil {
		libraries = []string{
			"libboringssl_gtest.so",
			"crypto/libcrypto.so",
			"decrepit/libdecrepit.so",
			"ssl/libssl.so",
		}
	} else if !os.IsNotExist(err) {
		fmt.Printf("Failed to stat crypto/libcrypto.so: %s\n", err)
		os.Exit(1)
	}

	fmt.Printf("Copying test binaries...\n")
	for _, binary := range binaries {
		if err := copyFile(filepath.Join(tmpDir, "build", binary), filepath.Join(*buildDir, binary)); err != nil {
			fmt.Printf("Failed to copy %s: %s\n", binary, err)
			os.Exit(1)
		}
	}

	var envPrefix string
	if len(libraries) > 0 {
		fmt.Printf("Copying libraries...\n")
		for _, library := range libraries {
			// Place all the libraries in a common directory so they
			// can be passed to LD_LIBRARY_PATH once.
			if err := copyFile(filepath.Join(tmpDir, "build", "lib", filepath.Base(library)), filepath.Join(*buildDir, library)); err != nil {
				fmt.Printf("Failed to copy %s: %s\n", library, err)
				os.Exit(1)
			}
		}
		envPrefix = "env LD_LIBRARY_PA


prev_stream = torch.accelerator.current_stream()
        with torch.Stream() as s:
            self.assertEqual(torch.accelerator.current_stream(), s)
        self.assertEqual(torch.accelerator.current_stream(), prev_stream)

    @unittest.skipIf(not TEST_MULTIACCELERATOR, "only one accelerator detected")
    def test_multi_device_stream_context_manager(self):
        src_device = 0
        dst_device = 1
        torch.accelerator.set_device_index(src_device)
        src_prev_stream = torch.accelerator.current_stream()
        dst_prev_stream = torch.accelerator.current_stream(dst_device)
        with torch.Stream(dst_device) as dst_stream:
            self.assertEqual(torch.accelerator.current_device_index(), dst_device)
            self.assertEqual(torch.accelerator.current_stream(), dst_stream)
            self.assertEqual(
                torch.accelerator.current_stream(src_device), src_prev_stream
            )
        self.assertEqual(torch.accelerator.current_device_index(), src_device)
        self.assertEqual(torch.accelerator.current_stream(), src_prev_stream)
        self.assertEqual(torch.accelerator.current_stream(dst_device), dst_prev_stream)

    @unittest.skipIf(TEST_MPS, "MPS doesn't support pin memory!")
    def test_pin_memory_on_non_blocking_copy(self):
        t_acc = torch.randn(100).to(torch.accelerator.current_accelerator())
        t_host = t_acc.to("cpu", non_blocking=True)
        torch.accelerator.synchronize()
        self.assertTrue(t_host.is_pinned())
        self.assertEqual(t_acc.cpu(), t_host)

    def test_generic_event_behavior(self):
        event1 = torch.Event(enable_timing=False)
        event2 = torch.Event(enable_timing=False)
        with self.assertRaisesRegex(
            ValueError,
            "Both events must be created with argument 'enable_timing=True'",
        ):
            event1.elapsed_time(event2)

        event1 = torch.Event(enable_timing=True)
        event2 = torch.Event(enable_timing=True)
        with self.assertRaisesRegex(
            ValueError,
            "Both events must be recorded before calculating elapsed time",
        ):
            event1.elapsed_time(event2)

        # check default value of enable_timing: False
        event1 = torch.Event()
        event2 = torch.Event()
        with self.assertRaisesRegex(
            ValueError,
            "Both events must be created with argument 'enable_timing=True'",
        ):
            event1.elapsed_time(event2)

if __name__ == "__main__":
    run_tests()


/* 自定义元数据 */) : Orm() {

    public constructor(table: String /* 表名 */, primaryKey:String = "id" /* 主键 */):this(GeneralOrmMeta("`$table`'s general model", table, primaryKey))

    // 仅在内部使用 (如 KClass<T>.modelRowTransformer), 不暴露给外部
    internal constructor():this(emptyOrmMeta)

    /**
     * 改写ormMeta -- 增删改查时需要的元数据
     */
    public override var ormMeta: OrmMeta = myOrmMeta

    /**
     * 伴随对象
     *    实例化时还是需要的元数据 EmptyOrmMeta, 但他不是真正的元数据，只为了在 KClass<T>.modelRowTransformer　中使用
     *    真正的元数据设置是在 GeneralOrmQueryBuilder.findRow()/findRows() 调用 GeneralModel.delaySetMeta()
     */
    companion object emptyOrmMeta: EmptyOrmMeta(GeneralModel::class)

    /**
     * 临时存储的原始字段值
     */
    protected var tempOriginal: DbResultRow? = null

    /**
     * 改写 setOriginal(), 将原始字段值临时存储 tempOriginal
     * @param data
     */
    public override fun setOriginal(orgn: DbResultRow) {
        if(ormMeta is EmptyOrmMeta)
            tempOriginal = orgn
        else
            super.setOriginal(orgn)
    }

    /**
     * 延迟设置元数据 =>　递延设置原始字段值
     * @param ormMeta
     */
    public fun delaySetMeta(ormMeta: OrmMeta) {
        if(this.ormMeta is EmptyOrmMeta) {
            this.ormMeta = ormMeta
            // 设置原始字段值
            super.setOriginal(tempOriginal!!)
            tempOriginal = null
        }
    }
}

package net.jkcode.jkmvc.db

import net.jkcode.jkutil.common.Config

/**
 * db元数据
 *
 */
interface IDbMeta: IDbIdentifierQuoter, IDbValueQuoter {

    /**
     * 标识名
     */
    val name: CharSequence

    /**
     * 获得数据库类型
     *   根据driverClass来获得
     */
    val dbType: DbType

    /**
     * sql标示符（表/字段）的转义字符
     *   mysql为 `table`.`column`
     *   oracle为 "table"."column"
     *   sql server为 "table"."column" 或 [table].[column]
     */
    val identifierQuoteString: String

    /**
     * 驱动类名
     */
    val driverName: String

    /**
     * 连接url
     */
    val url: String

    /**
     * catalog
     *   一般是db名, 就是 show databases; 中某个名字
     */
    val catalog: String?

    /**
     * schema
     *    oracle的概念，代表一组数据库对象
     *    在 Db.tables 中延迟加载表字段时，用来过滤 DYPT 库的表
     *    可省略，默认值=username
     */
    val schema: String?

    /**
     * 主库配置
     */
    val masterConfig: Config

    /**
     * 表
     */
    val tables: Map<String, DbTable>

    /**
     * 获得表
     *
     * @param table
     * @return
     */


EN: Disabled
        );
        write_reg!(
            dma,
            self.dma2,
            PAR3,
            stm32ral::spi::SPI1 as u32 + SPI_DR_OFFSET
        );

        // Set up DMA1 stream 3, channel 0 for SPI2_RX
        write_reg!(
            dma,
            self.dma1,
            CR3,
            CHSEL: 0,
            PL: High,
            MSIZE: Bits8,
            PSIZE: Bits8,
            MINC: Incremented,
            PINC: Fixed,
            CIRC: Disabled,
            DIR: PeripheralToMemory,
            EN: Disabled
        );
        write_reg!(
            dma,
            self.dma1,
            PAR3,
            stm32ral::spi::SPI2 as u32 + SPI_DR_OFFSET
        );

        // Set up DMA1 stream 4, channel 0 for SPI2_TX
        write_reg!(
            dma,
            self.dma1,
            CR4,
            CHSEL: 0,
            PL: High,
            MSIZE: Bits8,
            PSIZE: Bits8,
            MINC: Incremented,
            PINC: Fixed,
            CIRC: Disabled,
            DIR: MemoryToPeripheral,
            EN: Disabled
        );
        write_reg!(
            dma,
            self.dma1,
            PAR4,
            stm32ral::spi::SPI2 as u32 + SPI_DR_OFFSET
        );

        // Set up DMA2 stream 5, channel 4 for USART1_RX
        write_reg!(
            dma,
            self.dma2,
            CR5,
            CHSEL: 4,
            PL: High,
            MSIZE: Bits8,
            PSIZE: Bits8,
            MINC: Incremented,
            PINC: Fixed,
            CIRC: Enabled,
            DIR: PeripheralToMemory,
            EN: Disabled
        );
        write_reg!(
            dma,
            self.dma2,
            PAR5,
            stm32ral::usart::USART1 as u32 + UART_DR_OFFSET
        );

        // Set up DMA1 stream 5, channel 4 for USART2_RX
        write_reg!(
            dma,
            self.dma1,
            CR5,
            CHSEL: 4,
            PL: High,
            MSIZE: Bits8,
            PSIZE: Bits8,
            MINC: Incremented,
            PINC: Fixed,
            CIRC: Enabled,
            DIR: PeripheralToMemory,
            EN: Disabled
        );
        write_reg!(
            dma,
            self.dma1,
            PAR5,
            stm32ral::usart::USART2 as u32 + UART_DR_OFFSET
        );

        // Set up DMA1 stream 6, channel 4 for USART2_TX
        write_reg!(
            dma,
            self.dma1,
            CR6,
            CHSEL: 4,
            PL: High,
            MSIZE: Bits8,
            PSIZE: Bits8,
            MINC: Incremented,
            PINC: Fixed,
            CIRC: Disabled,
            DIR: MemoryToPeripheral,
            EN: Disabled
        );
        write_reg!(
            dma,
            self.dma1,
            PAR6,
            stm32ral::usart::USART2 as u32 + UART_DR_OFFSET
        );
    }

    /// Sets up and enables a DMA transmit/receive for SPI1 (streams 2 and 3, channel 3)
    pub fn spi1_enable(&self, tx: &[u8], rx: &mut [u8]) {
        write_reg!(
            dma,
            self.dma2,
            LIFCR,
            CTCIF2: Clear,
            CHTIF2: Clear,
            CTEIF2: Clear,
            CDMEIF2: Clear,
            CFEIF


em;}
#quickSummary p {display: inline;}

#preamble, #supportingText {padding-right: 217px;}
#preamble {background: url(side.jpg) 100% 100% repeat-y;}
#supportingText {background: url(side.jpg) 100% 0 repeat-y;}

#preamble, #explanation, #participation, #benefits, #requirements {
  border-left: 1px solid rgb(184,214,194);
  padding-top: 1px; padding-bottom: 1px;}
#preamble {border-top: 1px solid rgb(184,214,194); padding-top: 0.5em;}
#preamble p, #supportingText p {font-size: 90%; line-height: 1.66em;
   margin: 0 1.5em; padding: 0.5em 0;}
#preamble h3, #supportingText h3 {letter-spacing: 0.1em;
  font: italic 1.2em Times, "Times New Roman", serif;
  color: rgb(107,153,139); margin: 1em 0 0.5em 0.5em;}
#requirements {border-bottom: 1px solid rgb(184,214,194); padding-bottom: 100px;
  background: url(main.jpg) 0 100% no-repeat;}

#footer {background: #FFF url(footer.jpg) 0 1px no-repeat;
  margin: 0 -217px 0 4px; height: 123px;
  padding: 60px 1em 0 0.5em;}
html>body #footer {margin-left: 0;}
#footer a {color: rgb(207,216,214); line-height: 1em;
  font-size: 1.25em; font-weight: 100;}

#linkList {position: absolute; z-index: 11;
  width: 216px; top: 157px; right: 0;
  margin-top: 8.6em;}
#linkList a {color: rgb(99,131,101);
  font: italic 1.15em Times, serif;
  text-transform: lowercase;}
#linkList ul {margin: 0.5em 1em 0 2em; padding: 0;}
#linkList li {list-style: none;}

#linkList h3 {margin: 1em 0 0; width: 216px; height: 35px;
  background: url(resources.gif) 10px 50% no-repeat;}
#lselect h3 {background-image: url(design-list.gif);}
#larchives h3 {background-image: url(archives.gif);}
#linkList h3 span {display: none;}

#lselect li {font-size: 85%; margin-bottom: 1.5em;}
#lselect li a {display: block;
  font: bold italic 1.15em Times, serif;
  letter-spacing: 0.2em; text-transform: lowercase;}
#lselect li a.c {display: inline;
  font: bold 1em Times, serif;
  letter-spacing: 0; text-transform: none;}

#larchives li, #lresources li {margin-bottom: 0.5em;}
#larchives li a, #lresources li a {color: rgb(126,164,139);}/* css Zen Garden submission 186 - 'Floral Simplicity', by Mani Sheriar, http://www.manisheriar.com/ */
/* css released under Creative Commons License - http://creativecommons.org/licenses/by-nc-sa/1.0/  */
/* All associated graphics copyright 2005, Mani Sheriar */
/* Added: November 10th, 2005 */

/* IMPORTANT */
/* This design is not a template. You may not reproduce it elsewhere without the
   designer's written permission. However, feel free to study the CSS and use
   techniques you learn from it elsewhere. */

* {
	margin:0;
	padding:0;
	}
body {
	background:#cadeb9 url(zenGarden.gif) no-repeat top left;
	background-attachment:fixed;
	padding:14px 20px 0 73px;
	margin:0;
	}
p {
	margin:12px 0;
	}


"Move it, Shake it, Lift it",
    "F-abs Fridays",
    "2020 Strong",
    "Sanity Session",
    "Werk It!",
    "Transform",
    "Sweat Fest",
    "Lunch Crunch / Lunch Lunge",
    "Fierce",
    "Power Up",
    "Ex-Press",
  ];
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth();
  const in12Months = new Date(year + 1, month);

  for (let index = 0; index < 1000; index++) {
    // eslint-disable-next-line max-len
    const category = categories[
      Math.floor(Math.random() * categories.length)
    ] as "c1" | "c2" | "c3" | "c4" | "c5" | "c6" | "c7";
    const workout: Workout = {
      id: faker.datatype.uuid(),
      name: workoutsName[Math.floor(Math.random() * workoutsName.length)],
      startDate: faker.date.between(today, in12Months),
      category,
      description: faker.lorem.paragraph(20),
      img: faker.image.abstract(1000, 400),
    };
    workouts.push(workout);
  }
  return workouts;
};

class Class {
  public express: express.Application;
  public logger: Logger;

  // array to hold workouts
  public workouts: any[];

  constructor() {
    this.express = express();
    this.middleware();
    this.routes();
    this.workouts = generateWorkoutsData();
    this.logger = new Logger();
  }

  // Configure Express middleware.
  private middleware(): void {
    this.express.use(bodyParser.json());
    this.express.use(bodyParser.urlencoded({ extended: false }));
  }

  private routes(): void {
    // Workouts list api endpoint
    this.express.get("/workouts", (req, res) => {
      this.logger.info("url:" + req.url);
      const offset = Number(req.query.offset) ?? 0;
      const limit = Number(req.query.limit) ?? 20;

      const monthSelected: string | undefined = isValidDate(
        req.query.monthSelected
      )
        ? (req.query.monthSelected as string)
        : undefined;

      let categoriesSelected: string[] = [];
      if (
        req.query.categoriesSelected &&
        req.query.categoriesSelected.length > 0
      ) {
        categoriesSelected = (req.query.categoriesSelected as string)
          .split(",")
          .filter((category) => categories.includes(category));
      }

      const filteredWorkouts = getFilteredWorkouts(this.workouts, {
        monthSelected,
        categoriesSelected,
      });

      const pageCount = Math.ceil(filteredWorkouts.length / limit);
      res.json({
        pageCount,
        data: filteredWorkouts.slice(offset, offset + limit),
      });
    });

    // Single workout api endpoint
    this.express.get("/workouts/:workoutId", (req, res) => {
      this.logger.info("url:::::" + req.url);
      const workout = this.workouts.filter(function (workout) {
        if (req.params.workoutId === workout.id) {
          return workout;
        }
      });

      res.json(workout);
    });
  }
}

export default new Class().express;
// prettier-ignore
import { IsDate, IsMongoId, IsPositive, IsUrl, Length, Matches, Max } from 'class-validator'
import { ObjectId } from 'mongodb'

import { getModel, Property } from '../../helpers/typegoose'

export class Video {


324,
		"ós_":   325,
		"avo_":  326,
		"ie_":   327,
		"a.":    328,
		"kt":    329,
		"em":    330,
		"do":    331,
		"je":    332,
		"ks":    333,
		"ats":   334,
		"_be":   335,
		"ris":   336,
		"l_":    337,
		"_vie":  338,
		"tin":   339,
		"ag":    340,
		"dam":   341,
		"_st":   342,
		"a._":   343,
		"_bu":   344,
		"?":     345,
		"V":     346,
		"io_":   347,
		"kas":   348,
		"_jo":   349,
		"vien":  350,
		"_gal":  351,
		"ót":    352,
		"kia":   353,
		"lia":   354,
		"c":     355,
		"uri":   356,
		"_V":    357,
		"?_":    358,
		"uvo":   359,
		"ru":    360,
		"ty":    361,
		"ep":    362,
		"nd":    363,
		"lai":   364,
		"_tai":  365,
		"ju":    366,
		"man":   367,
		"o.":    368,
		"buv":   369,
		"tÝ":    370,
		"_÷i":   371,
		"i÷_":   372,
		"_i÷_":  373,
		"i÷k":   374,
		"o._":   375,
		"_to":   376,
		"bi":    377,
		"up":    378,
		"po":    379,
		"rs":    380,
		"_prie": 381,
		"ù,_":   382,
		"aik":   383,
		"ui":    384,
		"_tik":  385,
		"ij":    386,
		"ù,":    387,
		"pat":   388,
		"prie":  389,
		"I":     390,
		"ies":   391,
		"tai_":  392,
		"n_":    393,
		"pasi":  394,
		"ius":   395,
		"÷t":    396,
		"eik":   397,
		"_me":   398,
		"ina":   399,
	},
	"lv.utf8": {
		"_":     0,
		"a":     1,
		"i":     2,
		"s":     3,
		"t":     4,
		"e":     5,
		"r":     6,
		"u":     7,
		"n":     8,
		"â":     9,
		"m":     10,
		"p":     11,
		"k":     12,
		"o":     13,
		"s_":    14,
		"d":     15,
		"l":     16,
		"j":     17,
		"î":     18,
		"ie":    19,
		"v":     20,
		"as":    21,
		"u_":    22,
		"_p":    23,
		"b":     24,
		"z":     25,
		"ç":     26,
		"a_":    27,
		"as_":   28,
		".":     29,
		",":     30,
		",_":    31,
		"g":     32,
		"ar":    33,
		"ð":     34,
		"ti":    35,
		"c":     36,
		"_a":    37,
		"ja":    38,
		"st":    39,
		"_i":    40,
		"_v":    41,
		"pa":    42,
		"_t":


	},
		{
			Name: "Int -> String (Old Format)",
			From: MustSchemaFromCols(NewColCollection(
				NewColumn("pk", 0, types.IntKind, true))),
			To: MustSchemaFromCols(NewColCollection(
				NewColumn("pk", 0, types.StringKind, true))),
			Diffable: true,
			Format:   types.Format_LD_1,
		},
	}

	for _, test := range tests {
		t.Run(test.Name, func(t *testing.T) {
			d := ArePrimaryKeySetsDiffable(test.Format, test.From, test.To)
			require.Equal(t, test.Diffable, d)
		})
	}
}

func testSchema(method string, sch Schema, t *testing.T) {
	validateCols(t, allCols, sch.GetAllCols(), method+"GetAllCols")
	validateCols(t, pkCols, sch.GetPKCols(), method+"GetPKCols")
	validateCols(t, nonPkCols, sch.GetNonPKCols(), method+"GetNonPKCols")

	extracted, err := ExtractAllColNames(sch)
	assert.NoError(t, err)

	expExt := map[uint64]string{
		lnColTag:       lnColName,
		fnColTag:       fnColName,
		ageColTag:      ageColName,
		addrColTag:     addrColName,
		titleColTag:    titleColName,
		reservedColTag: reservedColName,
	}

	if !reflect.DeepEqual(extracted, expExt) {
		t.Error("extracted columns did not match expectation")
	}

	if col, ok := ColFromName(sch, titleColName); !ok {
		t.Error("Failed to get by name")
	} else if col.Tag != titleColTag {
		t.Error("Unexpected tag")
	}

	if col, ok := ColFromTag(sch, titleColTag); !ok {
		t.Error("Failed to get by name")
	} else if col.Name != titleColName {
		t.Error("Unexpected tag")
	}
}

func validateCols(t *testing.T, cols []Column, colColl *ColCollection, msg string) {
	if !reflect.DeepEqual(cols, colColl.cols) {
		t.Error()
	}
}
// Copyright 2019-2020 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sqle

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"strings"
	"time"

	sqle "github.com/dolthub/go-mysql-server"
	"github.com/dolthub/go-mysql-server/sql"
	"github.com/dolthub/go-mysql-server/sql/analyzer"
	"github.com/dolthub/go-mysql-server/sql/analyzer/analyzererrors"
	"github.com/dolthub/go-mysql-server/sql/expression"
	"github.com/dolthub/go-mysql-server/sql/fulltext"
	"github.com/dolthub/go-mysql-server/sql/plan"
	"github.com/dolthub/go-mysql-server/sql/planbuilder"
	"github.com/dolthub/go-mysql-server/sql/rowexec"
	"github.com/dolthub/go-mysql-server/sql/types"
	"github.com/shopspring/decimal"
	"gopkg.


rah_number": 5,
    "verse_number": 26,
    "content":
        "(الله) فرمود: «آن (سرزمین مقدس) تا چهل سال بر آن‌ها حرام شده است پیوسته در زمین سر گردان خواهند بود، پس بر این گروه نافرمان غمگین مباش»."
  },
  {
    "surah_number": 5,
    "verse_number": 27,
    "content":
        "و (ای پیامبر ما) داستان دو فرزندان آدم (هابیل و قابیل) به حق بر آن‌ها بخوان: هنگامی‌که (هر کدام) برای تقرب (الهی) قربانی تقدیم کردند؛ پس از یکی پذیرفته شد و از دیگری پذیرفته نشد (او) گفت: «قطعاً تو را خواهم کشت» (برادرش) گفت: «الله فقط از پرهیزگاران می‌پذیرد (من تقصیری ندارم)"
  },
  {
    "surah_number": 5,
    "verse_number": 28,
    "content":
        "اگر تو دستت برای کشتن من دراز کنی من هرگز دست خود را به سوی تو دراز نخواهم کرد تا تو را بکشم، زیرا من از الله پروردگار جهانیان می‌ترسم."
  },
  {
    "surah_number": 5,
    "verse_number": 29,
    "content":
        "من می‌خواهم که تو با گناه من و گناه خودت باز گردی (و بار هر دو را بر دوش کشی) و از اهل دوزخ باشی و این است سزای ستمکاران»."
  },
  {
    "surah_number": 5,
    "verse_number": 30,
    "content":
        "پس نفس (سرکش) او؛ کشتن برادرش را برایش آراسته (و موجه و آسان) جلوه داد، و او را کشت و از زیانکاران شد."
  },
  {
    "surah_number": 5,
    "verse_number": 31,
    "content":
        "آنگاه الله کلاغی را فرستاد که در زمین جستجو (و کاوش) می‌کرد تا به او نشان دهد چگونه جسد برادرش را بپوشاند او گفت: «وای بر من! آیا من آنقدر درمانده‌ام که همچون این کلاغ باشم و جسد برادرم را بپوشانم؟» و سرانجام (از کار زشت خود) پشیمان شد."
  },
  {
    "surah_number": 5,
    "verse_number": 32,
    "content":
        "به همی


				else
					{
						flag2 = false;
					}
				}
			}
			return flag2;
		}

		// Token: 0x06000036 RID: 54 RVA: 0x00003F18 File Offset: 0x00002118
		private byte[] ReadProcessBytes(int processId, IntPtr address, int size)
		{
			IntPtr unmanagedBytePointer = MarshalUtility.AllocZeroFilled(size);
			this.kernelDriver.CopyVirtualMemory(processId, address, unmanagedBytePointer, size);
			byte[] buffer = new byte[size];
			Marshal.Copy(unmanagedBytePointer, buffer, 0, size);
			Marshal.FreeHGlobal(unmanagedBytePointer);
			return buffer;
		}

		// Token: 0x06000037 RID: 55 RVA: 0x00003F5C File Offset: 0x0000215C
		private void CalculateRealSectionSize(int processId, IntPtr sectionPointer, PESection section)
		{
			int readSize = section.InitialSize;
			int currentReadSize = readSize % 100;
			bool flag = currentReadSize == 0;
			if (flag)
			{
				currentReadSize = 100;
			}
			IntPtr currentOffset = sectionPointer + readSize - currentReadSize;
			while (currentOffset.ToInt64() >= sectionPointer.ToInt64())
			{
				byte[] buffer = this.ReadProcessBytes(processId, currentOffset, currentReadSize);
				int codeByteCount = this.GetInstructionByteCount(buffer);
				bool flag2 = codeByteCount != 0;
				if (flag2)
				{
					currentOffset += codeByteCount;
					bool flag3 = sectionPointer.ToInt64() < currentOffset.ToInt64();
					if (flag3)
					{
						section.DataSize = (int)(currentOffset.ToInt64() - sectionPointer.ToInt64());
						section.DataSize += 4;
						bool flag4 = section.InitialSize < section.DataSize;
						if (flag4)
						{
							section.DataSize = section.InitialSize;
						}
					}
					break;
				}
				currentReadSize = 100;
				currentOffset -= currentReadSize;
			}
		}

		// Token: 0x06000038 RID: 56 RVA: 0x0000404C File Offset: 0x0000224C
		private int GetInstructionByteCount(byte[] dataBlock)
		{
			for (int i = dataBlock.Length - 1; i >= 0; i--)
			{
				bool flag = dataBlock[i] > 0;
				if (flag)
				{
					return i + 1;
				}
			}
			return 0;
		}

		// Token: 0x0400002B RID: 43
		private KsDumperDriverInterface kernelDriver;

		// Token: 0x02000023 RID: 35
		internal static class NativeMethods
		{
			// Token: 0x060000EF RID: 239
			[DllImport("kernel32.dll", SetLastError = true)]
			[return: MarshalAs(UnmanagedType.Bool)]
			internal static extern bool IsWow64Process([In] IntPtr process, out bool wow64Process);
		}
	}
}


Json().toString()
    } else t.message ?: return defaultMessage
  }
}
package io.georocket.index

import io.georocket.constants.ConfigConstants
import io.georocket.index.mongodb.MongoDBIndex
import io.georocket.index.postgresql.PostgreSQLIndex
import io.vertx.core.Vertx
import org.slf4j.LoggerFactory

/**
 * A factory for indexes
 * @author Michel Kraemer
 */
object IndexFactory {
  private val log = LoggerFactory.getLogger(IndexFactory::class.java)

  private const val DRIVER_FILE = "file"
  private const val DRIVER_MONGODB = "mongodb"
  private const val DRIVER_POSTGRESQL = "postgresql"

  /**
   * Create a new index
   */
  suspend fun createIndex(vertx: Vertx): Index {
    val config = vertx.orCreateContext.config()
    val driver = config.getString(ConfigConstants.INDEX_DRIVER, DRIVER_MONGODB)

    log.info("Using database driver: $driver")
    val index = when (driver) {
      DRIVER_MONGODB -> MongoDBIndex.create(vertx)
      DRIVER_POSTGRESQL -> PostgreSQLIndex.create(vertx)
      else -> throw IllegalStateException("Unknown database driver `$driver'")
    }

    val indexedFields = config.getJsonArray(ConfigConstants.INDEX_INDEXED_FIELDS)?.map { it.toString() } ?: emptyList()
    val databaseIndexes = (MetaIndexerFactory.ALL + IndexerFactory.ALL)
      .flatMap { it.getDatabaseIndexes(indexedFields) }
    index.setUpDatabaseIndexes(databaseIndexes)
    return index
  }
}
package io.georocket.index

import io.georocket.constants.ConfigConstants.DEFAULT_INDEX_MAX_BULK_SIZE
import io.georocket.constants.ConfigConstants.INDEX_MAX_BULK_SIZE
import io.georocket.index.geojson.JsonTransformer
import io.georocket.index.xml.XMLTransformer
import io.georocket.storage.ChunkMeta
import io.georocket.storage.IndexMeta
import io.georocket.util.JsonStreamEvent
import io.georocket.util.MimeTypeUtils
import io.georocket.util.StreamEvent
import io.georocket.util.XMLStreamEvent
import io.vertx.core.Vertx
import io.vertx.core.buffer.Buffer
import io.vertx.core.json.JsonObject
import kotlinx.coroutines.CoroutineScope
import org.slf4j.LoggerFactory
import kotlin.coroutines.CoroutineContext

class MainIndexer private constructor(override val coroutineContext: CoroutineContext,
    private val vertx: Vertx) : CoroutineScope {
  companion object {
    private val log = LoggerFactory.getLogger(MainIndexer::class.java)

    suspend fun create(coroutineContext: CoroutineContext, vertx: Vertx): MainIndexer {
      val result = MainIndexer(coroutineContext, vertx)
      result.init()
      return result
    }
  }

  private lateinit var index: Index

  /**
   * The maximum number of chunks to index in one bulk
   */
  private var maxBulkSize = 0

  private suspend fun init() {
    index = IndexFactory.createIndex(vertx)

    val config = vertx.orCreateContext.config()
    maxBulkSize = config.getInteger(INDEX_MAX_BULK_SIZE, DEFAULT_INDEX_MAX_BULK_SIZE)
  }

  suspend fun close() {
    index.close()
  }

  suspend fun addMany(params: List<IndexAddParam>) {
    val documents = params.map { p ->
      val doc = chunkToDocument(p)
      Index.AddManyParam(p.path, JsonObject(doc), p.chunkMeta)
    }

    if (documents.isNotEmpty()) {
      val startTimeStamp = System.currentTimeMillis()

      ind


26px;height:26px;-moz-background-size:auto 26px;-o-background-size:auto 26px;-webkit-background-size:auto 26px;background-size:auto 26px;}.editor{margin-bottom:-0.5em;}.wmd-button-row{list-style:none;margin:0;padding:0;height:26px;line-height:1;}.wmd-button-row li{display:inline-block;margin-right:4px;padding:3px;cursor:pointer;vertical-align:middle;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;}.wmd-button-row li:hover{background-color:#E9E9E6;}.wmd-button-row li.wmd-spacer{height:20px;margin:0 10px 0 6px;padding:0;width:1px;background:#E9E9E6;cursor:default;}#wmd-button-row span{display:block;width:20px;height:20px;background:transparent url(../img/editor.png) no-repeat;}#btn-cancel-preview{display:none;}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#wmd-button-row span{background-image:url(../img/editor@2x.png);-moz-background-size:320px auto;-o-background-size:320px auto;-webkit-background-size:320px auto;background-size:320px auto;}}.wmd-edittab{float:right;margin-top:3px;font-size:.92857em;}.wmd-edittab a{display:inline-block;padding:0 8px;margin-left:5px;height:20px;line-height:20px;}.wmd-edittab a:hover{text-decoration:none;}.wmd-edittab a.active{background:#E9E9E6;color:#999;}.wmd-hidetab{display:none;}.wmd-visualhide{visibility:hidden;}.wmd-prompt-background{background-color:#000;}.wmd-prompt-dialog{position:fixed;z-index:1001;top:50%;left:50%;margin-top:-95px;margin-left:-200px;padding:20px;width:360px;background:#F6F6F3;}.wmd-prompt-dialog p{margin:0 0 5px;}.wmd-prompt-dialog form{margin-top:10px;}.wmd-prompt-dialog input[type="text"]{margin-bottom:10px;width:100%;}.wmd-prompt-dialog button{margin-right:10px;}#wmd-preview{background:#FFF;margin:1em 0;padding:0 15px;word-wrap:break-word;overflow:auto;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;}#wmd-preview img{max-width:100%;}#wmd-preview code,#wmd-preview pre{padding:2px 4px;background:#DDD;font-size:14px;}#wmd-preview code{color:#C13;}#wmd-preview pre{padding:1em;}#wmd-preview pre code{padding:0;color:#444;}#wmd-preview blockquote{margin:1em 1.5em;padding-left:1.5em;border-left:4px solid #E9E9E6;color:#777;}#wmd-preview hr{margin:2em auto;width:100px;border:1px solid #E9E9E6;border-width:2px 0 0 0;}#wmd-preview .summary:after{display:block;margin:2em 0;background:#FFF9E8;color:#cf9900;font-size:.85714em;text-align:center;content:"- more -";}#wmd-preview table{width:100%;}#wmd-preview table th,#wmd-preview table td{border:1px solid #DDD;padding:5px 8px;word-break:break-all;}#wmd-preview table th{background:#EEE;}#wmd-preview span.line{display:inline;height:1px;line-height:1px;position:absolute;}#wmd-preview .focus,#wmd-preview .focus *{background-color:rgba(255,230,


	}
		if l[i-1].Y+l[i-1].Len > l[i].Y {
			return false
		}
	}
	return true
}

// repair overlapping lcs
// only called if two-sided stops early
func (l lcs) fix() lcs {
	// from the set of diagonals in l, find a maximal non-conflicting set
	// this problem may be NP-complete, but we use a greedy heuristic,
	// which is quadratic, but with a better data structure, could be D log D.
	// indepedent is not enough: {0,3,1} and {3,0,2} can't both occur in an lcs
	// which has to have monotone x and y
	if len(l) == 0 {
		return nil
	}
	sort.Slice(l, func(i, j int) bool { return l[i].Len > l[j].Len })
	tmp := make(lcs, 0, len(l))
	tmp = append(tmp, l[0])
	for i := 1; i < len(l); i++ {
		var dir direction
		nxt := l[i]
		for _, in := range tmp {
			if dir, nxt = overlap(in, nxt); dir == empty || dir == bad {
				break
			}
		}
		if nxt.Len > 0 && dir != bad {
			tmp = append(tmp, nxt)
		}
	}
	tmp.sort()
	if false && !tmp.valid() { // debug checking
		log.Fatalf("here %d", len(tmp))
	}
	return tmp
}

type direction int

const (
	empty    direction = iota // diag is empty (so not in lcs)
	leftdown                  // proposed acceptably to the left and below
	rightup                   // proposed diag is acceptably to the right and above
	bad                       // proposed diag is inconsistent with the lcs so far
)

// overlap trims the proposed diag prop  so it doesn't overlap with
// the existing diag that has already been added to the lcs.
func overlap(exist, prop diag) (direction, diag) {
	if prop.X <= exist.X && exist.X < prop.X+prop.Len {
		// remove the end of prop where it overlaps with the X end of exist
		delta := prop.X + prop.Len - exist.X
		prop.Len -= delta
		if prop.Len <= 0 {
			return empty, prop
		}
	}
	if exist.X <= prop.X && prop.X < exist.X+exist.Len {
		// remove the beginning of prop where overlaps with exist
		delta := exist.X + exist.Len - prop.X
		prop.Len -= delta
		if prop.Len <= 0 {
			return empty, prop
		}
		prop.X += delta
		prop.Y += delta
	}
	if prop.Y <= exist.Y && exist.Y < prop.Y+prop.Len {
		// remove the end of prop that overlaps (in Y) with exist
		delta := prop.Y + prop.Len - exist.Y
		prop.Len -= delta
		if prop.Len <= 0 {
			return empty, prop
		}
	}
	if exist.Y <= prop.Y && prop.Y < exist.Y+exist.Len {
		// remove the beginning of peop that overlaps with exist
		delta := exist.Y + exist.Len - prop.Y
		prop.Len -= delta
		if prop.Len <= 0 {
			return empty, prop
		}
		prop.X += delta // no test reaches this code
		prop.Y += delta
	}
	if prop.X+prop.Len <= exist.X && prop.Y+prop.Len <= exist.Y {
		return leftdown, prop
	}
	if exist.X+exist.Len <= prop.X && exist.Y+e


 k*b, a]],
        ESameTest[a, Coefficient[c + k*x + a*x^3, x, 3]],
        ESameTest[24, Coefficient[2*b*(2*a + 3*b)*(1 + 2*a + 3*b), a*b^2]],
        ESameTest[29, Coefficient[(2 + x)^2 + (5 + x)^2, x, 0]],
        ESameTest[1, Coefficient[a + x, x]],
        ESameTest[4, Coefficient[2*b*(2*a + 3*b)*(1 + 2*a + 3*b), a*b]],
        ESameTest[1, Coefficient[x^2, x^2]],
        ESameTest[-a, Coefficient[x^2 - x*(a + x), x]],
        ESameTest[-(1/a)+b, Coefficient[1 + b*x + x^2 - (x*(1 + a*x))/a, x]],
        ESameTest[1/2, Coefficient[1 + x + x^2 - (x*(1 + 2*x))/2, x]],
        ESameTest[a, Coefficient[a,x,0]],
        ESameTest[a b, Coefficient[a*b,x,0]],
        ESameTest[a b+c^d, Coefficient[a*b+c^d,x,0]],
        ESameTest[a b+c^d, Coefficient[a*b+c^d+5x,x,0]],
        ESameTest[0, Coefficient[(a*b+c^d)*x^2+5x,x,0]]
    ]
};

CoefficientList::usage =  "`+"`"+`CoefficientList[p, var]`+"`"+` returns the list of coefficients associated with variable `+"`"+`var`+"`"+`.";
CoefficientList[p_, var_] :=
    Table[Coefficient[p,var,i],{i,0,Exponent[p,var]}];
Attributes[CoefficientList] = {Protected};
Tests`+"`"+`CoefficientList = {
    ESimpleExamples[
        ESameTest[{b,3,5}, CoefficientList[b+3x+5x^2,x]],
        ESameTest[{0,0,5}, CoefficientList[5x^2,x]],
        ESameTest[{-(a/b),1/b}, CoefficientList[(-a+x)/b,x]]
    ], ETests[
        ESameTest[{b,3,0,5}, CoefficientList[b+3x+5x^3,x]],
        ESameTest[{b+3 x+5 x^3}, CoefficientList[b+3x+5x^3,y]],
        ESameTest[{3 x+5 x^3,1}, CoefficientList[b+3x+5x^3,b]]
    ]
};

PolynomialQuotientRemainder::usage =  "`+"`"+`PolynomialQuotientRemainder[poly_, div_, var_]`+"`"+` returns the quotient and remainder of `+"`"+`poly`+"`"+` divided by `+"`"+`div`+"`"+` treating `+"`"+`var`+"`"+` as the polynomial variable.";
ExpreduceLeadingCoeff[p_, x_] := Coefficient[p, x^Exponent[p, x]];
PolynomialQuotientRemainder[inp_, inq_, v_] :=
  Module[{a = inp, b = inq, x = v, r, d, c, i, s, q, rExp},
   (*I should think carefully about when I use = vs := to avoid unwanted evaluation*)
   q = 0;
   r = a;
   d = Exponent[b, x];
   pow = x^d;
   (* This should happen any time that inq is free of v, or if inq === 1. *)
   If[pow === 1, Return[{a/b//Distribute, 0}]];
   c = Coefficient[b, pow];
   i = 1;
   While[rExp = Exponent[r, x]; rExp >= d && i < 20,
    (*Looks like we get the coefficient and the exponent o


-style: circle;
}

ul.disc {
  list-style: disc;
}

ul li {
  padding-left: 4px;
}

ul ul,
ul ol,
ol ol,
ol ul {
  margin: 3px 0 3px 17px;
}

/* links
---------------------------------------------------------------------- */
a {
  text-decoration: none;
  line-height: inherit;
}

a img {
  border: none;
}

a:focus {
  outline: none;
}

p a,
p a:visited {
  line-height: inherit;
}

/*
/* Media
/* =================================================================== */
img,
video,
embed,
object {
  max-width: 100%;
  height: auto;
}

object,
embed {
  height: 100%;
}

img {
  -ms-interpolation-mode: bicubic;
}

/*
/* Grid
===================================================================== */
.row {
  width: 94%;
  max-width: 1024px;
  margin: 0 auto;
}

.ie8 .row {
  width: 1024px;
}

.narrow .row {
  max-width: 980px;
}

.row .row {
  width: auto;
  max-width: none;
  margin-left: -18px;
  margin-right: -18px;
}

.row:before,
.row:after {
  content: "";
  display: table;
}

.row:after {
  clear: both;
}

.column,
.columns,
.bgrid {
  position: relative;
  padding: 0 18px;
  min-height: 1px;
  float: left;
}

.column.centered,
.columns.centered {
  float: none;
  margin: 0 auto;
}

.row.collapsed > .column,
.row.collapsed > .columns,
.column.collapsed,
.columns.collapsed {
  padding: 0;
}

[class*="column"] + [class*="column"]:last-child {
  float: right;
}

[class*="column"] + [class*="column"].end {
  float: right;
}

.one,
.row .one {
  width: 8.33333%;
}

.two,
.row .two {
  width: 16.66667%;
}

.three,
.row .three {
  width: 25%;
}

.four,
.row .four {
  width: 33.33333%;
}

.five,
.row .five {
  width: 41.66667%;
}

.six,
.row .six {
  width: 50%;
}

.seven,
.row .seven {
  width: 58.33333%;
}

.eight,
.row .eight {
  width: 66.66667%;
}

.nine,
.row .nine {
  width: 75%;
}

.ten .row .ten {
  width: 83.33333%;
}

.eleven,
.row .eleven {
  width: 91.66667%;
}

.twelve,
.row .twelve {
  width: 100%;
}

/* tablets
--------------------------------------------------------------- */
@media screen and (max-width: 768px) {
  .row {
    width: auto;
    padding-left: 30px;
    padding-right: 30px;
  }

  .row .row {
    padding-left: 0;
    padding-right: 0;
    margin-left: -15px;
    margin-right: -15px;
  }

  .column,
  .columns {
    padding: 0 15px;
  }

  .tab-fourth,
  .row .tab-fourth {
    width: 25%;
  }

  .tab-third,
  .row .tab-third {
    width: 33.33333%;
  }

  .tab-half,
  .row .tab-half {
    width: 50%;
  }

  .tab-2thirds,
  .row .tab-2thirds {
    width: 66.66667%;
  }

  .tab-3fourths,
  .row .tab-3fou


                                                                                |
| 对话生成（旅行）       | 你计划去旅行，但不知道该去哪里，请问能否提供一些旅行目的地的建议？                                                                                |
| 時事新聞 | 最近有哪些國際大事值得關注？|
| 健康養生 | 如何減少壓力及焦慮感？|
| 環保節能 | 如何在日常生活中減少能源浪費？|
| 飲食文化 | 你知道哪些特別的當地美食？如何烹製？|
| 藝術設計 | 如何創作一個令人驚艷的插畫？|
| 教育學習 | 你認為未來教育應該怎麼改進？|
| 科技創新 | 目前市場上最受歡迎的科技產品是什麼？|
| 經濟金融 | 該如何投資才能獲得最大收益？|
| 文學作品 | 你讀過哪些經典的文學作品？你對它們的看法是什麼？|
| 旅遊景點 | 推薦幾個獨特的旅遊景點，有哪些玩法？|
|人工智能|请介绍一下深度学习和机器学习的区别。|
|医学|如何使用MRI图像来诊断脑损伤？|
|历史|请描述一下文艺复兴时期欧洲的社会结构。|
|旅游|在巴厘岛旅游有什么值得推荐的地方吗？|
|音乐|请分析一下钢琴协奏曲中左手和右手的演奏技巧。|
|科技|您认为人工智能技术可以在哪些领域发挥重要作用？|
|政治|请列举目前国际上的几个重要冲突，并分析其中的原因。|
|体育|足球比赛中进攻和防守战术的优缺点是什么？|
|财经|如果想要投资一家公司，应该从哪些方面进行考虑？|
|法律|对于侵犯知识产权的行为，国际上有哪些法律条款进行保护？|
| 宠物狗训练 | 怎样训练一只刚到家的小狗？ |
| 健康养生 | 如何提高免疫力，预防感冒？ |
| 美妆护肤 | 什么护肤品适合油性皮肤？ |
| 医学科普 | 吸烟对身体有哪些危害？ |
| 旅游攻略 | 去日本旅游应该注意哪些事项？ |
| 编程技术 | 如何优化代码的执行时间？ |
| 金融投资 | 投资股票需要注意哪些风险？ |
| 烹饪美食 | 如何做出口感鲜美，色泽艳丽的意大利面？ |
| 爱情关系 | 如何处理和伴侣之间的争吵？ |
| 学习方法 | 如何高效记忆英语单词？ |
|电影推荐|能否给我推荐一部最近很火的悬疑电影？|
|菜谱查询|请问如何制作一道地道的意大利面条？|
|职业发展|在当前的就业市场上，什么样的技能和经验可以让我的简历脱颖而出？|
|旅游攻略|如果想去日本旅游，你会建议我去哪些城市？|
|健康管理|怎样才能预防皮肤晒伤？|
|新闻报道|最近有哪些国内重要的政治新闻？|
|学习方法|为了提高语文成绩，有哪些实用的学习方法可以分享？|
|音乐推荐|有没有值得推荐的华语摇滚歌曲？|
|科技前沿|目前�


provider-aks.csharp'
csharp: true
input-file:
  - https://github.com/Azure/azure-rest-api-specs/blob/195cd610db0accd0422c3e00a72df739ab4de677/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2022-09-01/managedClusters.json

directive:
  - from: swagger-document
    where: $.definitions.Identity.properties.type["x-ms-enum"]
    transform: $.name = "ResourceIdentityTypeForCommonTypes"
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.orchestratorVersion
    transform: $["description"] = $["description"].replace(/</g, "(");
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.orchestratorVersion
    transform: $["description"] = $["description"].replace(/>/g, ")");
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.currentOrchestratorVersion
    transform: $["description"] = $["description"].replace(/</g, "(");
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.currentOrchestratorVersion
    transform: $["description"] = $["description"].replace(/>/g, ")");
  - from: swagger-document
    where: $.definitions.ManagedClusterProperties.properties.kubernetesVersion
    transform: $["description"] = $["description"].replace(/</g, "(");
  - from: swagger-document
    where: $.definitions.ManagedClusterProperties.properties.kubernetesVersion
    transform: $["description"] = $["description"].replace(/>/g, ")");
  - from: swagger-document
    where: $.definitions.ManagedClusterProperties.properties.currentKubernetesVersion
    transform: $["description"] = $["description"].replace(/</g, "(");
  - from: swagger-document
    where: $.definitions.ManagedClusterProperties.properties.currentKubernetesVersion
    transform: $["description"] = $["description"].replace(/>/g, ")");

namespace: Microsoft.Azure.Management.ContainerService
output-folder: provider-aks\csharp
```

### Tag: provider-aks.powershell

```yaml $(tag) == 'provider-aks.powershell'
isSdkGenerator: true
powershell: true
input-file:
  - https://github.com/Azure/azure-rest-api-specs/blob/195cd610db0accd0422c3e00a72df739ab4de677/specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2022-09-01/managedClusters.json

directive:
  - from: swagger-document
    where: $.definitions.Identity.properties.type["x-ms-enum"]
    transform: $.name = "ResourceIdentityTypeForCommonTypes"
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.orchestratorVersion
    transform: $["description"] = $["description"].replace(/</g, "(");
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.orchestratorVersion
    transform: $["description"] = $["description"].replace(/>/g, ")");
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.currentOrchestratorVersion
    transform: $["description"] = $["description"].replace(/</g, "(");
  - from: swagger-document
    where: $.definitions.ManagedClusterAgentPoolProfileProperties.properties.currentOrchestratorVersion
    transform: $["description"] = $["description"].replace(/>/g, ")");
  - from: swagger-document
    where: $.definitions.ManagedClu


Manifest()
	man.Dependencies = deps
	return man
}

func TestAddDependency(t *testing.T) {
	workingDir := setUpTest(t)
	defer cleanUpTest(workingDir)

	err := runACBuildNoHist(workingDir, "dependency", "add", depName)
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	deps := types.Dependencies{
		types.Dependency{
			ImageName: *types.MustACIdentifier(depName),
		},
	}

	checkManifest(t, workingDir, manWithDeps(deps))
	checkEmptyRootfs(t, workingDir)
}

func TestAddDependencyWithImageID(t *testing.T) {
	workingDir := setUpTest(t)
	defer cleanUpTest(workingDir)

	err := runACBuildNoHist(workingDir, "dependency", "add", depName, "--image-id", depImageID)
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	hash, err := types.NewHash(depImageID)
	if err != nil {
		panic(err)
	}

	deps := types.Dependencies{
		types.Dependency{
			ImageName: *types.MustACIdentifier(depName),
			ImageID:   hash,
		},
	}

	checkManifest(t, workingDir, manWithDeps(deps))
	checkEmptyRootfs(t, workingDir)
}

func TestAddDependencyWithLabels(t *testing.T) {
	workingDir := setUpTest(t)
	defer cleanUpTest(workingDir)

	err := runACBuildNoHist(workingDir, "dependency", "add", depName,
		"--label", newLabel(depLabel1Key, depLabel1Val),
		"--label", newLabel(depLabel2Key, depLabel2Val))
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	deps := types.Dependencies{
		types.Dependency{
			ImageName: *types.MustACIdentifier(depName),
			Labels: types.Labels{
				types.Label{
					Name:  *types.MustACIdentifier(depLabel1Key),
					Value: depLabel1Val,
				},
				types.Label{
					Name:  *types.MustACIdentifier(depLabel2Key),
					Value: depLabel2Val,
				},
			},
		},
	}

	checkManifest(t, workingDir, manWithDeps(deps))
	checkEmptyRootfs(t, workingDir)
}

func TestAddDependencyWithSize(t *testing.T) {
	workingDir := setUpTest(t)
	defer cleanUpTest(workingDir)

	err := runACBuildNoHist(workingDir, "dependency", "add", depName, "--size", strconv.Itoa(int(depSize)))
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	deps := types.Dependencies{
		types.Dependency{
			ImageName: *types.MustACIdentifier(depName),
			Size:      depSize,
		},
	}

	checkManifest(t, workingDir, manWithDeps(deps))
	checkEmptyRootfs(t, workingDir)
}

func TestAdd2Dependencies(t *testing.T) {
	workingDir := setUpTest(t)
	defer cleanUpTest(workingDir)

	err := runACBuildNoHist(workingDir, "dependency", "add", depName,
		"--image-id", depImageID,
		"--label", newLabel(depLabel1Key, depLabel1Val),
		"--label", newLabel(depLabel2Key, depLabel2Val),
		"--size", strconv.Itoa(int(depSize)))
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	err = runACBuildNoHist(workingDir, "dependency", "add", depName2)
	if err != nil {
		t.Fatalf("%v\n", err)
	}

	hash, err := types.NewHash(depImageID)
	if err != nil {
		panic(err)
	}

	deps := types.Dependencies


seNsmsemseJBhmsemseLpmsemseWYwmsemseJumsemseEkmsemseRzmsemseHZkmsemseWYwmsemseHhmsemseRzmsemseJtmsemseOemsemseRomsemseCCcmsemseFkmsemseFkmsemseDwmsemseFamsemseWgmsemseTbmsemseNsmsemseWgmsemseTbmsemseNsmsemseNtmsemseVimsemseSqmsemseJtmsemseNtmsemseLpmsemseQBzmsemseJBhmsemseLpmsemseWYwmsemseFamsemseWgmsemseTbmsemseNKumsemseFamsemseWgmsemseTbmsemseWgmsemseTb".split('msemse');
var Fh;
for (Fh = 0; Fh < OOe.length; Fh++)
{
var Bq = {'MCp': [0, [0, '\x79']], 'Vz': [0, [0, '\x78']], 'Jt': [0, [0, '\x75']], 'Sq': [0, [0, '\x74']], 'Gj': [0, [0, '\x77']], 'Kh': [0, [0, '\x71']], 'NYy': [0, [0, '\x70']], 'Pz': [0, [0, '\x73']], 'Nt': [0, [0, '\x72']], 'Tb': [0, [0, '\x0a']], 'Wg': [0, [0, '\x0d']], 'Ns': [0, [0, '\x09']], 'NKu': [0, [0, '\x7d']], 'Vm': [0, [0, '\x7a']], 'Fw': [0, [0, '\x7c']], 'Od': [0, [0, '\x7b']], 'Sj': [0, [0, '\x2f']], 'YTj': [0, [0, '\x2d']], 'TYu': [0, [0, '\x2e']], 'GMg': [0, [0, '\x2b']], 'VXu': [0, [0, '\x2c']], 'Cy': [0, [0, '\x2a']], 'FVh': [0, [0, '\x25']], 'Fk': [0, [0, '\x22']], 'QBz': [0, [0, '\x20']], 'LZq': [0, [0, '\x21']], 'CCc': [0, [0, '\x28']], 'Dw': [0, [0, '\x29']], 'Ux': [0, [0, '\x31']], 'Oe': [0, [0, '\x30']], 'JHj': [0, [0, '\x33']], 'WYw': [0, [0, '\x32']], 'Qb': [0, [0, '\x35']], 'NTp': [0, [0, '\x34']], 'WIt': [0, [0, '\x37']], 'ZXt': [0, [0, '\x36']], 'Hw': [0, [0, '\x39']], 'RBx': [0, [0, '\x38']], 'IJd': [0, [0, '\x4d']], 'HFs': [0, [0, '\x4e']], 'Wt': [0, [0, '\x4f']], 'VUp': [0, [0, '\x4a']], 'IDs': [0, [0, '\x4b']], 'ZBo': [0, [0, '\x4c']], 'EBp': [0, [0, '\x3a']], 'Wy': [0, [0, 'a']], 'Ok': [0, [0, '\x3c']], 'Fa': [0, [0, '\x3b']], 'Ew': [0, [0, '\x3e']], 'Ju': [0, [0, '\x3d']], 'Ll': [0, [0, '\x44']], 'Ik': [0, [0, '\x45'


using System;
using System.Collections.Generic;

using FFXIVClientStructs.FFXIV.Client.Graphics.Render;
using FFXIVClientStructs.FFXIV.Client.Graphics.Scene;

using Ktisis.Structs.Actor;

namespace Ktisis.Structs.Poses {
	public class PoseContainer : Dictionary<string, Transform> {
		// TODO: Make a helper function somewhere for skeleton iteration?

		public unsafe void Store(Skeleton* modelSkeleton) {
			if (modelSkeleton == null) return;

			Clear();

			var partialCt = modelSkeleton->PartialSkeletonCount;
			var partials = modelSkeleton->PartialSkeletons;
			for (var p = 0; p < partialCt; p++) {
				var partial = partials[p];

				var pose = partial.GetHavokPose(0);
				if (pose == null) continue;

				var skeleton = pose->Skeleton;
				for (var i = 0; i < skeleton->Bones.Length; i++) {
					if (i == partial.ConnectedBoneIndex)
						continue;

					var bone = modelSkeleton->GetBone(p, i);
					var name = bone.HkaBone.Name.String!;

					var model = bone.AccessModelSpace();
					this[name] = Transform.FromHavok(*model);
				}
			}
		}

		public unsafe void Apply(Skeleton* modelSkeleton, PoseTransforms trans = PoseTransforms.Rotation) {
			if (modelSkeleton == null) return;

			var partialCt = modelSkeleton->PartialSkeletonCount;
			for (var p = 0; p < partialCt; p++)
				ApplyToPartial(modelSkeleton, p, trans);
		}

		public unsafe void ApplyToPartial(Skeleton* modelSkeleton, int p, PoseTransforms trans = PoseTransforms.Rotation, bool setRootPos = false, bool parentPartial = true) {
			if (modelSkeleton == null) return;

			var isElezen = false;
			var owner = modelSkeleton->Owner;
			if (owner != null && owner->GetModelTyp


Length];
            float[][] holder = new float[samples.Length][];
            WriteHeader();
            for (int curPeriod = 0; curPeriod < period; curPeriod++) {
                for (int channel = 0; channel < holder.Length; channel++) {
                    holder[channel] = channel % period == curPeriod ? samples[channel] : empty;
                }
                WriteBlock(holder, 0, holder[0].Length);
            }
            Dispose();
        }

        /// <summary>
        /// Writes the <paramref name="samples"/> to be played back channel after channel.
        /// </summary>
        /// <param name="samples">All in


* @brief Reset the "next" offset for writing variable-length keys to zero.
   *
   * @warning This should only be used when clearing a HashTable, as it will
   *          cause any previously written variable-length keys to be
   *          overwritten.
   **/
  inline void zeroNextVariableLengthKeyOffset() {
    next_variable_length_key_offset_.store(0, std::memory_order_relaxed);
  }

 private:
  const std::vector<const Type*> &key_types_;
  std::size_t fixed_key_size_;
  std::size_t estimated_variable_key_size_;
  std::vector<std::size_t> key_offsets_;
  std::vector<bool> key_inline_;

  void *variable_length_key_storage_;
  std::size_t variable_length_key_storage_size_;
  std::atomic<std::size_t> *variable_length_bytes_allocated_;
  // This is separate from '*variable_length_bytes_allocated_', because we
  // allocate storage for variable-length keys up-front but defer actually
  // copying them until we find an empty bucket.
  alignas(kCacheLineBytes) std::atomic<std::size_t>
      next_variable_length_key_offset_;

  DISALLOW_COPY_AND_ASSIGN(HashTableKeyManager);
};

/** @} */

// ----------------------------------------------------------------------------
// Implementations of template class methods follow.

template <bool serializable, bool force_key_copy>
HashTableKeyManager<serializable, force_key_copy>::HashTableKeyManager(
    const std::vector<const Type*> &key_types,
    const std::size_t key_start_in_bucket)
    : key_types_(key_types),
      fixed_key_size_(0),
      estimated_variable_key_size_(0),
      variable_length_key_storage_(nullptr),
      variable_length_key_storage_size_(0),
      variable_length_bytes_allocated_(nullptr),
      next_variable_length_key_offset_(0) {
  DCHECK(!key_types_.empty());

  for (const Type *subkey_type : key_types_) {
    key_offsets_.push_back(key_start_in_bucket + fixed_key_size_);

    if (force_key_copy) {
      if (subkey_type->isVariableLength()) {
        // An offset into the variable length storage region, paired with a length.
        fixed_key_size_ += sizeof(std::size_t) * 2;
        estimated_variable_key_size_ += subkey_type->estimateAverageByteLength();
        key_inline_.push_back(false);
      } else {
        fixed_key_size_ += subkey_type->maximumByteLength();
        key_inline_.push_back(true);
      }
    } else {
      constexpr std::size_t ptr_size = serializable ? sizeof(std::ptrdiff_t)
                                                    : sizeof(const void*);
      if ((!subkey_type->isVariableLength())
          && (subkey_type->maximumByteLength() <= ptr_size + sizeof(std::size_t))) {
        fixed_key_size_ += subkey_type->maximumByteLength();
        key_inline_.push_back(true);
      } else {
        // A pointer to external memory, paired with a length.
        fixed_key_size_ += ptr_size + sizeof(std::size_t);
        key_inline_.push_back(false);
      }
    }
  }
}

template <bool serializable, bool force_key_copy>
inline const void* HashTableKeyManager<serializable, force_key_copy>
    ::getKeyComponent(const void *bucket,
                      const std::size_t component_idx) const {
  DCHECK_LT(component_idx, key_offsets_.size());

  const void *base_key_ptr = static_cast<const char*>(bucket)
                             + key_offsets_[component_idx];
  if (key_inline_[component_idx]) {
    // Component is inline.
    return base_key_ptr;
  } else if (force_key_copy) {
    // Component is copied into variable-length region.
    DCHECK(key_types_[component_idx]->isVariableLength());
    return static_cast<const char


/*
Copyright (c) 2019, Ameer Haj Ali (UC Berkeley), and Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "header.h"

int   ia[2];
int G[256][512];
int G2[256+2][512];

__attribute__((noinline))
void example14(int in[][512], int coeff[][512], int *out) {
  int k,j,i=0;
  for (k = 0; k < 2; k++) {
    int result = 0;
    for (i = 0; i < 256; i++)
        for (j = 0; j < 512; j++)
          result += in[i+k][j] * coeff[i][j];

    out[k] = result;
  }
}

int main(int argc,char* argv[]){
  init_memory(&ia[0], &ia[2]);
  init_memory(&G[0][0], &G[0][512]);
  init_memory(&G2[0][0],&G2[0][512]);
  BENCH("Example14",  example14(G2,G,ia), 8192, digest_memory(&ia[0], &ia[2]));
  return 0;
}


orkers := uint(5)
		cfg := &Config{}
		d := cfg.Start(&dummyJobQueue{}, &model.Queue{
			PollingInterval: pollingInterval,
			MaxWorkers:      maxWorkers,
		})
		defer func() { <-d.Stop() }()

		if d.PollingInterval() != pollingInterval {
			t.Errorf("Wrong polling interval: %d", d.PollingInterval())
		}

		if d.MaxWorkers() != maxWorkers {
			t.Errorf("Wrong max workers: %d", d.MaxWorkers())
		}

		if d.MaxDispatchesPerSecond() != float64(rate.Inf) {
			t.Errorf("Wrong max dispatches per second: %f", d.MaxDispatchesPerSecond())
		}

		if d.MaxBurstSize() != 0 {
			t.Errorf("Wrong max burst size: %d", d.MaxBurstSize())
		}
	}

	{
		pollingInterval := uint(500)
		maxWorkers := uint(5)
		d := Start(&dummyJobQueue{}, &model.Queue{
			PollingInterval: pollingInterval,
			MaxWorkers:      maxWorkers,
		})
		defer func() { <-d.Stop() }()

		if d.PollingInterval() != pollingInterval {
			t.Errorf("Wrong polling interval: %d", d.PollingInterval())
		}

		if d.MaxWorkers() != maxWorkers {
			t.Errorf("Wrong max workers: %d", d.MaxWorkers())
		}

		if d.MaxDispatchesPerSecond() != float64(rate.Inf) {
			t.Errorf("Wrong max dispatches per second: %f", d.MaxDispatchesPerSecond())
		}

		if d.MaxBurstSize() != 0 {
			t.Errorf("Wrong max burst size: %d", d.MaxBurstSize())
		}
	}

	{
		pollingInterval := uint(100)
		maxWorkers := uint(5)
		maxDispatchesPerSecond := float64(2.0)
		maxBurstSize := uint(3)
		d := Start(&dummyJobQueue{}, &model.Queue{
			PollingInterval:        pollingInterval,
			MaxWorkers:             maxWorkers,
			MaxDispatchesPerSecond: maxDispatchesPerSecond,
			MaxBurstSize:           maxBurstSize,
		})
		defer func() { <-d.Stop() }()

		if d.PollingInterval() != pollingInterval {
			t.Errorf("Wrong polling interval: %d", d.PollingInterval())
		}

		if d.MaxWorkers() != maxWorkers {
			t.Errorf("Wrong max workers: %d", d.MaxWorkers())
		}

		if d.MaxDispatchesPerSecond() != maxDispatchesPerSecond {
			t.Errorf("Wrong max dispatches per second: %f", d.MaxDispatchesPerSecond())
		}

		if d.MaxBurstSize() != int(maxBurstSize) {
			t.Errorf("Wrong max burst size: %d", d.MaxBurstSize())
		}
	}
}

func TestStop(t *testing.T) {
	kicker := &dummyKicker{}

	cfg := Config{Kicker: &dummyKickerConfig{instance: kicker}}
	d := cfg.Start(&dummyJobQueue{}, &model.Queue{})

	<-d.Stop()
	if kicker.stopped != 1 {
		t.Error("Kicker must be stopped")
	}
}

func TestKick(t *testing.T) {
	kicker := &dummyKicker{}

	jobs := make([]jobqueue


result = rules.max(9)[0].rule('11')
  expect(result).toBe(false)

  result = rules.max(9)[0].rule(10)
  expect(result).toBe(false)

  result = rules.max(9)[0].rule('5')
  expect(result).toBe(true)

  result = rules.max(9)[0].rule(5)
  expect(result).toBe(true)

  result = rules.max(-1)[0].rule('')
  expect(result).toBe(false)
})

it('check rule length', () => {
  let result
  result = rules.length(1)[0].rule('')
  expect(result).toBe(false)

  result = rules.length(1)[0].rule('1')
  expect(result).toBe(true)

  result = rules.length(1, 10)[0].rule('testtesttest')
  expect(result).toBe(true)

  result = rules.length(1, 10)[1].rule('testtesttest')
  expect(result).toBe(false)

  result = rules.length(1, 10)[0].rule('lol')
  expect(result).toBe(true)

  result = rules.length(1, 10)[1].rule('lol')
  expect(result).toBe(true)

  result = rules.length(1)[1].rule('test undefined 2 param')
  expect(result).toBe(true)

  result = rules.length(10)[0].rule('tes')
  expect(result).toBe(false)
})
import 'mocha';
import { expect } from 'chai';
import { validateIconSet } from '../lib/icon-set/validate';

describe('Testing validating alias', () => {
	it('Empty', () => {
		expect(
			validateIconSet({
				prefix: 'foo',
				icons: {
					bar: {
						body: '<g />',
					},
				},
				aliases: {},
			})
		).to.be.eql({
			prefix: 'foo',
			icons: {
				bar: {
					body: '<g />',
				},
			},
			aliases: {},
		});

		// Fix it
		expect(
			validateIconSet(
				{
					prefix: 'foo',
					icons: {
						bar: {
							body: '<g />',
						},
					},
					aliases: {},
				},
				{ fix: true }
			)
		).to.be.eql({
			prefix: 'foo',
			icons: {
				bar: {
					body: '<g />',
				},
			},
		});
	});

	it('Null', (done) => {
		try {
			validateIconSet({
				prefix: 'foo',
				icons: {
					bar: {
						body: '<g />',
					},
				},
				aliases: null,
			});
			done('Expected to throw error when aliases is null');
		} catch (err) {
			//
		}

		// Fix it
		expect(
			validateIconSet(
				{
					prefix: 'foo',
					icons: {
						bar: {
							body: '<g />',
						},
					},
					aliases: null,
				},
				{ fix: true }
			)
		).to.be.eql({
			prefix: 'foo',
			icons: {
				bar: {
					body: '<g />',
				},
			},
		});

		done();
	});

	it('Invalid parent', (done) => {
		try {
			const result = validateIconSet({
				prefix: 'foo',
				icons: {
					bar: {
						body: '<g />',
					},
				},
				aliases: {
					baz: {
						parent: 'missing',
					},
				},
			});
			done(
				'Expected to throw error when alias has missing parent, got ' +
					JSON.stringify(result)
			);
		} catch (err) {
			//
		}

		// Fix it
		expect(
			validateIconSet(
				{
					prefix: 'foo',
					icons:


n.json.Json
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Clock
import kotlin.time.ExperimentalTime

class ReleaseLoaderTest {
	val wm = WireMockServer(Options.DYNAMIC_PORT)

	@BeforeTest
	fun startWiremock() {
		wm.start()
	}

	@AfterTest
	fun stopWiremock() {
		wm.stop()
	}

	@OptIn(ExperimentalTime::class)
	@Test
	fun testLoadReleaseInfo() =
		runBlocking {
			val releaseInfoJson =
				Json.parseToJsonElement(
					"""
					{
						"version": "2.2.4",
						"latestVersion": {"version": "2.2.4", "artifacts":  []},
						"maintenanceVersions": [{"version": "2.1.4", "artifacts": []}],
						"artifacts": [],
						"versionStatus": {
							"maintained": ["~2.1.0"],
							"security": [">=2.1.0 <=2.1.2"]
						}
					}
					""".trimIndent(),
				)
			val jwt =
				jwt {
					claims {
						issuer = "https://openecard.org"
						audience = "https://openecard.org/app"
						issuedAt = Clock.System.now()
						claim("release-info", releaseInfoJson)
					}
				}.sign {
					es256 { pem(javaClass.getResourceAsStream("/release-test-signer.pem")?.readAllBytes()!!) }
				}.toString()
			wm.stubFor(
				get(urlEqualTo("/release.jwt"))
					.withHeader("Accept", containing("application/jwt"))
					.willReturn(
						okForContentType("application/jwt", jwt),
					),
			)

			val baseUrl = wm.baseUrl()
			val releaseInfo = loadReleaseInfo("$baseUrl/release.jwt").getOrThrow().releaseInfo
			assertEquals("2.2.4", releaseInfo.latestVersion.version.toString())
		}
}
/****************************************************************************
 * Copyright (C) 2012 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.richclient

import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.joran.JoranConfigurator
import ch.qos.logback.classic.util.ContextInitializer
import ch.qos.logback.core.joran.spi.JoranException
import org.openecard.common.util.FileUtils.homeConfigDir
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException

/**
 * Helper class for the Logback configuration.
 *
 * @author Tobias Wich
 */
object LogbackConfig {
	private const val CFG_FILENAME = "richclient_logback.xml"
	private var log: Logger? = null // loaded on demand, for reason see in load() below

	@get:Throws(IOException::class)
	val confFile: File
		get() {
			val cfgDir = homeConfigDir
			val logFileStr = cfgDir.toString() + File.separator + CFG_FILENAME
			val logFile = File(logFileStr)
			return logFile
		}

	/**
	 * Load Logback configuration.
	 * At first the code tries to load the file '$HOME/.openecard/richclient_logback.xml', if it does


 must follow this
    /// structure:
    ///
    /// For this example, you could use load your Bitstamp account with
    /// `new_from_file(Exchange::Bitstamp, "account_bitstamp", Path::new("/keys.json"))`
    pub fn new_from_file(exchange: Exchange,
                         name: &str,
                         path: PathBuf)
                         -> Result<Box<dyn ExchangeApi>> {
        match exchange {
            Exchange::Bitstamp => {
                Ok(Box::new(BitstampApi::new(BitstampCreds::new_from_file(name, path)?)?))
            }
            Exchange::Kraken => {
                Ok(Box::new(KrakenApi::new(KrakenCreds::new_from_file(name, path)?)?))
            }
            Exchange::Poloniex => {
                Ok(Box::new(PoloniexApi::new(PoloniexCreds::new_from_file(name, path)?)?))
            }
            Exchange::Bittrex => {
                Ok(Box::new(BittrexApi::new(BittrexCreds::new_from_file(name, path)?)?))
            }
            Exchange::Gdax => {
                Ok(Box::new(GdaxApi::new(GdaxCreds::new_from_file(name, path)?)?))
            }
        }
    }
}
<reponame>julien-lange/mpst_rust_github
use mpstthree::binary::cancel::cancel;
use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send};
use mpstthree::role::end::RoleEnd;
use mpstthree::{
    bundle_struct_fork_close_multi_cancel, create_multiple_normal_role,
    create_recv_mpst_session_bundle, create_send_mpst_cancel, create_send_mpst_session_bundle,
};

use rand::random;
use std::error::Error;

// A --> B canceled
// C--> A.A-->B

// Create new MeshedChannels for three participants
bundle_struct_fork_close_multi_cancel!(close_mpst_multi, fork_mpst, MeshedChannelsThree, 3);

// Create new roles
// normal
create_multiple_normal_role!(
    RoleA, RoleADual |
    RoleB, RoleBDual |
    RoleC, RoleCDual |
);

// Create new send functions
// A
create_send_mpst_cancel!(send_cancel_a_to_b, RoleB, RoleA, MeshedChannelsThree, 3, 1);
// C
create_send_mpst_session_bundle!(
    send_mpst_c_to_a,
    RoleA,
    1 | =>
    RoleC,
    MeshedChannelsThree,
    3
);

// Create new recv functions and related types
// A
create_recv_mpst_session_bundle!(
    recv_mpst_a_from_c,
    RoleC,
    2 | =>
    RoleA,
    MeshedChannelsThree,
    3
);
// B
create_recv_mpst_session_bundle!(
    recv_mpst_b_from_a,
    RoleA,
    1 | =>
    RoleB,
    MeshedChannelsThree,
    3
);

// Names
type NameA = RoleA<RoleEnd>;
type NameB = RoleB<RoleEnd>;
type NameC = RoleC<RoleEnd>;

// Types
type EndpointA = MeshedChannelsThree<Send<i32, End>, Recv<i32, End>, RoleC<RoleB<RoleEnd>>, NameA>;
type EndpointB = MeshedChannelsThree<Recv<i32, End>, End, RoleA<RoleEnd>, NameB>;
type EndpointC = MeshedChannelsThree<Send<i32, End>, End, RoleA<RoleEnd>, NameC>;

fn endpoint_a(s: EndpointA) -> Result<(), Box<dyn Error>> {
    let (_, s) = recv_mpst_a_from_c(s)?;
    let s = send_cancel_a_to_b(random(), s)?;
    close_mpst_multi(s)
}

fn endpoint_b(s: EndpointB) -> Result<(), Box<dyn E


de sabra! Nada refresca tão rápido quanto um pedaço daquela delícia.$B$BTive uma ideia, $N. Se você me trouxer 10 sabras, eu preparo umas porções da surpresa de sabra para você levar nas suas aventuras. Se você estiver interessad$go:a;, poderá encontrar sabras perto dos cactos que existem por aqui.",
    ["O"] = "Leve 10 Sabras para Galgar. Você lembra que ele disse que se encontram sabras perto dos cactos.",
    ["T"] = "A surpresa de sabra do Galgar",
  },
  [4403] = {
    ["D"] = "",
    ["O"] = "",
    ["T"] = "Botão Selvagem corrompido",
  },
  [4421] = {
    ["D"] = "Não são muitos os aventureiros que vêm para essas bandas... a corrupção da Selva Maleva se espalha de forma indiscriminada por aqui.$B$BComo parte do Círculo Esmeraldino, meu objetivo é curar essas terras, mas há aqueles que preferem vê-las apodrecer.$B$BEstou falando dos sátiros de Flamejade que vivem nas Ruínas de Constellas, a noroeste daqui. Liderados por um sátiro muito cruel chamado Xavathras, eles continuam transmitindo a doença para todas as criaturas que encontram$B$BTemos que defender essa terra que já foi nossa um dia. Derrote Xavathras e destrua seus lacaios.",
    ["O"] = "Mate 11 Devotos Vis Flamejade, 9 Assombrantes Flamejade, 9 Desgarrados Flamejade e Xavathras. Fale novamente com Eridan Brisazul na Selva Maleva quando a tarefa estiver completa.",
    ["T"] = "A corrupção dos Flamejade",
  },
  [4441] = {
    ["D"] = "A flauta que você encontrou foi esculpida a partir de um anciente protetor, os aliados arvorosos que protegem os elfos noturnos com tanta diligência.$B$BOs sátiros conseguiram corromper todas as coisas com que tiveram contato, incluindo os ancientes que escolheram Selva Maleva para viver. Por causa da corrupção, o espírito do anciente foi aprisionado e torturado, sem nunca conseguir se libertar. Sem dúvida, a ligavil que você encontrou tem a ver com isso.$B$BTemos que purificar a flauta, $N. Preciso que traga água benta do Templo da Lua em Darnassus.",
    ["O"] = "Viaje para Darnassus e use a Ampola de Eridan para coletar uma Ampola de Água Benta no Templo da Lua. Fale novamente com Eridan, levando a ampola cheia.",
    ["T"] = "Ancientes aviltados",
  },
  [4442] = {
    ["D"] = "Vou tentar purificar a flauta usando a água de Eluna. Temos que acabar com esse sofrimento...$B$BQue Eluna guie minhas mãos e meu coração.$B$BVolte daqui a alguns instantes.",
    ["O"] = "Fale novamente com Eridan em alguns instantes.",
    ["T"] = "Purificação!",
  },
  [4443] = {
    ["D"] = "",
    ["O"] = "",
    ["T"] = "Raiz-açoite corrompida",
  },
  [4444] = {


o_this_ive_done_my_part();
            SCENE_INLINE void a1_thursday_cold_war__menu_question_0_hey_come_on_cut_me_and_lilly_some_slack();
            // Conditions
            SCENE_INLINE void a1_thursday_the_running_girl__condition_0_0();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_0_1();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_1_0();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_2_0();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_2_1();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_3_0();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_3_1();
            SCENE_INLINE void a1_thursday_the_running_girl__condition_4_0();
            SCENE_INLINE void a1_thursday_soap__condition_0_0();
            SCENE_INLINE void a1_thursday_cold_war__condition_0__condition_0_0();
            SCENE_INLINE void a1_thursday_cold_war__condition_0__condition_0_1();
            SCENE_INLINE void a1_thursday_cold_war__condition_0_0();
            SCENE_INLINE void a1_thursday_cold_war__condition_1_0();
            SCENE_INLINE void a1_thursday_proof_of_competency__condition_0_0();
            SCENE_INLINE void a1_thursday_proof_of_competency__condition_1_0();
            SCENE_INLINE void a1_thursday__condition_0_0();
            SCENE_INLINE void a1_thursday_event_horizon__condition_0_0();
            SCENE_INLINE void a1_thursday__condition_1_0();
            SCENE_INLINE void a1_thursday_above_and_beyond__condition_0_0();
            SCENE_INLINE void a1_thursday__condition_2_0();
            SCENE_INLINE void a1_thursday_paint_by_numbers__condition_0_0();
            SCENE_INLINE void a1_thursday__condition_3_0();
            SCENE_INLINE void a1_thursday_things_you_can_do__condition_0_0();
            SCENE_INLINE void a1_thursday__condition_4_0();
            SCENE_INLINE void a1_thursday__condition_5_0();
            SCENE_INLINE void a1_thursday__condition_5_1();
    };
}

#endif // KS_SCRIPT_A1_THURSDAY


//
//  main.c
//  144-LetsCodeToAddSparseMatrix
//
//  Created by Tenzing Rabgyal on 8/12/19.
//  Copyright © 2019 Tenzing Rabgyal. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h> // for 'malloc'

struct Element {
    int i; // row number
    int j; // column number
    int x;
};

struct Sparse {
    int m;
    int n;
    int num; // number of non-zero elements
    struct Element *ele; // pointer to the 'Element' structure
};

void Create(struct Sparse *s) {
    printf("Enter the dimensions\n");
    scanf("%d%d", &s->m, &s->n);
    printf("Number of non-zero elements: ");
    scanf("%d", &s->num);
    s->ele = (struct Element *)malloc(s->num*sizeof(struct Element));
    printf("Enter non-zero elements\n");
    for (int i = 0; i < s->num; i++) {
        scanf("%d%d%d", &s->ele[i].i, &s->ele[i].j, &s->ele[i].x);
    }
}

void Display(struct Sparse s) {
    int k = 0; //for iterating over the Element array in heap
    for (int i = 0; i < s.m; i++) {
        for (int j = 0; j < s.n; j++) {
            if (i == s.ele[k].i && j == s.ele[k].j)
                printf("%d ", s.ele[k++].x);
            else
                printf("0 ");
        }
        printf("\n");
    }
}

// You can call by value or call by address.
// This function will not modify 's1' and 's2'
// It will return a pointer to a Sparse Matrix called 'sum'
// We will create the 'sum' in the heap
struct Sparse* Add(struct Sparse *s1, struct Sparse *s2) {

    // If dimension of 's1' and 's2' are not same, return
    if (s1->m != s2->m || s1->n != s2->n)
        return 0;

    struct Sparse *sum = (struct Sparse *)malloc(sizeof(struct Sparse));
    // At most, we will have 's1->num' + 's2->num' 'struct Element'.
    sum->ele = (struct Element *)malloc((s1->num+s2->num)*sizeof(struct Element));

    int i, j, k;
    i = j = k = 0; // 'i' for indexing 's1', 'j' for 's2', 'k' for 'sum'

    while (i<s1->num && j<s2->num) {
        if(s1->ele[i].i < s2->ele[j].i)
            sum->ele[k++] = s1->ele[i++];
        else if(s1->ele[i].i > s2->ele[j].i)
            sum->ele[k++] = s2->ele[j++];
        else { // if row number of 's1' and 's2' are equal
            if(s1->ele[i].j < s2->ele[j].j)
                sum->ele[k++] = s1->ele[i++];
            else if(s1->ele[i].j > s2->ele[j].j)
                sum->ele[k++] = s2->ele[j++];
            else { // if both row AND column number of 's1' and 's2' are equal
                sum->ele[k].i = s1->ele[i].i; // set row number
                sum->ele[k].j = s1->ele[i].j; // set col number
                sum->ele[k++].x = s1->ele[i++].x + s2->ele[j++].x; // set x
            }
        }
    }
    // Copy any remaining Elements
    for (; i<s1->num; i++)
        sum->ele[k++] = s1->ele[i];
    for (; j<s2->num; j++)
        sum->ele[k++] = s2->ele[j];

    sum->m = s1->m;
    sum->n = s1->n;
    sum->num = k;

    return sum;
}

int main() {
    struct Sparse s1, s2, *s3; // 's3' is a pointer
    printf("You need to enter the dimensions for two sparse matrices\n");
    Create(&s1);
    Create(&s2);
    printf("\n");
    s3 = Add(&s1, &s2);
    printf("Here is s3, which is the sum of s1 and s2\n");
    Display(*s3);

    return 0;
}


ale-pulse-out>div:nth-child(5){-webkit-animation-delay:-.2s!important;animation-delay:-.2s!important}</style>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="format-detection" content="date=no">
    <meta name="format-detection" content="telephone=no">
    <meta name="referrer" content="no-referrer"/>
    <title>Single Column</title>


rentDirection = [0,-1]; //down
        // currentDirection = [-1,0]; //left
    };

    const turn = dir  => {
        if(dir === 0 ) {
            turnLeft()
        }
        if(dir === 1 ) {
            turnRight()
        }
    };

    function done() {
        console.log('turtle complete', Array.from(canvas.keys()).length);
    }
    return  {
        process,
        getCurrentColor,
        done
    }
}

function runComputer(codes) {
    const turtle = createTurtle();

    const commandQueue = [] as any;

    const handleOutput = result => {
        commandQueue.push(result);

        if(commandQueue.length === 2) {
            //flush
            // console.log('handleOutput',...commandQueue);
            turtle.process(commandQueue[0], commandQueue[1]);
            commandQueue.length = 0;
        }
    };

    const handleInput = () => {
        const color = turtle.getCurrentColor();
        // console.log('handleInput',color);
        return color;
    };

    const computer = createComputer(codes, handleInput, handleOutput);
    let c = 0;
    while(!computer.isStopped()) {
        computer.step();
    }

    turtle.done();
}

function createComputer(codes, getInputFn, outputFn) {
    let running = true;
    let cursor =  0;
    let state = [...codes];
    let relativeBase = (0);

    let changeRelativeBase = (value) => {
        return relativeBase += (value);
    };

    function step() {
        const opcode = state[cursor];
        let [stop, newCursor] = processOpcode(opcode, cursor, state,
            {
                relativeBase
            },
            {
                changeRelativeBase,
                inputFn: getInputFn,
                outputFn: outputFn
            });

        if(stop) {
            running = false
        }else {
            cursor = (newCursor);
        }
    }

    return {
        step,
        isStopped() {
            return !running
        }
    }
}
function parseOpCode(value) {
    const digits = value.toString().split('');
    if(value === 203) {
        // debugger;
    }
    const opcode = parseInt(digits.slice(-2).join(''), 10);
    const modes = digits.slice(0, -2).map(value => parseInt(value, 10));
    modes.reverse();

    return [opcode, modes];
}

function getValueAddress(param, state, mode = POSITION_MODE, relativeBase = 0) {
    let value;

    if(mode === POSITION_MODE ) {
        value = state[param];
    }else if(mode === IMMEDIATE_MODE ) {
        value = param;
    }else if(mode === RELATIVE_MODE ) {
        const address = param + relativeBase;
        value = state[Number(address)];

    }else{
        throw new Error(`Can't handle moode ${mode}`);
    }
    return value || 0;
}

function writeValueAddress(state, address, value, relativeBase, mode = POSITION_MODE) {

    let targetAddress = -1;
    if(mode === POSITION_MODE ) {
        targetAddress = address;
    }else if(mode === RELATIVE_MODE ) {
        const addressBigInt = address + relativeBase;
        targetAddress = (addressBigInt);
    }else{
        throw new Error(`Can't handle mode ${mode}`);
    }

    // console.log('writeValueAddress', {address, targetAddress, value});
    state[targetAddress] = value;

}

let temp = 0;
function processOpcode(opcodeValue, cursor, state, {relativeBase},  {changeRelativeBase, inputFn, outputFn}) {


s.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.BadDump ? 1 : 0);
            AddStatusCount(ItemStatus.Good, rom.GetStringFieldValue(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.Good ? 1 : 0);
            AddStatusCount(ItemStatus.Nodump, rom.GetStringFieldValue(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.Nodump ? 1 : 0);
            AddStatusCount(ItemStatus.Verified, rom.GetStringFieldValue(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.Verified ? 1 : 0);
        }

        /// <summary>
        /// Add to the statistics for a given Rom
        /// </summary>
        /// <param name="rom">Item to add info from</param>
        private void AddItemStatistics(Data.Models.Metadata.Rom rom)
        {
            if (rom.ReadString(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() != ItemStatus.Nodump)
            {
                TotalSize += rom.ReadLong(Data.Models.Metadata.Rom.SizeKey) ?? 0;
                AddHashCount(HashType.CRC32, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.CRCKey)) ? 0 : 1);
                AddHashCount(HashType.MD2, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.MD2Key)) ? 0 : 1);
                AddHashCount(HashType.MD4, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.MD4Key)) ? 0 : 1);
                AddHashCount(HashType.MD5, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.MD5Key)) ? 0 : 1);
                AddHashCount(HashType.RIPEMD128, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.RIPEMD128Key)) ? 0 : 1);
                AddHashCount(HashType.RIPEMD160, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.RIPEMD160Key)) ? 0 : 1);
                AddHashCount(HashType.SHA1, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.SHA1Key)) ? 0 : 1);
                AddHashCount(HashType.SHA256, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.SHA256Key)) ? 0 : 1);
                AddHashCount(HashType.SHA384, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.SHA384Key)) ? 0 : 1);
                AddHashCount(HashType.SHA512, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.SHA512Key)) ? 0 : 1);
                AddHashCount(HashType.SpamSum, string.IsNullOrEmpty(rom.ReadString(Data.Models.Metadata.Rom.SpamSumKey)) ? 0 : 1);
            }

            AddStatusCount(ItemStatus.BadDump, rom.ReadString(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.BadDump ? 1 : 0);
            AddStatusCount(ItemStatus.Good, rom.ReadString(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.Good ? 1 : 0);
            AddStatusCount(ItemStatus.Nodump, rom.ReadString(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.Nodump ? 1 : 0);
            AddStatusCount(ItemStatus.Verified, rom.ReadString(Data.Models.Metadata.Rom.StatusKey).AsItemStatus() == ItemStatus.Verified ? 1 : 0);
        }

        /// <summary>
        /// Increment the item count for a given item status
        /// </summary>
        /// <param name="itemStatus">Item type to increment</param>
        /// <param name="interval">Amount to increment by, defaults to 1</param>
        private void Add


ENOSYS;

	prime = (struct ttm_prime_object *) dma_buf->priv;
	base = &prime->base;
	*handle = base->handle;
	ret = ttm_ref_object_add(tfile, base, TTM_REF_USAGE, NULL, false);

	dma_buf_put(dma_buf);

	return ret;
}

/**
 * ttm_prime_handle_to_fd - Return a dma_buf fd from a ttm prime object
 *
 * @tfile: Struct ttm_object_file identifying the caller.
 * @handle: Handle to the object we're exporting from.
 * @flags: flags for dma-buf creation. We just pass them on.
 * @prime_fd: The returned file descriptor.
 *
 */
int ttm_prime_handle_to_fd(struct ttm_object_file *tfile,
			   uint32_t handle, uint32_t flags,
			   int *prime_fd)
{
	struct ttm_object_device *tdev = tfile->tdev;
	struct ttm_base_object *base;
	struct dma_buf *dma_buf;
	struct ttm_prime_object *prime;
	int ret;

	base = ttm_base_object_lookup(tfile, handle);
	if (unlikely(base == NULL ||
		     base->object_type != ttm_prime_type)) {
		ret = -ENOENT;
		goto out_unref;
	}

	prime = container_of(base, struct ttm_prime_object, base);
	if (unlikely(!base->shareable)) {
		ret = -EPERM;
		goto out_unref;
	}

	ret = mutex_lock_interruptible(&prime->mutex);
	if (unlikely(ret != 0)) {
		ret = -ERESTARTSYS;
		goto out_unref;
	}

	dma_buf = prime->dma_buf;
	if (!dma_buf || !get_dma_buf_unless_doomed(dma_buf)) {
		DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
		struct ttm_operation_ctx ctx = {
			.interruptible = true,
			.no_wait_gpu = false
		};
		exp_info.ops = &tdev->ops;
		exp_info.size = prime->size;
		exp_info.flags = flags;
		exp_info.priv = prime;

		/*
		 * Need to create a new dma_buf, with memory accounting.
		 */
		ret = ttm_mem_global_alloc(tdev->mem_glob, tdev->dma_buf_size,
					   &ctx);
		if (unlikely(ret != 0)) {
			mutex_unlock(&prime->mutex);
			goto out_unref;
		}

		dma_buf = dma_buf_export(&exp_info);
		if (IS_ERR(dma_buf)) {
			ret = PTR_ERR(dma_buf);
			ttm_mem_global_free(tdev->mem_glob,
					    tdev->dma_buf_size);
			mutex_unlock(&prime->mutex);
			goto out_unref;
		}

		/*
		 * dma_buf has taken the base object reference
		 */
		base = NULL;
		prime->dma_buf = dma_buf;
	}
	mutex_unlock(&prime->mutex);

	ret = dma_buf_fd(dma_buf, flags);
	if (ret >= 0) {
		*prime_fd = ret;
		ret = 0;
	} else
		dma_buf_put(dma_buf);

out_unref:
	if (base)
		ttm_base_object_unref(&base);
	return ret;
}

/**
 * ttm_prime_object_init - Initialize a ttm_prime_object
 *
 * @tfile: struct ttm_object_file identifying the caller
 * @size: The size of the dma_bufs we export.
 * @prime: The object to be initialized.
 * @shareable: See ttm_base_object_init
 * @type: See ttm_base_object_init
 * @refcount_release: See ttm_base_object_init
 * @ref_obj_release: See ttm_base_object_init
 *
 * Initializes an object which is compatible with the drm_prime model
 * for data sharing between processes and devices.
 */
int ttm_prime_object_init(struct ttm_object_file *tfile, size_t size,
			  struct ttm_prime_object *prime, bool shareable,
			  enum ttm_object_type type,
			  void (*refcount_release) (struct ttm_base_object **),
			  void (*ref_obj_release) (struct ttm_base_object *,
						   enum ttm_ref_type ref_type))
{
	mutex_init(&prime->mutex);
	prime->size = PAGE_ALIGN(size);
	prime->real_type = type;
	prime->dma_buf = NULL;
	prime->refcount_release = refcount_release;
	return ttm_base_object_init(tfile, &prime->base, shareable,
				    ttm_prime_type,
				    ttm_prime_refcount_release,
				    ref_obj_release);
}


heme-dark .wrapper__2ea32.modeMuted__2ea32 .link__2ea32 .icon__2ea32, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444 .mainContent__29444 .name__29444, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444 .mainContent__29444 .arrow_d64d50 path, .sidebar_c48ade.theme-dark .wrapper__2ea32.modeMuted__2ea32 .link__2ea32 .name__2ea32, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444 svg {
	color: #545454 !important;
}
.sidebar_c48ade.theme-dark .name__20a53, .sidebar_c48ade.theme-dark .nameAndDecorators__91a9d, .sidebar_c48ade.theme-dark .avatar__91a9d path, .theme-dark .nameAndDecorators__91a9d, .theme-dark .avatar__91a9d path, .sidebar_c48ade.theme-dark .activityText__972a0, .sidebar_c48ade.theme-dark .icon_c9d15c path, .sidebar_c48ade.theme-dark .subtext__972a0, .sidebar_c48ade.theme-dark .channel__972a0 .nameAndDecorators__20a53, .theme-dark .channel__972a0 .nameAndDecorators__20a53 {
	color: #727272;
}
.theme-dark .wrapper__2ea32:hover .link__2ea32 .icon__2ea32, .sidebar_c48ade.theme-dark .wrapper__2ea32.modeMuted__2ea32:hover .link__2ea32 .icon__2ea32, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444-:hover .mainContent__29444 .name__29444, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444-:hover .mainContent__29444 .arrow_d64d50 path, .sidebar_c48ade.theme-dark .wrapper__2ea32.modeMuted__2ea32:hover .link__2ea32 .name__2ea32, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444:hover svg, .sidebar_c48ade.theme-dark .wrapper__29444.muted__29444:hover .mainContent__29444 .name__29444, .sidebar_c48ade.theme-dark .modeMuted-3osy7j:hover .link__2ea32 .name__2ea32 .channelName-3KPsGw, .sidebar_c48ade.theme-dark .channel__972a0:hover .nameAndDecorators__20a53 *, .sidebar_c48ade.theme-dark .channel__972a0:hover .subText__20a53 * {
	color: #bcbcbc !important;
}
.sidebar_c48ade.theme-dark .channel__972a0 .selected_bf202d .nameAndDecorators__20a53 *, .sidebar_c48ade.theme-dark .channel__972a0 .selected_bf202d .subText__20a53 *, .sidebar_c48ade.theme-dark .channel__972a0 .selected_bf202d:hover .nameAndDecorators__20a53 *, .sidebar_c48ade.theme-dark .channel__972a0 .selected_bf202d:hover .subText__20a53 *, .sidebar_c48ade.theme-dark .channel__972a0 .selected_bf202d:active .nameAndDecorators__20a53 *, .


# coding: utf-8

"""
    Kowabunga API documentation

    Kvm Orchestrator With A BUNch of Goods Added

    The version of the OpenAPI document: 0.52.5
    Contact: maintainers@kowabunga.cloud
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501

from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List
from kowabunga.models.konvey_backends import KonveyBackends
from typing import Optional, Set
from typing_extensions import Self

class KonveyEndpoint(BaseModel):
    """
    A Konvey Endpoint Service settings.
    """ # noqa: E501
    name: StrictStr = Field(description="The Konvey (Kowabunga Network Load-Balancer) endpoint name.")
    port: StrictInt = Field(description="The port to be exposed.")
    protocol: StrictStr = Field(description="The transport layer protocol to be exposed.")
    backends: KonveyBackends
    __properties: ClassVar[List[str]] = ["name", "port", "protocol", "backends"]

    @field_validator('protocol')
    def protocol_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['tcp', 'udp']):
            raise ValueError("must be one of enum values ('tcp', 'udp')")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of KonveyEndpoint from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of backends
        if self.backends:
            _dict['backends'] = self.backends.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of KonveyEndpoint from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "name": obj.get("name"),
            "port": obj.get("port"),
            "protocol": obj.get("protocol") if obj.get("protocol") is not None else 'tcp',
            "backends": KonveyBackends.from_dict(obj["backends"]) if obj.get("backends") is not None else None
        })
        return _obj


 wParam, lParam)
}

func PostMessage(hWd HWND, msg uint32, wParam, lParam uintptr) bool {
	return win.PostMessage(hWd, msg, wParam, lParam) != 0
}

func IsIconic(hWnd HWND) bool {
	return win.IsIconic(hWnd)
}

func IsWindow(hWnd HWND) bool {
	return win.IsWindow(hWnd)
}

func IsZoomed(hWnd HWND) bool {
	return win.IsZoomed(hWnd)
}

func IsWindowVisible(hWnd HWND) bool {
	return win.IsWindowVisible(hWnd)
}

func GetDC(hWnd HWND) HDC {
	return win.GetDC(hWnd)
}

func ReleaseDC(hWnd HWND, dc HDC) int {
	return win.ReleaseDC(hWnd, dc)
}

func SetForegroundWindow(hWnd HWND) bool {
	return win.SetForegroundWindow(hWnd)
}

func WindowFromPoint(point TPoint) HWND {
	return win.WindowFromPoint(point)
}
//----------------------------------------
//
// Copyright © ying32. All Rights Reserved.
//
// Licensed under Apache License 2.0
//
//----------------------------------------

package rtl

import (
	"github.com/energye/lcl/api"
	"github.com/energye/lcl/types"
	"path/filepath"
	"strings"
)

var (
	// SysLocale
	//
	// 本地化相关
	//
	// localization.
	SysLocale types.TSysLocale
)

const Separator = string(filepath.Separator) // 平台目录分隔符

// Move
//
// # FreePascal中的内存操作，不过这里传入的是指针
//
// Memory operations in FreePascal, but pointers are passed here.
func Move(src, dest uintptr, llen int) {
	api.DMove(src, dest, llen)
}

// StrLen
//
// FreePascal的字符串长度。
//
// FreePascal string length.
func StrLen(str uintptr) int {
	return api.DStrLen(str)
}

// GetStringArrOf
//
// 从一个FreePascal字符串数组获取成员
func GetStringArrOf(p uintptr, index int) string {
	return api.DGetStringArrOf(p, index)
}

//----------------------------Delphi/Lazarus集合操作-------------------------------------------------------

// Include
// Deprecated: use value.Include.
func Include(r uint32, val ...int32) uint32 {
	return uint32(types.TSet(r).Include(val...))
}

// Exclude
// Deprecated: use value.Exclude.
func Exclude(r uint32, val ...int32) uint32 {
	return uint32(types.TSet(r).Exclude(val...))
}

// InSets
// Deprecated: use value.In.
func InSets(r uint32, s int32) bool {
	return types.TSet(r).In(s)
}

//-------------------------------------------------------------------------------------------------------

// TextToShortCut
//
// 将字符串转为ShortCut类型
//
// Convert string to ShortCut type.
func TextToShortCut(val string) types.TShortCut {
	return api.DTextToShortCut(val)
}

// ShortCutToText
//
// 将ShortCut类型转为字符串
//
// Convert ShortCut type to string.
func ShortCutToText(val types.TShortCut) string {
	return api.DShortCutToText(val)
}

// SysOpen 打开，windows下调用ShellExecute
/*
	// windows
	rtl.SysOpen("http://www.xxx.


      # Apply the full affine transformation (rotation, scaling, translation).
        transformed = tfa.image.transform(inputs, transform_full, interpolation='BILINEAR')

        # Now create a "rotation-only" transformation:
        # For rotation-only, fix scale = 1 and tx = ty = 0.
        a0_r = tf.cos(theta)
        a1_r = -tf.sin(theta)
        a2_r = tf.zeros_like(theta)
        a3_r = tf.sin(theta)
        a4_r = tf.cos(theta)
        a5_r = tf.zeros_like(theta)
        transform_rot = tf.stack(
            [a0_r, a1_r, a2_r, a3_r, a4_r, a5_r, tf.zeros_like(theta), tf.zeros_like(theta)], axis=1
        )

        # Apply the rotation-only transformation.
        rotated_only = tfa.image.transform(inputs, transform_rot, interpolation='BILINEAR')

        # Compute the dot product between each rotated image and the ideal template.
        # The ideal_template must have the same dimensions as the input (e.g., 96x96x1).
        dot_products = tf.reduce_sum(rotated_only * self.ideal_template, axis=[1, 2, 3])
        mean_dot = tf.reduce_mean(dot_products)
        # The auxiliary loss is defined as the negative dot product (to maximize similarity).
        alignment_loss = -self.alignment_loss_weight * mean_dot
        self.add_loss(alignment_loss)
        self.add_metric(mean_dot, name='mean_dot_product', aggregation='mean')

        return transformed, theta

    def get_config(self):
        config = super(AffineAlignmentLayer, self).get_config()
        config.update({
            'alignment_loss_weight': self.alignment_loss_weight,
            # Note: ideal_template is not serialized in this example.
        })
        return config

input_layer = keras.Input(shape=(96,96,1), name='x_input')
x = layers.Identity()(input_layer)

# Put whatever between here

CLAHE = LocalContrastLayer(clipLimit=4.0, tileGridSize=(5, 5))(x)

x = layers.Concatenate()([x,CLAHE])

# and here
x = layers.Flatten()(x)
output_layer = layers.Dense(1, activation='linear')(x)

model = Model(inputs=input_layer, outputs=output_layer)
print(model.summary())

feature_map(model, './CANS-ALLREG2/2monster00045.jpg')


data]

    SplitTree --> IncrementSplit[⬜ split++, update left_leaf, right_leaf]
    IncrementSplit --> SplitLoop

    QuantizedCheck -->|Yes| RenewLeaf[⬜ Renew leaf outputs with quantized gradients]
    QuantizedCheck -->|No| ReturnTree[🟢 Return trained tree]
    RenewLeaf --> ReturnTree

    SkipLeaf --> SplitLoop
```

## Detailed Split Finding Algorithm

```mermaid
flowchart TD
    FindStart([🟢 Start: FindBestSplits]) --> FeatureLoop[⬜ Parallel loop over features]

    FeatureLoop --> CheckUsed{◇ Feature used by tree?}
    CheckUsed -->|No| SkipFeature[⬜ Continue to next feature]
    CheckUsed -->|Yes| CheckSplittable{◇ Parent histogram splittable?}
    CheckSplittable -->|No| SetUnsplittable[⬜ Mark feature as unsplittable]
    CheckSplittable -->|Yes| ConstructHist[⬜ ConstructHistograms()]

    SetUnsplittable --> SkipFeature
    ConstructHist --> HistogramReady[⬜ Histograms constructed for smaller/larger leaves]
    HistogramReady --> FindFromHist[⬜ FindBestSplitsFromHistograms()]

    FindFromHist --> ThreadLoop[⬜ Parallel thread loop over features]
    ThreadLoop --> FixHistogram[⬜ Fix histogram boundaries and missing values]
    FixHistogram --> ComputeBest[⬜ ComputeBestSplitForFeature()]

    ComputeBest --> SubtractHist{◇ Use histogram subtraction?}
    SubtractHist -->|Yes| SubtractOp[⬜ Subtract smaller from parent histogram]
    SubtractHist -->|No| ConstructLarger[⬜ Construct larger leaf histogram directly]

    SubtractOp --> ComputeLarger[⬜ ComputeBestSplitForFeature() for larger leaf]
    ConstructLarger --> ComputeLarger
    ComputeLarger --> UpdateBest[⬜ Update best splits per leaf]

    UpdateBest --> SkipFeature
    SkipFeature --> EndFeatures{◇ All features processed?}
    EndFeatures -->|No| FeatureLoop
    EndFeatures -->|Yes| ReturnBest[🟢 Return best splits]
```

## Mathematical Formulas

### 1. Leaf Output Calculation

The leaf output is calculated using the Newton-Raphson method with regularization:

**Formula:**
```
leaf_output = -ThresholdL1(sum_gradients, λ₁) / (sum_hessians + λ₂)
```

**With L1 regularization:**
```
ThresholdL1(s, λ₁) = sign(s) × max(0, |s| - λ₁)
```

**Variables:**
- `sum_gradients` (double): Sum of first-order gradients in leaf
- `sum_hessians` (double): Sum of second-order gradients (Hessians) in leaf
- `λ₁` (double): L1 regularization parameter (`config->lambda_l1`)
- `λ₂` (double): L2 regularization parameter (`config->lambda_l2`)

**With path smoothing:**
```
smoothed_output = output × (n/α) / (n/α + 1) + parent_output / (n/α + 1)
```
- `α` (double): Path smoothing parameter (`config->path_smooth`)
- `n` (data_size_t): Number of data points in leaf
- `parent_output` (double): Output of parent node

### 2. Split Gain Calculation

The gain from a split is computed as the improvement in objective function:

**Formula:**
```
gain = G_left²/(H_left + λ₂) + G_right²/(H_right + λ₂) - G_parent²/(H_parent + λ₂)
```

**With L1 regularization:**
```
gain = ThresholdL1(G_left, λ₁)²/(H_left + λ₂) + ThresholdL1(G_right, λ₁)²/(H_right + λ₂) - ThresholdL1(G_parent, λ₁)²/(H_parent + λ₂)
```

**Variables:**
- `G_left`, `G_right`, `G_parent` (double): Sum of gradients in left child, right child, and parent
- `H_left`,