,
		},
	}

	for _, c := range cases {
		diags := &diag.Diagnostics{}
		result := &TestMapOfFloatFWModel{}

		convert.Flatten(context.Background(), c.input, result, diags)

		if diags.HasError() && !c.expectError {
			t.Errorf("Test: %s \ndiags: %+v", c.name, diags)
		}

		if !reflect.DeepEqual(result, c.expected) && !c.expectError {
			t.Errorf("\nTest: %s\nexpected:\n %+v\ngot:\n %+v", c.name, c.expected, result)
		}

	}
}

func TestFlatten_mapOfFloatPtr(t *testing.T) {
	ctx := context.Background()
	cases := []struct {
		name        string
		input       *TestMapOfFloatPtrModel
		expected    *TestMapOfFloatFWModel
		expectError bool
	}{
		{
			name:  "omitted property",
			input: &TestMapOfFloatPtrModel{},
			expected: &TestMapOfFloatFWModel{
				MapFloatProperty: typehelpers.NewMapValueOfNull[types.Float64](ctx),
			},
		},
		{
			name: "zero length input",
			input: &TestMapOfFloatPtrModel{
				MapFloatProperty: map[string]*float64{},
			},
			expected: &TestMapOfFloatFWModel{
				MapFloatProperty: typehelpers.NewMapValueOfMust[types.Float64](ctx, map[string]attr.Value{}),
			},
		},
		{
			name: "length 1 input",
			input: &TestMapOfFloatPtrModel{
				MapFloatProperty: map[string]*float64{
					"foo": pointer.To(floatVal),
				},
			},
			expected: &TestMapOfFloatFWModel{
				MapFloatProperty: typehelpers.NewMapValueOfMust[types.Float64](ctx, map[string]attr.Value{
					"foo": types.Float64Value(floatVal),
				}),
			},
		},
	}

	for _, c := range cases {
		diags := &diag.Diagnostics{}
		result := &TestMapOfFloatFWModel{}

		convert.Flatten(context.Background(), c.input, result, diags)

		if diags.HasError() && !c.expectError {
			t.Errorf("Test: %s \ndiags: %+v", c.name, diags)
		}

		if !reflect.DeepEqual(result, c.expected) && !c.expectError {
			t.Errorf("\nTest: %s\nexpected:\n %+v\ngot:\n %+v", c.name, c.expected, result)
		}

	}
}

func TestFlatten_mapOfString(t *testing.T) {
	ctx := context.Background()
	cases := []struct {
		name        string
		input       *TestMapOfStringModel
		expected    *TestMapOfStringFWModel
		expectError bool
	}{
		{
			name:  "omitted property",
			input: &TestMapOfStringModel{},
			expected: &TestMapOfStringFWModel{
				MapStringProperty: typehelpers.NewMapValueOfNull[types.String](ctx),
			},
		},
		{
			name: "zero length input",
			input: &TestMapOfStringModel{
				MapStringProperty: map[string]string{},
			},
			expected: &TestMapOfStringFWModel{
				MapStringProperty: typehelpers.NewMapValueOfMust[types.String](ctx, map[string]attr.Value{}),
			},
		},
		{
			name: "length 1 input",
			input: &TestMapOfStringModel{
				MapStringProperty: map[string]string{
					"foo": strVal,
				},
			},
			expected: &TestMapOfStringFWModel{
				MapStringProperty: typehelpers.NewMapValueOfMust[types.String](ctx, map[string]attr.Value{
					"foo": types.StringValue(strVal),
				}),


#include "binary_trees.h"

/**
 * binary_tree_height_b - Measures height of a binary tree for a bal tree
 * @tree: tree to go through
 * Return: the height
 */

size_t binary_tree_height_b(const binary_tree_t *tree)
{
	size_t l = 0;
	size_t r = 0;

	if (tree == NULL)
	{
		return (0);
	}
	else
	{
		if (tree)
		{
			l = tree->left ? 1 + binary_tree_height_b(tree->left) : 1;
			r = tree->right ? 1 + binary_tree_height_b(tree->right) : 1;
		}
		return ((l > r) ? l : r);
	}
}

/**
 * binary_tree_balance - Measures balance factor of a binary tree
 * @tree: tree to go through
 * Return: balanced factor
 */

int binary_tree_balance(const binary_tree_t *tree)
{
	int right = 0, left = 0, total = 0;

	if (tree)
	{
		left = ((int)binary_tree_height_b(tree->left));
		right = ((int)binary_tree_height_b(tree->right));
		total = left - right;
	}
	return (total);
}


лността.
\n
\nMonero взема предпазни мерки за да скрие данните във веригата като получател, подател и суми съответно чрез скрити адреси, подписи на пръстена и ангажименти на Педерсен. Това минимизира шансовете на случаен наблюдател да извлече критична информация след като транзакциите вече са били изпратени и сега са само част от записаната история. Има обаче някои атаки които могат да бъдат извършени в момента на извършване на транзакция която не може да бъде извършена по-късно.
';

  @override
  String get knowledge250Sbdandelion250Sb0250Sbtitle => 'Поверителността като приоритет';

  @override
  String get knowledge250Sbdandelion250Sb1250Sbtext => 'Тези атаки се въртят около идентифицирането на кой IP адрес идва транзакцията. Ако тази информация бъде извлечена тя може да разкрие че физическо лице е изпратило транзакция на Monero. Не е в състояние да покаже на кого и колко но има някои случаи в които знанието на някой който използва Monero е достатъчно за да причини вреда.\n

\nДобрата новина е че ако тази информация не бъде събрана в момента на извършване на транзакцията тя не може да бъде научена на по-късен етап тъй като IP адресите не се съхраняват в блокчейна. Също така е утешително да се знае че подобна атака е малко вероятно да бъде видяна в дивата природа тъй като за да я осъществи нападателят ще се нуждае от голямо мнозинство от възли в мрежата. Ако обаче човек можеше да управлява това голямо мнозинство той би могъл да идентифицира „посоката“, от която идва транзакцията.\n

\nТова може да е объркващо така че тук ще обясним малко основна информация. Всеки възел се свързва с други възли в мрежата така че да могат да поддържат своя блокчейн актуален както и да споделят това което знаят с другите. Тези връзки им позволяват да научават за нови транзакции да ги разпространяват и да изпращат свои собствени. Тъй като един възел може да каже на своите връстници само за транзакции за които знае логично е че първият възел който разпространява транзакция е възелът който всъщност изпраща Monero.\n

\nАко хакерът притежава г


itle>File Share</title>Public
$| p/File Share httpd/ i/Android mobile phone/ d/phone/ o/Linux/ cpe:/o:linux:linux_kernel/a
match http m|^HTTP/1\.1 200 OK\r\nConnection: close\r\n.*<title>VoIP Gateway</title>.*<frame name=\"contents\" target=\"main\" src=\"otgw\.cgi\?PAGE=USER\" scrolling=\"auto\" noresize>|s p/D-Link DVS-4088S, DVS-5088S, or DVG-7062S VoIP gateway http config/ d/VoIP adapter/
match http m|^HTTP/1\.0 200 OK\r\nServer: BEJY V([\w._-]+)  HTTP ([\w._-]+) \r\n| p/BEJY httpd/ v/$2/ i/BEJY $1/
match http m|^HTTP/1\.0 404 Not Found\r\nServer: Xfire\r\nConnection: close\r\n\r\n\r\n$| p/Xfire httpd/
match http m|^HTTP/1\.0 302 Found\r\nLocation: http://guide(?:test)?\.[\w._-]*opendns\.com/\?url=\r\nContent-type: text/html\r\nContent-Length: 0\r\nConnection: close\r\nDate: .*\r\nServer: OpenDNS Guide\r\n\r\n$| p/OpenDNS Guide/
match http m|^HTTP/1\.0 302 Found\r\nLocation: http://guide(?:test)?\.[\w._-]*opendns\.com/\?url=\r\nContent-Length: 0\r\nConnection: close\r\nDate: .*\r\nServer: OpenDNS Guide\r\n\r\n$| p/OpenDNS Guide/
match http m|^HTTP/1\.0 303 See Other\r\nLocation: http://guide(?:test)?\.[\w._-]*opendns\.com/\?url=\r\nContent-Length: 0\r\nConnection: close\r\nDate: .*\r\nServer: OpenDNS Guide\r\n\r\n$| p/OpenDNS Guide/
match http m|^HTTP/1\.1 200 OK\r\nContent-Type: text/html\r\nCache-Control: no-cache\r\nPragma: no-cache\r\n\r\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4\.01 Frameset//EN\">\r\n\r\n\r\n\r\n<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">\r\n<TITLE>\r\n(DocuPrint [\w._-]+) - ([\w._-]+)\r\n</TITLE>| p/Fuji Xerox $1 printer http config/ d/printer/ h/$2/ cpe:/h:fuji:xerox_$1/a
match http m|^HTTP/1\.1 502 Bad Gateway\r\nContent-Type: text/html\r\nContent-Length: 487\r\n\r\n\n\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<title>\nContent Server Message\n</title>\n\n\nNetwork message format error\. Unable to parse browser environment or content item\. Unable to parse properties\. Name-value pairs are missing an '='\.\n


ust** use the *PostgisTrait*.

You must also define an array called `$postgisFields` which defines
what attributes/columns on your model are to be considered geometry objects. By default, all attributes are of type `geography`. If you want to use `geometry` with a custom SRID, you have to define an array called `$postgisTypes`. The keys of this assoc array must match the entries in `$postgisFields` (all missing keys default to `geography`), the values are assoc arrays, too. They must have two keys: `geomtype` which is either `geography` or `geometry` and `srid` which is the desired SRID. **Note**: Custom SRID is only supported for `geometry`, not `geography`.

```PHP
use Illuminate\Database\Eloquent\Model;
use MStaack\LaravelPostgis\Eloquent\PostgisTrait;
use MStaack\LaravelPostgis\Geometries\Point;

class Location extends Model
{
    use PostgisTrait;

    protected $fillable = [
        'name',
        'address'
    ];

    protected $postgisFields = [
        'location',
        'location2',
        'location3',
        'polygon',
        'polygon2'
    ];

    protected $postgisTypes = [
        'location' => [
            'geomtype' => 'geography',
            'srid' => 4326
        ],
        'location2' => [
            'geomtype' => 'geography',
            'srid' => 4326
        ],
        'location3' => [
            'geomtype' => 'geometry',
            'srid' => 27700
        ],
        'polygon' => [
            'geomtype' => 'geography',
            'srid' => 4326
        ],
        'polygon2' => [
            'geomtype' => 'geometry',
            'srid' => 27700
        ]
    ]
}

$linestring = new LineString(
    [
        new Point(0, 0),
        new Point(0, 1),
        new Point(1, 1),
        new Point(1, 0),
        new Point(0, 0)
    ]
);

$location1 = new Location();
$location1->name = 'Googleplex';
$location1->address = '1600 Amphitheatre Pkwy Mountain View, CA 94043';
$location1->location = new Point(37.422009, -122.084047);
$location1->location2 = new Point(37.422009, -122.084047);
$location1->location3 = new Point(37.422009, -122.084047);
$location1->polygon = new Polygon([$linestring]);
$location1->polygon2 = new Polygon([$linestring]);
$location1->save();

$location2 = Location::first();
$location2->location instanceof Point // true
```

Available geometry classes:

 * Point
 * MultiPoint
 * LineString
 * MultiLineString
 * Polygon
 * MultiPolygon
 * GeometryCollection

## Publishing config
A configuration file exists for overriding default values. To add to your project, run:

```sh
php artisan vendor:publish --provider="MStaack\LaravelPostgis\DatabaseServiceProvider" --tag="postgis"
```
### Coordinate precision
The precision of stored/displayed coordinated can be customised in the config.

```php
# config/postgis.php
return [
    ...
    'precision' => 6,
];
```
See http://wiki.gis.com/wiki/index.php/Decimal_degrees#Accuracy for more information
# Make MOE step by step

从零构建一个MOE代码存放于 **make_moe_step_by_step.ipynb**文件下。其中有详细的代码注释，推荐结合技术博客阅读，因为博客中手画了许多图以更好地理解。

## 😸技术博客链接

- [从零构建一个MOE](https://zhuanlan.zhihu.com/p/701777558)

## 补充

博客中没提到的一点是 Expert Capacity。大概意思就是为了防�


span>

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="test.css">
  <title>Zepto Core unit tests</title>

Zepto Core unit tests

    Running… see browser console for results


s: A) -> B): (source: S) -> T? =
    { s -> getOrNull(s)?.let { b -> reverseGet(f(b)) } }

  /**
   * Create a product of the [PPrism] and a type [C]
   */
  override fun <C> first(): PPrism<Pair<S, C>, Pair<T, C>, Pair<A, C>, Pair<B, C>> =
    PPrism(
      { (s, c) -> getOrModify(s).mapLeft { it to c }.map { it to c } },
      { (b, c) -> reverseGet(b) to c }
    )

  /**
   * Create a product of a type [C] and the [PPrism]
   */
  override fun <C> second(): PPrism<Pair<C, S>, Pair<C, T>, Pair<C, A>, Pair<C, B>> =
    PPrism(
      { (c, s) -> getOrModify(s).mapLeft { c to it }.map { c to it } },
      { (c, b) -> c to reverseGet(b) }
    )

  /**
   * Create a sum of the [PPrism] and a type [C]
   */
  public fun <C> left(): PPrism<Either<S, C>, Either<T, C>, Either<A, C>, Either<B, C>> =
    PPrism(
      {
        it.fold(
          { a -> getOrModify(a).mapLeft { l -> Either.Left(l) }.map { r -> Either.Left(r) } },
          { c -> Either.Right(Either.Right(c)) })
      },
      {
        when (it) {
          is Left -> Left(reverseGet(it.value))
          is Right -> Right(it.value)
        }
      }
    )

  /**
   * Create a sum of a type [C] and the [PPrism]
   */
  public fun <C> right(): PPrism<Either<C, S>, Either<C, T>, Either<C, A>, Either<C, B>> =
    PPrism(
      {
        it.fold(
          { c -> Either.Right(Either.Left(c)) },
          { s -> getOrModify(s).mapLeft { l -> Either.Right(l) }.map { r -> Either.Right(r) } })
      },
      { it.map(this::reverseGet) }
    )

  /**
   * Compose a [PPrism] with another [PPrism]
   */
  public infix fun <C, D> compose(other: PPrism<in A, out B, out C, in D>): PPrism<S, T, C, D> =
    PPrism(
      getOrModify = { s -> getOrModify(s).flatMap { a -> other.getOrModify(a).mapLeft{ set(s, it) } } },
      reverseGet = { reverseGet(other.reverseGet(it)) }
    )

  public operator fun <C, D> plus(other: PPrism<in A, out B, out C, in D>): PPrism<S, T, C, D> =
    this compose other

  public companion object {

    public fun <S> id(): Iso<S, S> = PIso.id()

    /**
     * Invoke operator overload to create a [PPrism] of type `S` with focus `A`.
     * Can also be used to construct [Prism]
     */
    public operator fun <S, T, A, B> invoke(
      getOrModify: (S) -> Either<T, A>,
      reverseGet: (B) -> T
    ): PPrism<S, T, A, B> =
      object : PPrism<S, T, A, B> {
        override fun getOrModify(source: S): Either<T, A> = getOrModify(source)

        override fun reverseGet(focus: B): T = reverseGet(focus)
      }

    /**
     * A [PPrism] that checks for equality with a given value [a]
     */
    public fun <A> only(a: A, eq: (constant: A, other: A) -> Boolean = { aa, b -> aa == b }): Prism<A


#ifndef POKEPLATINUM_OV22_0225AF8C_H
#define POKEPLATINUM_OV22_0225AF8C_H

#include <nitro/gx.h>

#include "struct_decls/struct_02029C68_decl.h"
#include "struct_decls/struct_02029C88_decl.h"

#include "overlay022/struct_ov22_0225AF8C.h"
#include "overlay022/struct_ov22_0225B1BC_decl.h"

UnkStruct_ov22_0225B1BC *ov22_0225AF8C(const UnkStruct_ov22_0225AF8C *param0, const UnkStruct_02029C68 *param1);
UnkStruct_ov22_0225B1BC *ov22_0225AFB0(const UnkStruct_ov22_0225AF8C *param0, const UnkStruct_02029C88 *param1);
UnkStruct_ov22_0225B1BC *ov22_0225AFD4(const UnkStruct_ov22_0225AF8C *param0, const UnkStruct_02029C88 *param1);
void ov22_0225AFF8(UnkStruct_ov22_0225B1BC *param0);
void ov22_0225B020(UnkStruct_ov22_0225B1BC *param0);
void ov22_0225B06C(UnkStruct_ov22_0225B1BC *param0);
void ov22_0225B074(UnkStruct_ov22_0225B1BC *param0, BOOL param1);
void ov22_0225B07C(UnkStruct_ov22_0225B1BC *param0, BOOL param1);
void ov22_0225B080(UnkStruct_ov22_0225B1BC *param0, int param1, int param2);
void ov22_0225B0D8(UnkStruct_ov22_0225B1BC *param0, int param1, int param2);
void ov22_0225B0E4(UnkStruct_ov22_0225B1BC *param0, u16 param1);
void ov22_0225B0EC(UnkStruct_ov22_0225B1BC *param0, fx32 param1, fx32 param2, fx32 param3);
void ov22_0225B100(UnkStruct_ov22_0225B1BC *param0, int param1, int param2);
void ov22_0225B158(UnkStruct_ov22_0225B1BC *param0, int param1, int param2, int param3);
void ov22_0225B198(UnkStruct_ov22_0225B1BC *param0, GXRgb param1);
void ov22_0225B1AC(UnkStruct_ov22_0225B1BC *param0, int param1);

#endif // POKEPLATINUM_OV22_0225AF8C_H


6, --
				[631] = 139, --
				[645] = 336, --
				[646] = 429, --
				[649] = 259, --
				[651] = 233, --
				[654] = 399, --
				[667] = 324, --
				[668] = 363, --
				[669] = 318, --
				[670] = 315, --
				[672] = 250, --
				[681] = 362, --
				["name"] = "Zul'Aman",
			},
			-- Eastern Plaguelands
			[315] = {
				[56] = 0, -- 763
				[70] = 0, -- 606
				[635] = 0, -- 366
				[673] = 0, -- 501
				["name"] = "Acherus: The Ebon Hold",
				[10] = 315, --
				[11] = 297, --
				[13] = 236, --
				[17] = 253, --
				[68] = 50, --
				[76] = 186, --
				[82] = 231, --
				[83] = 164, --
				[84] = 130, --
				[85] = 96, --
				[86] = 66, --
				[87] = 106, --
				[205] = 143, --
				[213] = 390, --
				[383] = 137, --
				[384] = 212, --
				[460] = 260, --
				[617] = 221, --
				[625] = 209, --
				[630] = 77, --
				[631] = 252, --
				[645] = 277, --
				[649] = 200, --
				[651] = 175, --
				[654] = 340, --
				[667] = 265, --
				[668] = 305, --
				[669] = 259, --
				[670] = 256, --
				[672] = 191, --
				[681] = 303, --
			},
			[68] = {
				[18] = 789,
				[20] = 731,
				[56] = 717,
				[70] = 560,
				[75] = 467,
				[315] = 64,
				[383] = 94,
				[384] = 169,
				[635] = 322,
				[649] = 158,
				[651] = 133,
				[659] = 500,
				[668] = 262,
				[670] = 214,
				[672] = 149,
				["name"] = "Light's Hope Chapel",
				[10] = 272, --
				[11] = 254, --
				[13] = 193, --
				[17] = 210, --
				[76] = 143, --
				[82] = 187, --
				[83] = 120, --
				[84] = 87, --
				[85] = 53, --
				[86] = 23, --
				[87] = 63, --
				[205] = 98, --
				[213] = 346, --
				[460] = 217, --
				[601] = 243, --
				[608] = 527, --
				[617] = 178, --
				[625] = 165, --
				[630] = 35, --
				[631] = 208, --
				[645] = 234, --
				[646] = 327, --
				[654] = 297, --
				[667] = 222, --
				[669] = 216, --
				[681] = 260, --
			},
			[85] = {
				[10] = 269, --
				[11] = 250, --
				[13] = 189, --
				[17] = 242, --
				[68] = 58, --
				[76] = 194, --
				[82] = 237, --
				[83] = 171, --
				[84] = 49, --
				[86] = 30, --
				[87] = 52, --
				[205] = 149, --
				[213] = 397, --
				[315] = 115, --


Resource menu commands

Commands in the Resource menu (see Figure 25-16) are used to
create new resources. In each case, a new ID is automatically
created and assigned to the resource, and the resource is opened in
the right pane of the Browser window so that the resource can be
edited.

	[Figure 25-16 Browser window Resource menu

New Dialog Box

Creates a new dialog box. As the resource is created, the
DialogExpress dialog box lets you select a predefined dialog type
to use as a starting point (see "Dialog Editor," in Chapter 26, "Dialog
Editor").

New Bitmap

Creates a new bitmap. As the resource is created, the
BitmapExpress dialog box lets you specify initial bitmap
parameters (see "Bitmap Editor," in Chapter 28, "Bitmap, Cursor,
Icon, and Font Editors").

New Icon

Creates a new icon.

New Cursor

Creates a new cursor.

New Menu

Creates a new menu.

New Font

Creates a new font. As the resource is created, the FontExpress
dialog box lets you specify initial font parameters (see "Font Editor,"
in Chapter 28, "Bitmap, Cursor, Icon, and Font Editors").

New String Table

Creates a new string table.

New Accelerator Table

Creates a new accelerator table.

New Version

Creates a new version information resource.

New Other

Opens the Create Custom Resource dialog box (see Figure 25-17). Use this
dialog box to select a custom resource type to create and to define
new custom resource types.

	[Figure 25-17 Create Custom Resource dialog box

To create one of the listed resource types, select it and click OK. To
define a new resource type, click on Add Type. The New Resource
Type dialog box opens (see Figure 25-18).

	[Figure 25-18 New Resource Type dialog box

Type a name for the new resource type in the textbox and click OK.
The new type is added to the list in the Create Custom Resource dialog
box.

Toolbar commands

The Browser window toolbar provides quick
access to frequently used menu commands:

	[Figure 25-19 Browser window toolbar]

	Same as choosing Save from the File menu.

	Same as choosing Undo from the Edit menu. Right-click on
	this button to undo multiple operations at once.

	Same as choosing <b


>
【实例二】证书双向验证抓包

证书双向验证抓包

此处以soal app为例

首先需要下载soul app，然后安装

先尝试一下是不是单向验证+SSL pinning来防止抓包的

方法一：Xposed加载JustTrustMe模块

方法二：使用frida的ssl_pinning的js模块

frida -U -l<span class="t


et argument stack ptr
        lda #<(__RAM_START__ + __RAM_SIZE__)
        sta sp
        lda #>(__RAM_START__ + __RAM_SIZE__)
        sta sp + 1

        ldx #zpspace - 1
@L1:
        lda sp, x
        sta zpsave, x    ; Save the zero page locations we need
        dex
        bpl @L1
        rts

c_exit:
        ldx #zpspace - 1
@L1:
        lda zpsave, x    ; Restore the zero page locations we need
        sta sp, x
        dex
        bpl @L1
        rts

.segment "ZPSAVE"

zpsave:
        .res ZPSPACE

.code

; =============================================================================
;
; =============================================================================
irq_ret:
        rti

; =============================================================================
; Common code on all KERNAL banks
; =============================================================================
.segment "KERNAL_COMMON"
.include "kernal_common.s"

; these vectors are not used usually as this is the KERNAL bank 1
.segment "VECTORS"
.word   irq_ret
.word   irq_ret ; <= arrrgh!
.word   irq_ret


blems/set-matrix-zeroes/)

### `O(mn)` Space Complexity
```kotlin
fun setZeroes(matrix: Array<IntArray>): Unit {
    val setZeroPositions = hashSetOf<Pair<Int, Int>>()
    val m = matrix.size
    val n = matrix[0].size
    for (i in 0 until m) {
        for (j in 0 until n) {
            if (matrix[i][j] == 0) setZeroPositions.add(i to j)
        }
    }

    for (position in setZeroPositions) {
        setZero(matrix, position.first, position.second)
    }
}

private fun setZero(matrix: Array<IntArray>, row: Int, col: Int) {
    for (i in 0 until matrix.size) {
        matrix[i][col] = 0
    }
    for (j in 0 until matrix[0].size) {
        matrix[row][j] = 0
    }
}
```

### `O(m + n)` Space Complexity
```kotlin
fun setZeroes(matrix: Array<IntArray>): Unit {
    val m = matrix.size
    val n = matrix[0].size
    val zeroRows = BooleanArray(m)
    val zeroCols = BooleanArray(n)
    for (i in 0 until m) {
        for (j in 0 until n) {
            if (matrix[i][j] == 0) {
                zeroRows[i] = true
                zeroCols[j] = true
            }
        }
    }

    for (i in 0 until m) {
        for (j in 0 until n) {
            if (zeroRows[i] || zeroCols[j]) {
                matrix[i][j] = 0
            }
        }
    }
}
```

### `O(1)` Space Complexity
**Idea!!** We can use the first row and column to keep track of whether that row/column has to set zero, but before that, we have to know whether the first row/column itself contains zero first.

```js
// Original
5, 5, 5
0, 5, 0
5, 5, 5

// If we don't check the first row/column first, we will get the wrong result
5, 5, 0
0, 5, 5
5, 5, 5

// It leads to the wrong result
5, 5, 0
0, 0, 0
5, 5, 0

// But the correct result is
0, 5, 0
0, 0, 0
0, 5, 0
```

```python
def setZeroes(self, matrix: List[List[int]]) -> None:
    """
    Do not return anything, modify matrix in-place instead.
    """
    m = len(matrix)
    n = len(matrix[0])

    row0 = False
    col0 = False
    for i in range(0, m):
        for j in range(0, n):
            if matrix[i][j] == 0:
                if i == 0: row0 = True
                if j == 0: col0 = True
                if i > 0 and j > 0:
                    matrix[0][j] = 0
                    matrix[i][0] = 0

    for i in range(1, m):
        for j in range(1, n):
            if matrix[0][j] == 0 or matrix[i][0] == 0:
                matrix[i][j] = 0

    if row0:
        for j in range(0, n):
            matrix[0][j] = 0
    if col0:
        for i in range(0, m):
            matrix[i][0] = 0
```

```kotlin
fun setZeroes(matrix: Array<IntArray>): Unit {
    val m = matrix.size
    val n = matrix[0].size
    var firstRowContainsZero = false
    var firstColContainsZero = false
    for (i in 0 until m) {
        for (j in 0 until n) {
            if (matrix[i][j] == 0) {
                if (i == 0) firstRowContainsZero = true
                if (j == 0) firstColContainsZero = true
                if (i != 0 && j != 0) {
                    matrix[0][j] = 0
                    matrix[i][0] = 0


ator (76 users)","Salon Manager (60 users)","Special Events Coordinator (62 users)","Talent Agent (75 users)","Talent Manager (77 users)","Theater Manager (72 users)","Theatrical Agent (54 users)"],"type":"scatter","mode":"markers","hoverinfo":["text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text","text"],"textposition":["middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right","middle right"],"name":"Fashion Marketer","marker":{"color":"rgba(106,61,154,0.7)","size":[55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55],"sizemode":"area","line":{"color":"rgba(106,61,154,1)"}},"textfont":{"color":"rgba(106,61,154,0.7)","size":55},"error_y":{"color":"rgba(106,61,154,0.7)","width":55},"error_x":{"color":"rgba(106,61,154,0.7)","width":55},"line":{"color":"rgba(106,61,154,0.7)","width":55},"xaxis":"x","yaxis":"y","frame":null},{"x":[17.107044778605,13.6412364239544,13.9839032410969,13.9400187288728,13.7980556111186,4.17585951955001,15.8600747892422,13.5355252494326,3.56599496554256,17.3770875031147,10.3289305409813,8.06086038505775,16.6174220966613,13.2199309379023,13.6385513254376,15.6214764353456,13.7331933383928,8.5553454556201,16.8638662529822,14.6264491681344,14.9593929985139,15.7572948835598,13.6829801542281,15.75953773706,15.773981030861,13.7251504851411,14.0654515319971,17.0166371094669,11.5524694215542,11.660603045701,13.0892399789484,13.6757050923452,-0.856198825980262,4.83596883858575,-8.47166411671478,15.0196897670641,17.3104120123655,13.5085514690115,12.5422547164291,15.0350294228208,12.8478131944669,11.6717374788643,15.7572808946151,16.7603911087352,14.4796397219099,15.271829535614,-0.664775516098121,15.8065247269252,11.8014014656395,15.6187999057277,9.86662965198016,16.3662718725569,4.33146989762869,16.6546797490771,14.1958297393171,21.3067604177868,8.85154234791852,10.2111936036121,15.1750754971802,-0.706919860353225,14.7315996408038,17.5798357949584,20.9917685602672,15.9149091744685,8.28030866539561,10.3230917444091,9.17154443005941,11.7770856026171,16.8182113


conocido"},
        {".PATTERN.printX509Cert.with.weak",
                "Propietario: {0}\nEmisor: {1}\nN\u00FAmero de serie: {2}\nV\u00E1lido desde: {3} hasta: {4}\nHuellas digitales del certificado:\n\t SHA1: {5}\n\t SHA256: {6}\nNombre del algoritmo de firma: {7}\nAlgoritmo de clave p\u00FAblica de asunto: {8}\nVersi\u00F3n: {9}"},
        {"PKCS.10.with.weak",
                "Solicitud de certificado PKCS #10 (Versi\u00F3n 1.0)\nAsunto: %1$s\nFormato: %2$s\nClave p\u00FAblica: %3$s\nAlgoritmo de firma: %4$s\n"},
        {"verified.by.s.in.s.weak", "Verificado por %1$s en %2$s con %3$s"},
        {"whose.sigalg.risk", "%1$s utiliza el algoritmo de firma %2$s, lo que se considera un riesgo de seguridad."},
        {"whose.key.risk", "%1$s utiliza %2$s, lo que se considera riesgo de seguridad."},
        {"jks.storetype.warning", "El almac\u00E9n de claves %1$s utiliza un formato propietario. Se recomienda migrar a PKCS12, que es un formato est\u00E1ndar del sector que utiliza \"keytool -importkeystore -srckeystore %2$s -destkeystore %2$s -deststoretype pkcs12\"."},
        {"migrate.keystore.warning", "Se ha migrado \"%1$s\" a %4$s. Se ha realizado la copia de seguridad del almac\u00E9n de claves %2$s como \"%3$s\"."},
        {"backup.keystore.warning", "La copia de seguridad del almac\u00E9n de claves \"%1$s\" se ha realizado como \"%3$s\"..."},
        {"importing.keystore.status", "Importando el almac\u00E9n de claves de %1$s a %2$s..."},
    };

    /**
     * Returns the contents of this ResourceBundle.
     *
     *

     *
     * @return the contents of this ResourceBundle.
     */
    @Override
    public Object[][] getContents() {
        return contents;
    }
}
/*
 * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package sun.security.internal.spec;

import java.security.spec.KeySpec;

import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

/**
 * KeySpec class for SSL/TLS key material.
 *
 *
Instances of this class are returned by the generateKey()
 * method of KeyGenerators of the type "Tls


/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 * Hash Table
 * (C) 2013  Jung-Sang Ahn <jungsang.ahn@gmail.com>
 */

#ifndef _JSAHN_HASH_H
#define _JSAHN_HASH_H

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#define _HASH_TREE
#ifdef _HASH_TREE
    #include "avltree.h"
#else
    #include "list.h"
#endif

//#define _HASH_LOCK
#ifdef _HASH_LOCK
    #include "arch.h"
#endif

struct hash_elem {
#ifdef _HASH_TREE
    struct avl_node avl;
#else
    struct list_elem list_elem;
#endif
};

struct hash;

typedef uint32_t hash_hash_func(struct hash *hash, struct hash_elem *e);
typedef int hash_cmp_func(struct hash_elem *a, struct hash_elem *b);
//typedef int hash_cmp_func(void *a, void *b);
typedef void hash_free_func(struct hash_elem *e);
typedef void *hash_check_func(struct hash_elem *e, void *ctx);

struct hash {
    size_t nbuckets;
#ifdef _HASH_TREE
    struct avl_tree *buckets;
#else
    struct list *buckets;
#endif

    hash_hash_func *hash_func;
    hash_cmp_func *cmp;
#ifdef _HASH_TREE
    avl_cmp_func *avl_cmp;
#endif

#ifdef _HASH_LOCK
    // define locks for each bucket
    spin_t *locks;
#endif
};

void hash_init(struct hash *hash, int nbuckets, hash_hash_func *hash_func, hash_cmp_func *cmp_func);
void hash_insert(struct hash *hash, struct hash_elem *e);
void hash_insert_by_hash_val(struct hash *hash, struct hash_elem *e, uint32_t hash_val);
struct hash_elem * hash_find(struct hash *hash, struct hash_elem *e);
struct hash_elem * hash_find_by_hash_val(struct hash *hash, struct hash_elem *e,
                                         uint32_t hash_val);
void *hash_scan(struct hash *hash, hash_check_func *check_func, void *ctx);
void hash_remove(struct hash *hash, struct hash_elem *e);
void hash_free(struct hash *hash);
void hash_free_active(struct hash *hash, hash_free_func *free_func);

#ifdef __cplusplus
}
#endif

#endif


x24, 40]
	str	x1, [x22]
	ldp	x19, x20, [sp, 16]
	ldp	x21, x22, [sp, 32]
	ldp	x23, x24, [sp, 48]
	ldr	x25, [sp, 64]
	ldp	x29, x30, [sp], 80
	ret
	.p2align 3
.L884:
	asr	w19, w0, 31
	lsr	w19, w19, 21
	add	w0, w0, w19
	and	w0, w0, 2047
	sub	w19, w0, w19
	b	.L872
.L885:
	ldr	w1, [x20, 8]
	mov	w2, w19
	mov	x0, x24
	bl	ReleaseSegArrayPackets
	ldr	x0, [x25]
	str	x0, [x22]
	mov	w0, 0
	ldp	x19, x20, [sp, 16]
	ldp	x21, x22, [sp, 32]
	ldp	x23, x24, [sp, 48]
	ldr	x25, [sp, 64]
	ldp	x29, x30, [sp], 80
	ret
	.size	SM_SeekPtsInSegArray, .-SM_SeekPtsInSegArray
	.global	_mcount
	.align	2
	.p2align 3,,7
	.global	SM_SeekPtsInRawArray
	.type	SM_SeekPtsInRawArray, %function
SM_SeekPtsInRawArray:
	stp	x29, x30, [sp, -48]!
	add	x29, sp, 0
	stp	x19, x20, [sp, 16]
	stp	x21, x22, [sp, 32]
	mov	x20, x0
	mov	x0, x30
	mov	w19, w2
	mov	x21, x1
	mov	w22, w3
	bl	_mcount
	ldr	x0, .LC235
	add	x0, x0, x19, sxtw 4
	ldr	x9, [x0, 16]
	cbz	x9, .L905
	cmp	w22, 1
	mov	w10, 0
	ldp	x8, x11, [x21]
	beq	.L917
.L888:
	add	x6, x20, 98304
	ldp	w3, w7, [x6]
	str	w3, [x6, 8]
	mov	w1, w3
	.p2align 2
.L889:
	sxtw	x5, w1
	add	w0, w1, 1
	asr	w4, w0, 31
	lsl	x2, x5, 2
	sub	x2, x2, x5
	lsr	w4, w4, 22
	cmp	w1, w7
	add	w0, w0, w4
	add	x2, x20, x2, lsl 5
	and	w0, w0, 1023
	beq	.L918
	ldr	x2, [x2, 64]
	cmn	x2, #1
	beq	.L919
	cmp	x8, x2
	bls	.L895
	str	w1, [x6, 8]
	sub	w1, w0, w4
	b	.L889
	.p2align 3
.L919:
	add	w0, w1, 1
	asr	w1, w0, 31
	lsr	w1, w1, 22
	add	w0, w0, w1
	and	w0, w0, 1023
	sub	w1,


="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../../property_tree/reference.html#header.boost.property_tree.ini_parser_hpp" title="Header <boost/property_tree/ini_parser.hpp>">
<link rel="prev" href="ini_parser_error.html" title="Class ini_parser_error">
<link rel="next" href="read_ini_id1075595.html" title="Function template read_ini">

Home
Libraries
People
FAQ
More

Function validate_flags

boost::property_tree::ini_parser::validate_flags

Synopsis

// In header: <boost/property_tree/ini_parser.hpp>

bool validate_flags(int flags);

Description

Determines whether the flags are valid for use with the ini_parser.

<col align="left" valign="top">

Parameters:

<col align="left" valign="top">

<span class


   Task<Nota> GetByIdAsync(int id);

        bool Adicionar(Nota nota);
        bool Atualizar(Nota nota);
        bool Remover(Nota nota);
        bool Salvar();
    }
}


cFrame("main_frame") {

    init {
        defaultCloseOperation = EXIT_ON_CLOSE

        setSize(1050, 800)

        contentPane.add(MainPanel)

        jMenuBar = Menu

        @Suppress("UNUSED_EXPRESSION")
        BattlePanel // make sure the battle panel is initialized before being used the first time

        ClientEvents.apply {
            onGameStarted.subscribe(MainFrame) { MainPanel.showArena() }
            onGameEnded.subscribe(MainFrame) { MainPanel.showLogo() }
            onGameAborted.subscribe(MainFrame) { MainPanel.showLogo() }
            onPlayerChanged.subscribe(MainFrame) { MainPanel.showArena() }
        }
        ServerEvents.onStopped.subscribe(MainFrame) { MainPanel.showLogo() }

        onClosing { close() }
        Runtime.getRuntime().addShutdownHook(Thread { close() })
    }

    private fun close() {
        Client.close()
        BootProcess.stop()
        RecorderProcess.stop()
        ServerProcess.stop()
    }

    private object MainPanel : JPanel() {
        init {
            @Suppress("UnusedExpression")
            ControlEventHandlers
            @Suppress("UnusedExpression")
            SoundActions
            @Suppress("UnusedExpression")
            AutoRecorder

            layout = BorderLayout()
            add(LogoPanel, BorderLayout.CENTER)
            add(ControlPanel, BorderLayout.SOUTH)

            ControlPanel.isVisible = false
        }

        fun showLogo() {
            remove(BattlePanel)
            add(LogoPanel, BorderLayout.CENTER)

            refresh()
        }

        fun showArena() {
            remove(LogoPanel)
            add(BattlePanel, BorderLayout.CENTER)

            ControlPanel.isVisible = true
            refresh()
        }

        private fun refresh() {
            validate()
            repaint()
        }
    }
}package dev.robocode.tankroyale.gui.util

import java.awt.Color

/**
 * Data class for holding a HSL color.
 */
data class HslColor(var hue: Float, var saturation: Float, var lightness: Float) {

    /**
     * Multiply a factor to the HSL lightning value.
     * @param factor is the factor to multiply to the lightning value.
     */
    fun multLight(factor: Float): HslColor {
        lightness *= factor
        return this
    }

    /**
     * Add a value to the HSL lightning value.
     * @param value is the value to add to the lightning value.
     */
    fun addLight(value: Float): HslColor {
        lightness += value
        if (lightness < 0f) lightness = 0f
        else if (lightness > 1f) lightness = 1f
        return this
    }

    /**
     * Creates a new Color from a HSL color value.
     *
     * @return The converted Color.
     */
    fun toColor(): Color {
        val r: Float
        val g: Float
        val b: Float
        if (saturation == 0f) {
            b = lightness
            g = b
            r = g // achromatic
        } else {
            val q = if (lightness < 0.5f)
                lightness * (1 + saturation)
            else
                lightness + saturation - lightness * saturation
            val p = 2 * lightness - q
            r = hueToRgb(p, q, hue + 1f / 3f)
            g = hueToRgb(p, q, hue)
            b = hueToRgb(p, q, hue - 1f / 3f)
        }
        return Color(to255(r), to255(g), to255(b))
    }

    private fun to255(v: Float): Int {
        return 255f.coerceAtMost(256 * v).toInt()
    }

    /** Helper method that converts hue to rgb  */
    private fun hueToRgb(m1: Float, m2: Float, hue:


class Net(nn.Module):
  """
  Initialize MLP Network
  """

  def __init__(self, actv, input_feature_num, hidden_unit_nums, output_feature_num):
    """
    Initialize MLP Network parameters

    Args:
      actv: string
        Activation function
      input_feature_num: int
        Number of input features
      hidden_unit_nums: list
        Number of units per hidden layer, list of integers
      output_feature_num: int
        Number of output features

    Returns:
      Nothing
    """
    super(Net, self).__init__()
    self.input_feature_num = input_feature_num # Save the input size for reshaping later
    self.mlp = nn.Sequential() # Initialize layers of MLP

    in_num = input_feature_num # Initialize the temporary input feature to each layer
    for i in range(len(hidden_unit_nums)): # Loop over layers and create each one

      out_num = hidden_unit_nums[i] # Assign the current layer hidden unit from list
      layer = nn.Linear(in_num, out_num) # Use nn.Linear to define the layer
      in_num = out_num # Assign next layer input using current layer output
      self.mlp.add_module('Linear_%d'%i, layer) # Append layer to the model with a name

      actv_layer = eval('nn.%s'%actv) # Assign activation function (eval allows us to instantiate object from string)
      self.mlp.add_module('Activation_%d'%i, actv_layer) # Append activation to the model with a name

    out_layer = nn.Linear(in_num, output_feature_num) # Create final layer
    self.mlp.add_module('Output_Linear', out_layer) # Append the final layer

  def forward(self, x):
    """
    Simulate forward pass of MLP Network

    Args:
      x: torch.tensor
        Input data

    Returns:
      logits: Instance of MLP
        Forward pass of MLP
    """
    # Reshape inputs to (batch_size, input_feature_num)
    # Just in case the input vector is not 2D, like an image!
    x = x.view(-1, self.input_feature_num)

    logits = self.mlp(x) # Forward pass of MLP
    return logits

input = torch.zeros((100, 2))
## Uncomment below to create network and test it on input
net = Net(actv='LeakyReLU(0.1)', input_feature_num=2, hidden_unit_nums=[100, 10, 5], output_feature_num=1).to(DEVICE)
y = net(input.to(DEVICE))
print(f'The output shape is {y.shape} for an input of shape {input.shape}')


 boot: true, src_data: src_data3 })
    const { res } = await p.msg(
      "Hello3",
      { mod: mem.modules.aos2_0_1, auth: mu.addr }, // todo: module tag not allowed?
      { data: src_data }
    )
    const prs = mem.env
    let p2 = null
    for (let k in prs) {
      for (let k2 of prs[k].results) {
        for (let v of mem.msgs[k2].res.Spawns || []) {
          if (tags(v.Tags)["From-Process"] === pid) p2 = ao.p(k)
        }
      }
    }
    assert.notEqual(p2, null)
  })

  it("should assign a process from a handler", async () => {
    const { p, pid } = await ao.deploy({ boot: true, src_data: src_data4 })
    const { mid } = await p.msg("Add", { Plus: "3" })
    const { p: p2, pid: pid2 } = await ao.deploy({
      boot: true,
      src_data: src_data4,
    })
    await p.m("Hello4", { Message: mid, Process: pid2 })
    assert.equal(await p2.d("Get", { get: false }), "3")
  })

  it("should work with pre-loaded packages", async () => {
    const { p } = await ao.deploy({ src_data: src_data5 })
    assert.equal(await p.d("Hello"), "Hello, World!")
  })

  it("should work with weavedrive: Assignments", async () => {
    const { p, pid } = await ao.deploy({
      src_data: src_data6,
      tags: { Extension: "WeaveDrive", Attestor: ao.ar.addr },
      data: "Hello, World!",
    })
    await ao.attest({ id: pid })
    assert.equal(await p.d("Hello", { msg: pid }), "Hello, World!")
  })

  it("should work with weavedrive: Individual", async () => {
    const src = new Src({ dir: resolve(import.meta.dirname, "../../src/lua") })
    const data = src.data("aos2_0_1", "wasm")
    const { id: modid } = await ao.postModule({
      data,
      jwk,
      tags: { "Availability-Type": "Individual" },
    })

    const { p, pid } = await ao.deploy({
      module: modid,
      src_data: src_data6,
      tags: { Extension: "WeaveDrive", Attestor: ao.ar.addr },
      data: "Hello, World!",
    })
    await ao.avail({ ids: [pid] })
    assert.equal(await p.d("Hello", { msg: pid }), "Hello, World!")
  })

  it("should load apm mock", async () => {
    const { p } = await ao.deploy({
      tags: { Extension: "WeaveDrive", Attestor: ao.ar.addr },
      loads: [
        await blueprint("apm"),
        `apm.install('@rakis/WeaveDrive')`,
        src_data7,
      ],
    })
    const { id } = await ao.ar.post({ data: "Hello, World!" })
    await ao.attest({ id })
    assert.equal(await p.d("Get-Data", { id }), "Hello, World!")
    return
  })

  it("should post tx", async () => {
    const { id } = await ao.ar.post({
      data: "Hello, World!",
      tags: { one: "1" },
      jwk,
    })
    assert.equal(await ao.ar.data(id, true), "Hello, World!")
  })

  it("should monitor crons", async


 = Collate('BINARY');

  /// The same as [Collate.binary], except the 26 upper case characters of ASCII
  /// are folded to their lower case equivalents before the comparison is
  /// performed. Note that only ASCII characters are case folded. SQLite does
  /// not attempt to do full UTF case folding due to the size of the tables
  /// required.
  static const noCase = Collate('NOCASE');

  /// The same as [Collate.binary], except that trailing space characters are
  /// ignored.
  static const rTrim = Collate('RTRIM');
}

/// A `text COLLATE collate` expression in sqlite.
class _CollateOperator extends Expression<String> {
  /// The expression on which the collate function will be run
  final Expression inner;

  /// The [Collate] to use.
  final Collate collate;

  @override
  final Precedence precedence = Precedence.postfix;

  /// Constructs a collate expression on the [inner] expression and the
  /// [Collate].
  _CollateOperator(this.inner, this.collate);

  @override
  void writeInto(GenerationContext context) {
    writeInner(context, inner);
    context.buffer
      ..write(' COLLATE ')
      ..write(collate.name);
  }

  @override
  int get hashCode => Object.hash(inner, collate.name);

  @override
  bool operator ==(Object other) {
    return other is _CollateOperator &&
        other.inner == inner &&
        other.collate.name == collate.name;
  }
}
part of '../query_builder.dart';

/// Defines operations on boolean values.
extension BooleanExpressionOperators on Expression<bool> {
  /// Negates this boolean expression. The returned expression is true if
  /// `this` is false, and vice versa.
  Expression<bool> not() => _NotExpression(this);

  /// Returns an expression that is true iff both `this` and [other] are true.
  ///
  /// For a bitwise-and on two numbers, see [BitwiseInt.bitwiseAnd].
  Expression<bool> operator &(Expression<bool> other) {
    return BaseInfixOperator(this, 'AND', other, precedence: Precedence.and);
  }

  /// Returns an expression that is true if `this` or [other] are true.
  ///
  /// For a bitwise-or on two numbers, see [BitwiseInt.bitwiseOr].
  Expression<bool> operator |(Expression<bool> other) {
    return BaseInfixOperator(this, 'OR', other, precedence: Precedence.or);
  }
}

class _NotExpression extends Expression<bool> {
  final Expression<bool> inner;

  _NotExpression(this.inner);

  @override
  Precedence get precedence => Precedence.unary;

  @override
  void writeInto(GenerationContext context) {
    context.buffer.write('NOT ');
    writeInner(context, inner);
  }

  @override
  int get hashCode => inner.hashCode << 1;

  @override
  bool operator ==(Object other) {
    return other is _NotExpression && other.inner == inner;
  }
}
import 'package:meta/meta.dart';

import '../query_builder.dart';

/// A `CASE WHEN` expression **without** a base expression in sqlite.
///
/// This expression evaluates to the first value in [BaseCaseWhenExpression.orderedCases]
/// for which [CaseWhen.when] evaluates to `true`.
class CaseWhenExpression<R extends Object>
    extends BaseCaseWhenExpression<bool, R> {
  /// Creates a `CASE WHEN` expression from the independent components.
  ///
  /// This expression evaluates to the first value in [cases]
  /// for which [CaseWhen.when] evaluates to `true`.
  ///
  /// If [cases] is empty - throws [ArgumentError]
  CaseWhenExpression({
    required List<CaseWhen<bool, R>> cases,
    Expression<R>? orElse,
  }) : super._(null, cases, orElse);
}

/// `CASE WHEN` expression **with** base expression in sqlite.
/


{@link #GL_DISPATCH_INDIRECT_BUFFER DISPATCH_INDIRECT_BUFFER} buffer target at which the dispatch parameters are
     *                 stored.
     *
     * @see Reference Page
     */
    public static native void glDispatchComputeIndirect(@NativeType("GLintptr") long indirect);

    // --- [ glCopyImageSubData ] ---

    /**
     * Performs a raw data copy between two images.
     *
     * @param srcName   the name of a texture or renderbuffer object from which to copy
     * @param srcTarget the target representing the namespace of the source name {@code srcName}
     * @param srcLevel  the mipmap level to read from the source
     * @param srcX      the X coordinate of the left edge of the souce region to copy
     * @param srcY      the Y coordinate of the top edge of the souce region to copy
     * @param srcZ      the Z coordinate of the near edge of the souce region to copy
     * @param dstName   the name of a texture or renderbuffer object to which to copy
     * @param dstTarget the target representing the namespace of the destination name {@code dstName}
     * @param dstLevel  the mipmap level to write to the source
     * @param dstX      the X coordinate of the left edge of the destination region
     * @param dstY      the Y coordinate of the top edge of the destination region
     * @param dstZ      the Z coordinate of the near edge of the destination region
     * @param srcWidth  the width of the region to be copied
     * @param srcHeight the height of the region to be copied
     * @param srcDepth  the depth of the region to be copied
     *
     * @see Reference Page
     */
    public static native void glCopyImageSubData(@NativeType("GLuint") int srcName, @NativeType("GLenum") int srcTarget, @NativeType("GLint") int srcLevel, @NativeType("GLint") int srcX, @NativeType("GLint") int srcY, @NativeType("GLint") int srcZ, @NativeType("GLuint") int dstName, @NativeType("GLenum") int dstTarget, @NativeType("GLint") int dstLevel, @NativeType("GLint") int dstX, @NativeType("GLint") int dstY, @NativeType("GLint") int dstZ, @NativeType("GLsizei") int srcWidth, @NativeType("GLsizei") int srcHeight, @NativeType("GLsizei") int srcDepth);

    // --- [ glDebugMessageControl ] ---

    /**
     * Unsafe version of: {@link #glDebugMessageControl DebugMessageControl}
     *
     * @param count the length of the array {@code ids}
     */
    public static native void nglDebugMessageControl(int source, int type, int severity, int count, long ids, boolean enabled);

    /**
     * Controls the volume of debug output in the active debug group, by disabling specific or groups of messages.
     *
     *
If {@code enabled} is {@link GL11#GL_TRUE TRUE}, the referenced subset of messages will be enabled. If {@link GL11#GL_FALSE FALSE}, then those messages will be disabled.

     *
     *
This command can reference different subsets of messages by first considering the set of all messages, and filtering out messages based on the following
     * ways:

     *
     *

     *
If {@code source}, {@code type}, or {@code severity} is {@link GL11#GL_DONT_CARE DONT_CARE}, the messages from all sources, of all types, or of all severities are
     * referenced respectively.

     *
When values other than {@link GL11#GL_DONT_CARE DONT_CARE} are specified, all m


IBUTE*/
					Attributes: map[string]schema.Attribute{ /*START SCHEMA*/
						// Property: ConstantBitrate
						"constant_bitrate": schema.Int64Attribute{ /*START ATTRIBUTE*/
							Description: "The constant bitrate configuration for the video encode.\nWhen this field is defined, StatmuxSettings must be undefined.",
							Optional:    true,
							Computed:    true,
							Validators: []validator.Int64{ /*START VALIDATORS*/
								int64validator.Between(100000, 100000000),
							}, /*END VALIDATORS*/
							PlanModifiers: []planmodifier.Int64{ /*START PLAN MODIFIERS*/
								int64planmodifier.UseStateForUnknown(),
							}, /*END PLAN MODIFIERS*/
						}, /*END ATTRIBUTE*/
						// Property: StatmuxSettings
						"statmux_settings": schema.SingleNestedAttribute{ /*START ATTRIBUTE*/
							Attributes: map[string]schema.Attribute{ /*START SCHEMA*/
								// Property: MaximumBitrate
								"maximum_bitrate": schema.Int64Attribute{ /*START ATTRIBUTE*/
									Description: "Maximum statmux bitrate.",
									Optional:    true,
									Computed:    true,
									Validators: []validator.Int64{ /*START VALIDATORS*/
										int64validator.Between(100000, 100000000),
									}, /*END VALIDATORS*/
									PlanModifiers: []planmodifier.Int64{ /*START PLAN MODIFIERS*/
										int64planmodifier.UseStateForUnknown(),
									}, /*END PLAN MODIFIERS*/
								}, /*END ATTRIBUTE*/
								// Property: MinimumBitrate
								"minimum_bitrate": schema.Int64Attribute{ /*START ATTRIBUTE*/
									Description: "Minimum statmux bitrate.",
									Optional:    true,
									Computed:    true,
									Validators: []validator.Int64{ /*START VALIDATORS*/
										int64validator.Between(100000, 100000000),
									}, /*END VALIDATORS*/
									PlanModifiers: []planmodifier.Int64{ /*START PLAN MODIFIERS*/
										int64planmodifier.UseStateForUnknown(),
									}, /*END PLAN MODIFIERS*/
								}, /*END ATTRIBUTE*/
								// Property: Priority
								"priority": schema.Int64Attribute{ /*START ATTRIBUTE*/
									Description: "The purpose of the priority is to use a combination of the\\nmultiplex rate control algorithm and the QVBR capability of the\\nencoder to prioritize the video quality of some channels in a\\nmultiplex over others.  Channels that have a higher priority will\\nget higher video quality at the expense of the video quality of\\nother channels in the multiplex with lower priority.",
									Optional:    true,
									Computed:    true,
									Validators: []validator.Int64{ /*START VALIDATORS*/
										int64validator.Between(-5, 5),
									}, /*END VALIDATORS*/
									PlanModifiers: []planmodifier.Int64{ /*START PLAN MODIFIERS*/
										int64planmodifier.UseStateForUnknown(),
									}, /*END PLAN MODIFIERS*/
								}, /*END ATTRIBUTE*/
							}, /*END SCHEMA*/
							Description: "Statmux rate control settings.\nWhen this field is defined, ConstantBitrate must be undefined.",
							Optional:    true,
							Computed:    true,
							PlanModifiers: []planmodifier.Object{ /*START PLAN MODIFIERS*/
								objectplanmodifier.UseStateForUnknown


t id) async {
  WidgetsFlutterBinding.ensureInitialized();

  print('🔔 SCREEN OFF CALLBACK STARTED - ID: $id at ${DateTime.now()}');

  try {
    print('📱 Attempting to turn screen OFF...');
    await ScreenControl.toggleBoxScreenOff();
    print('📱 Screen turned OFF successfully');

    ToggleScreenFeature.recordEventExecution();
    print('📊 Event execution recorded');

    // Record execution for debugging
    await _recordAlarmExecution('SCREEN_OFF_BOX', id);

    print('✅ Screen OFF completed successfully - ID: $id');
  } catch (e, stackTrace) {
    print('💥 Screen OFF FAILED - ID: $id, Error: $e');
    print('Stack trace: $stackTrace');
  }

  print('✅ SCREEN OFF CALLBACK COMPLETED - ID: $id');
}

@pragma('vm:entry-point')
void screenOffTabletCallback(int id) async {
  WidgetsFlutterBinding.ensureInitialized();

  print('🔔 SCREEN OFF TABLET CALLBACK STARTED - ID: $id at ${DateTime.now()}');

  try {
    print('📱 Attempting to turn tablet screen OFF...');
    await ScreenControl.toggleTabletScreenOff();
    print('📱 Tablet screen turned OFF successfully');

    ToggleScreenFeature.recordEventExecution();
    print('📊 Event execution recorded');

    // Record execution for debugging
    await _recordAlarmExecution('SCREEN_OFF_TABLET', id);

    print('✅ Tablet screen OFF completed successfully - ID: $id');
  } catch (e, stackTrace) {
    print('💥 Tablet screen OFF FAILED - ID: $id, Error: $e');
    print('Stack trace: $stackTrace');
  }

  print('✅ SCREEN OFF TABLET CALLBACK COMPLETED - ID: $id');
}

// Helper function to record alarm executions for debugging
Future<void> _recordAlarmExecution(String type, int id) async {
  try {
    final prefs = await SharedPreferences.getInstance();
    final now = DateTime.now();
    final key = 'alarm_execution_${type}_$id';
    await prefs.setString(key, now.toIso8601String());
    print('📝 Recorded execution: $type ID:$id at $now');
  } catch (e) {
    print('❌ Failed to record execution: $e');
  }
}

@pragma('vm:entry-point')
class WorkManagerService {
  static bool _isInitialized = false;

  @pragma('vm:entry-point')
  static Future<void> initialize() async {
    if (_isInitialized) return;

    print('🚀 Initializing AlarmManager...');

    try {
      _isInitialized = await AndroidAlarmManager.initialize();

      if (!_isInitialized) {
        print('❌ AlarmManager initialization failed');
      } else {
        print('✅ AlarmManager initialized successfully');
      }
    } catch (e, stackTrace) {
      print('💥 AlarmManager initialization error: $e');
      print('Stack trace: $stackTrace');
    }
  }

  static int _alarmCounter = 0;

  static int _generateUniqueAlarmId() {
    final baseId = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    final uniqueId = (baseId + (++_alarmCounter)) % 2147483647;
    print('🔢 Generated alarm ID: $uniqueId (counter: $_alarmCounter)');
    return uniqueId;
  }

  @pragma('vm:entry-point')
  static Future<void> registerPrayerTask(String uniqueId, Map<String, dynamic> inputData, Duration initialDelay) async {
    print('📅 Starting to register prayer task - UniqueID: $uniqueId');

    try {
      final int alarmId = _generateUnique


file("Task.kt")
            }
            file("task.html")
          }
        }
      }
      file("build.gradle")
      file("settings.gradle")
    }
    fileTree.assertEquals(LightPlatformTestCase.getSourceRoot(), myFixture)
  }

  @Test
  fun `test open non dataset problem with language chosen by user without selected project`() {
    val request = HyperskillOpenStepRequest(step10960.id, FakeGradleBasedLanguage.id, true)
    assertThrows(IllegalStateException::class.java) {
      mockProjectOpener.open(HyperskillOpenInIdeRequestHandler, request)
    }
  }

  @Test
  fun `test open code problem without selected project in existing project`() {
    // set up existing project
    hyperskillCourseWithFiles {
      frameworkLesson(TEST_HYPERSKILL_PROJECT_NAME) {}
    }

    mockProjectOpener.open(HyperskillOpenInIdeRequestHandler, HyperskillOpenStepRequest(step2640.id, FakeGradleBasedLanguage.id))
    val fileTree = fileTree {
      dir(TEST_HYPERSKILL_PROJECT_NAME) {}
      dir(HYPERSKILL_TOPICS) {
        dir(step9455.title) {
          dir(THEORY) {
            dir("src") {
              file("Task.kt")
            }
            file("task.html")
          }
          dir(step525047.title) {
            file(AnswerTask.ANSWER_FILE_NAME)
            file("task.html")
          }
          dir(step2640.title) {
            dir("src") {
              file("Task.kt")
            }
            file("task.html")
          }
          dir(step2645.title) {
            dir("src") {
              file("Task.kt")
            }
            file("task.html")
          }
          dir(step2641.title) {
            dir("src") {
              file("Task.kt")
            }
            file("task.html")
          }
          dir(step2638.title) {
            dir("src") {
              file("Task.kt")
            }
            file("task.html")
          }
        }
      }
      file("build.gradle")
      file("settings.gradle")
    }
    fileTree.assertEquals(LightPlatformTestCase.getSourceRoot(), myFixture)
  }

  @Test
  fun `test unknown language`() {
    val unknownLanguage = "Unknown language"
    doLanguageValidationTest(unknownLanguage) {
      assertEquals(EduCoreBundle.message("hyperskill.unsupported.language", unknownLanguage), it.message)
    }
  }

  @Test
  fun `test language supported with plugin`() {
    doLanguageValidationTest("python") {
      assertTrue("actual: $it", it is PluginsRequired)
    }
  }

  @Test
  fun `test language not supported in IDE`() {
    val unsupportedLanguage = "Unsupported"
    doLanguageValidationTest(unsupportedLanguage) {
      val expectedMessage = EduCoreBundle.message(
        "rest.service.language.not.supported", ApplicationNamesInfo.getInstance().productName,
        unsupportedLanguage
      )
      assertEquals(expectedMessage, it.message)
    }
  }

  private fun doLanguageValidationTest(language: String, checkError: (CourseValidationResult) -> Unit) {
    mockConnector.configureFromCourse(testRootDisposable, hyperskillCourse(projectId = null) {
      section(HYPERSKILL_TOPICS) {
        lesson(TOPIC_NAME) {
          codeTask(stepId = 4) {
            taskFile("task.txt", "file text")
          }
        }
      }
    })

    mockProjectOpener.open(HyperskillOpenInIdeRequestHandler, HyperskillOpenStepWithProjectRequest(1, 4, language)).onError {
      checkError(it)


import os
import sys
import torch
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from pylab import mpl

# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]

# 添加项目根目录到路径
sys.path.append(str(Path(__file__).parent.parent.parent))

from LM_wm.models.bev_encoder import WeightedMSELoss

def create_test_image():
    """创建一个测试图像，包含深灰色边界、浅灰色道路和红蓝色车辆标记"""
    # 创建深灰色背景
    test_image = np.ones((224, 224, 3), dtype=np.float32) * 0.47

    # 添加浅灰色道路区域
    road_mask = np.zeros((224, 224), dtype=bool)
    road_mask[70:154, :] = True
    test_image[road_mask] = 0.65

    # 添加红色车辆标记
    red_mask = np.zeros((224, 224), dtype=bool)
    for x in range(50, 200, 30):
        red_mask[100:110, x:x+10] = True
    test_image[red_mask, 0] = 0.85  # 红色通道
    test_image[red_mask, 1:] = 0.2   # 绿色和蓝色通道

    # 添加蓝色车辆标记
    blue_mask = np.zeros((224, 224), dtype=bool)
    for x in range(65, 185, 30):
        blue_mask[115:125, x:x+10] = True
    test_image[blue_mask, 2] = 0.85  # 蓝色通道
    test_image[blue_mask, :2] = 0.2  # 红色和绿色通道

    # 转换为PyTorch张量
    tensor_image = torch.from_numpy(test_image).permute(2, 0, 1)

    # 返回图像及各区域掩码
    return tensor_image, road_mask, red_mask, blue_mask

def test_region_detection():
    """测试区域检测是否准确"""
    print("====== 测试区域检测准确性 ======")

    # 创建测试图像和已知掩码
    test_image, road_mask, red_mask, blue_mask = create_test_image()
    vehicle_mask = np.logical_or(red_mask, blue_mask)
    boundary_mask = ~road_mask

    # 准备为WeightedMSELoss使用
    target_batch = test_image.unsqueeze(0)

    # 使用损失函数的区域检测逻辑
    with torch.no_grad():
        # 检测深灰色边界区域
        pixel_mean = torch.mean(target_batch, dim=1, keepdim=True)
        pixel_std = torch.std(target_batch, dim=1, keepdim=True)

        detected_boundary = torch.logical_and(
            pixel_mean < 0.5,  # 较暗
            pixel_std < 0.03  # 颜色均匀
        ).float().squeeze()

        # 检测红色区域
        is_red = torch.logical_and(
            target_batch[:, 0] > 0.6,
            torch.max(target_batch[:, 1:], dim=1)[0] < 0.4
        ).float().squeeze()

        # 检测蓝色区域
        is_blue = torch.logical_and(
            target_batch[:, 2] > 0.6,
            torch.max(target_batch[:, :2], dim=1)[0] < 0.4
        ).float().squeeze()

        # 合并车辆区域
        detected_vehicle = torch.logical_or(is_red, is_blue).float()

        # 道路区域（非边界区域）
        detected_road = 1 - detected_boundary

    # 计算准确率和重叠度
    boundary_accuracy = calculate_iou(detected_boundary.numpy() > 0.5, boundary_mask)
    vehicle_accuracy = calculate_iou(detected_vehicle.numpy() > 0.5, vehicle_mask)
    road_accuracy = calculate_iou(detected_road.numpy() > 0.5, road_mask)

    print(f"边界区域检测 IoU: {boundary_accuracy:.4f}")
    print(f"车辆标记区域检测 IoU: {vehicle_accuracy:.4f}")
    print(f"道路区域检测 IoU: {road_accuracy:.4f}")

    # 可视化结果
    visualize_detection_results(
        test_image.permute(1, 2, 0).numpy(),
        detected_boundary.numpy(),
        detected_vehicle.numpy(),
        detected_road.numpy(),
        boundary_mask,
        vehicle_mask,
        road_mask
    )

    return boundary_accuracy, vehicle_accuracy, road_accuracy

def calculate_iou(detected_mask, true_mask):
    """计算交并比 (IoU)"""
    intersection = np.logical_and(detected_mask, true_mask).sum()
    union = np.logical_or(detected_mask, true_mask).sum()
    iou = intersection / union if union > 0 else 0
    return iou

def visualize_detection_results(original_img, detected_boundary, detected_vehicle,
                               detected_road, true_boundary, true_vehicle, true_road):
    """可视化检测结果和真实掩码的比较"""
    fig, axes = plt.subplots(3, 3, figsize=(15, 15))

    # 第一行: 原始图像和生成的掩码
    axes[0, 0].imshow(original_img)
    axes[0, 0].set_title('原始测试图像')
    axes[0, 0].axis('off')

    # 创建掩码可视化图像
    mask_viz = np.zeros(original_img.shape, dtype=np.float32)
    mask_viz[true_boundary, :] = [1.0, 0.0, 0.0]  # 边界区域 - 红色
    road_without_vehicle = np.logical_and(true_road, np.logical_not(true_vehicle))
    mask_viz[road_without_vehicle, :] = [0.0, 1.0, 0.0]  # 道路区域 - 绿色
    mask_viz[true_vehicle, :] = [0.0, 0.0, 1.0]  # 车辆区域 - 蓝色

    axes[0, 1].imshow(mask_viz)
    axes[0, 1].set_title('真实区域掩码')
    axes[0, 1].axis('off')

    # 创建检测掩码可视化
    detected_viz = np.zeros(original_img.shape, dtype=np.float32)
    detected_viz[detected_boundary > 0.5, :] = [1.0, 0.0, 0.0]  # 边界区域 - 红色
    detected_road_only


2FE553FA448 (PointerEventData_tC6C1BEE9D4C8755A31DA7FC0C9A1F28A36456954 * __this, const RuntimeMethod* method)
{
	static bool s_Il2CppMethodInitialized;
	if (!s_Il2CppMethodInitialized)
	{
		il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
		s_Il2CppMethodInitialized = true;
	}
	{
		// get { return pointerPressRaycast.module == null ? null : pointerPressRaycast.module.eventCamera; }
		RaycastResult_t9EFDE24B29650BD6DC8A49D954A3769E17146BCE  L_0;
		L_0 = PointerEventData_get_pointerPressRaycast_m3C5785CD2C31F91C91D6F1084D2EAC31BED56ACB_inline(__this, /*hidden argument*/NULL);
		BaseRaycaster_tBC0FB2CBE6D3D40991EC20F689C43F76AD82A876 * L_1 = L_0.get_module_1();
		IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
		bool L_2;
		L_2 = Object_op_Equality_m6D7EBC0E6D7E0CE1E9671D21DE14C9158AFB88B2(L_1, (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A *)NULL, /*hidden argument*/NULL);
		if (L_2)
		{
			goto IL_0024;
		}
	}
	{
		RaycastResult_t9EFDE24B29650BD6DC8A49D954A3769E17146BCE  L_3;
		L_3 = PointerEventData_get_pointerPressRaycast_m3C5785CD2C31F91C91D6F1084D2EAC31BED56ACB_inline(__this, /*hidden argument*/NULL);
		BaseRaycaster_tBC0FB2CBE6D3D40991EC20F689C43F76AD82A876 * L_4 = L_3.get_module_1();
		Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_5;
		L_5 = VirtFuncInvoker0< Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * >::Invoke(18 /* UnityEngine.Camera UnityEngine.EventSystems.BaseRaycaster::get_eventCamera() */, L_4);
		return L_5;
	}

IL_0024:
	{
		return (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C *)NULL;
	}
}
// UnityEngine.GameObject UnityEngine.EventSystems.PointerEventData::get_pointerPress()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * PointerEventData_get_pointerPress_mB55C5528AF445DB7B912086E43F0BCD9CDFF409C (PointerEventData_tC6C1BEE9D4C8755A31DA7FC0C9A1F28A36456954 * __this, const RuntimeMethod* method)
{
	{
		// get { return m_PointerPress; }
		GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_0 = __this->get_m_PointerPress_3();
		return L_0;
	}
}


      j3c13 => "--:-:-:-:1 \@!P1 $convert loadA1, loadA4.H1;\n",
        j3c17 => "--:-:-:-:1 \@!P1 $convert loadA0, loadA4.H0;\n",

        j4c5  => "--:-:-:-:1 \@!P1 $convert loadB3, loadB5.H1;\n",
        j4c9  => "--:-:-:-:1 \@!P1 $convert loadB2, loadB5.H0;\n",
        j4c13 => "--:-:-:-:1 \@!P1 $convert loadB1, loadB4.H1;\n",
        j4c17 => "--:-:-:-:1 \@!P1 $convert loadB0, loadB4.H0;\n",

        j5c5  => "02:-:-:-:1  \@P1 $convert loadA3, loadA1.H1;\n",
        j5c9  => "--:-:2:-:1  \@P1 $convert loadA2, loadA1.H0;\n",
        j5c13 => "--:-:-:-:1  \@P1 $convert loadA1, loadA0.H1;\n",
        j5c17 => "--:-:3:-:1  \@P1 $convert loadA0, loadA0.H0;\n",

        j5c29 => "02:-:-:-:1  \@P0 STS [writeS + 4x<3*128>], loadA3;\n",
        j5c31 => "--:-:-:-:1  \@P0 STS [writeS + 4x<2*128>], loadA2;\n",
        j5c33 => "04:-:-:-:1  \@P0 STS [writeS + 4x<1*128>], loadA1;\n",
        j5c35 => "--:-:-:-:1  \@P0 STS [writeS + 4x<0*128>], loadA0;\n",

        j6c5  => "08:-:-:-:1  \@P1 $convert loadB3, loadB1.H1;\n",
        j6c9  => "--:-:2:-:1  \@P1 $convert loadB2, loadB1.H0;\n",
        j6c13 => "--:-:3:-:1  \@P1 $convert loadB1, loadB0.H1;\n",
        j6c17 => "--:-:4:-:1  \@P1 $convert loadB0, loadB0.H0;\n",

        j6c29 => "02:-:-:-:1  \@P0 STS [writeS + 4x<11*128>], loadB3;\n",
        j6c31 => "--:-:-:-:1  \@P0 STS [writeS + 4x<10*128>], loadB2;\n",
        j6c33 => "04:-:-:-:1  \@P0 STS [writeS + 4x< 9*128>], loadB1;\n",
        j6c35 => "08:-:-:-:1  \@P0 STS [writeS + 4x< 8*128>], loadB0;\n",

        j5c46 => "--:-:-:-:1  \@P2 IADD   trackA0.CC, trackA0, 2x<16>;\n",
        j5c54 => "--:-:-:-:1  \@P2 IADD.X trackA1,    trackA1, RZ;\n",

        j6c46 => "10:-:-:-:1  \@P3 IADD   trackB0.CC, trackB0, 2x<16>;\n",
        j6c54 => "--:-:-:-:1  \@P3 IADD.X trackB1,    trackB1, RZ;\n",

        j7c63 => "--:-:-:Y:5  \@P0 BRA.U LOOP;\n",
            ) :
            (
        j0c7  => "--:-:-:-:1      ISETP.GE.AND P3, PT, k, 16, P6;\n",
        j0c8  => "--:-:-:-:


tum通常在高曲率区域提供更好的加速效果，而ASGD则通过平均历史梯度来平滑梯度更新，减少噪声的影响。

![alt text](assest/神经网络的优化器（四）ASGD/0.png)

## 参考
[1] [Acceleration of stochastic approximation by averaging](https://dl.acm.org/doi/10.1137/0330046)

## 欢迎关注我的GitHub和微信公众号，来不及解释了，快上船！

[GitHub: LLMForEverybody](https://github.com/luhengshiwo/LLMForEverybody)

仓库上有原始的Markdown文件，完全开源，欢迎大家Star和Fork！大模型训练框架（二）FSDP

Fully Sharded Data Parallel (FSDP)[1](#refer-anchor-1) 是一种数据并行方法，最早是在2021年由 FairScale-FSDP 提出的，并在后续被集成到了 PyTorch 1.11 版本中。

FSDP 可以看作是微软 Deepspeed 框架中提出的三种级别的 ZERO 算法中的 `ZERO-3` 的实现。它通过将模型的梯度、优化器状态和参数进行分片操作，使得每个 GPU 只存储部分参数信息，从而优化了资源的利用和提高了训练效率。此外，FSDP 也与包括 Tensor 实现、调度器系统和 CUDA 内存缓存分配器在内的几个关键 PyTorch 核心组件紧密协同设计，以提供非侵入式用户体验和高训练效率。

## 1. DP & DDP & ZeRO

***DP (Data Parallel)***：（狭义的）数据并行DP是最简单的并行策略了，它是将模型的副本分布到单机多卡上，每个卡都有一个模型副本，然后每个卡都会处理不同的数据子集。在每个训练步骤结束时，所有卡都会同步模型参数。

***DDP (Distributed Data Parallel)***随着数据量的增大，单机多卡的训练效率会变得很低，这时候就需要使用分布式数据并行DDP。DDP是将模型的副本分布到多台机器上，每台机器上有多个卡，每个卡都有一个模型副本。在每个训练步骤结束时，所有卡都会同步模型参数。

***ZeRO***，全称为"Zero Redundancy Optimizer"，是由微软研究院提出的一种用于优化分布式训练的内存管理技术。它旨在解决在大规模分布式训练中遇到的内存瓶颈问题，特别是在训练大型


const staking_contract = cfx.InternalContract('Staking');
// deposit some amount of tokens
staking_contract.deposit(your_number_of_tokens).sendTransaction({
  from: account,
}).confirmed();

// withdraw some amount of tokens
staking_contract.withdraw(your_number_of_tokens).sendTransaction({
  from: account,
}).confirmed();

// lock some tokens until some block number
staking_contract.voteLock(your_number_of_tokens, your_unlock_block_number).sendTransaction({
  from: account,
}).confirmed();
```

Conflux v2 hard-fork has introduced three new internal contracts: `ConfluxContext`, `PoSRegister`, `CrossSpaceCall`

## ConfluxContext

This contract can be used to query Conflux network info in contract including:

* `epochNumber` - Current epoch number
* `posHeight` - Current block height of PoS chain
* `finalizedEpochNumber` - The latest finalized (by PoS chain) PoW epoch number

`ConfluxContext`'s hex40 contract address is `0x0888000000000000000000000000000000000004`

```js
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.15;

interface ConfluxContext {
    /*** Query Functions ***/
    /**
     * @dev get the current epoch number
     * @return the current epoch number
     */
    function epochNumber() external view returns (uint256);
    /**
     * @dev get the height of the referred PoS block in the last epoch
`    * @return the current PoS block height
     */
    function posHeight() external view returns (uint256);
    /**
     * @dev get the epoch number of the finalized pivot block.
     * @return the finalized epoch number
     */
    function finalizedEpochNumber() external view returns (uint256);
}

```

## PoSRegister

This contract is used let user participate in PoS chain. If anyone want to become a PoS node, he need to interact with this contract. This contract provide serveral methods to increase or decrease PoS votes:

* `register` - Regist in PoS chain to become a PoS node
* `increaseStake` - Increase PoS stake
* `retire` - Decrease PoS stake

Also several methods to query one account's PoS info:

* `getVotes` - Query one account's votes info, will return `totalStakedVotes` and `totalUnlockedVotes`
* `identifierToAddress` - Query one PoS account's binded PoW address
* `addressToIdentifier` - Query one PoW account's binded PoS address

`PoSRegister`'s hex40 contract address is `0x0888000000000000000000000000000000000005`

```js
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

interface PoSRegister {
    /**
     * @dev Register PoS account
     * @param indentifier - PoS account address to register
     * @param votePower - votes count
     * @param blsPubKey - BLS public key
     * @param vrfPubKey - VRF public key
     * @param blsPubKeyProof - BLS public key's proof of legality, used to against some attack, generated by conflux-rust fullnode
     */
    function register(
        bytes32 indentifier,
        uint64 votePower,
        bytes calldata blsPubKey,
        bytes calldata vrfPubKey,
        bytes[2] calldata blsPubKeyProof
    ) external;

    /**
     * @dev Increase specified number votes for msg.sender
     * @param votePower - count of votes to increase
     */
    function increaseStake(uint64 votePower) external;

    /**
     * @dev Retire specified number votes for msg.sender
     * @param votePower - count of votes to retire
     */
    function retire(uint64 votePower) external;

    /**
     * @dev Query PoS account's lock info. Include "totalStakedVotes" and "totalUnlockedVotes"
     * @param identifier - PoS address
     */
    function getVotes(bytes32 identifier) external view returns (uint256, uint256);

    /**
     * @dev Query the PoW address binding with specified PoS address
     * @param identifier - PoS address
     */
    function identifierToAddress(bytes32 identifier) exte


rt';
import 'package:lichess_mobile/src/widgets/haptic_refresh_indicator.dart';
import 'package:lichess_mobile/src/widgets/list.dart';
import 'package:lichess_mobile/src/widgets/misc.dart';
import 'package:lichess_mobile/src/widgets/platform.dart';
import 'package:lichess_mobile/src/widgets/platform_alert_dialog.dart';
import 'package:url_launcher/url_launcher.dart';

class HomeTabScreen extends ConsumerStatefulWidget {
  const HomeTabScreen({super.key, this.editModeEnabled = false});

  final bool editModeEnabled;

  static Route<dynamic> buildRoute(BuildContext context, {bool editModeEnabled = false}) {
    return buildScreenRoute(context, screen: HomeTabScreen(editModeEnabled: editModeEnabled));
  }

  @override
  ConsumerState<HomeTabScreen> createState() => _HomeScreenState();
}

class _IsEditingHome extends InheritedWidget {
  const _IsEditingHome({required super.child, required this.isEditingWidgets});

  final bool isEditingWidgets;

  @override
  bool updateShouldNotify(_IsEditingHome oldWidget) {
    return isEditingWidgets != oldWidget.isEditingWidgets;
  }

  static _IsEditingHome? maybeOf(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<_IsEditingHome>();
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<bool>('isEditingWidgets', isEditingWidgets));
  }
}

class _HomeScreenState extends ConsumerState<HomeTabScreen> {
  final _refreshKey = GlobalKey<RefreshIndicatorState>();

  DateTime? _focusLostAt;

  bool wasOnline = true;
  bool hasRefreshed = false;

  @override
  void initState() {
    super.initState();

    showWelcomeMessage();
  }

  Future<bool> shouldDisplayWelcomeMessage() async {
    if (LichessBinding.instance.sharedPreferences.getBool('app_welcome_message_shown') == true) {
      return false;
    }

    if (ref.read(authSessionProvider) != null) {
      return false;
    }

    final hasPlayedGames =
        await (await ref.read(gameStorageProvider.future)).count(userId: null) > 0;

    return !hasPlayedGames;
  }

  Future<void> showWelcomeMessage() async {
    final prefs = LichessBinding.instance.sharedPreferences;
    if (await shouldDisplayWelcomeMessage()) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        final context = ref.read(currentNavigatorKeyProvider).currentContext;
        if (context == null || !context.mounted) return;
        showDialog<void>(
          context: context,
          builder: (context) => AlertDialog.adaptive(
            content: Container(
              color:
                  DialogTheme.of(context).backgroundColor ??
                  ColorScheme.of(context).surfaceContainerHigh,
              padding: const EdgeInsets.all(8.0),
              child: Text.rich(
                textAlign: TextAlign.center,
                TextSpan(
                  children: [
                    TextSpan(
                      text: '${context.l10n.mobileWelcomeToLichessApp}\n\n',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    TextSpan(
                      text: context.l10n.


信息所采取的措施等实际情况进行审查认定。

前款所列人员不能提供勤勉尽责的相应证据，仅以其不从事日常经营管理、无相关职业背景和专业知识、相信发行人或者管理层提供的资料、相信证券服务机构出具的专业意见等理由主张其没有过错的，人民法院不予支持。

第十五条 发行人的董事、监事、高级管理人员依照证券法第八十二条第四款的规定，以书面方式发表附具体理由的意见并依法披露的，人民法院可以认定其主观上没有过错，但在审议、审核信息披露文件时投赞成票的除外。

第十六条 独立董事能够证明下列情形之一的，人民法院应当认定其没有过错：

（一）在签署相关信息披露文件之前，对不属于自身专业领域的相关具体问题，借助会计、法律等专门职业的帮助仍然未能发现问题的；

（二）在揭露日或更正日之前，发现虚假陈述后及时向发行人提出异议并监督整改或者向证券交易场所、监管部门书面报告的；

（三）在独立意见中对虚假陈述事项发表保留意见、反对意见或者无法表示意见并说明具体理由的，但在审议、审核相关文件时投赞成票的除外；

（四）因发行人拒绝、阻碍其履行职责，导致无法对相关信息披露文件是否存在虚假陈述作出判断，并及时向证券交易场所、监管部门书面报告的；

（五）能够证明勤勉尽责的其他情形。

独立董事提交证据证明其在履职期间能够按照法律、监管部门制定的规章和规范性文件以及公司章程的要求履行职责的，或者在虚假陈述被揭露后及时督促发行人整改且效果较为明显的，人民法院可以结合案件事实综合判断其过错情况。

外部监事和职工监事，参照适用前两款规定。

第十七条 保荐机构、承销机构等机构及其直接责任人员提交的尽职调查工作底稿、尽职调查报告、内部审核意见等证据能够证明下列情形的，人民法院应


ting the client with desired parameters.
 */
@Suppress("unused")
class ZHttpClient private constructor(builder: Builder) {
    private var baseUrl = builder.getBaseUrl()
    private var connectionTimeoutMs = builder.getConnectionTimeout()
    private var readTimeoutMs = builder.getReadTimeout()
    private var defaultHeaders = builder.getDefaultHeaders()
    private val filesBufferSize = builder.getBufferSize()
    private val gson = Gson()
    val requestRetryMechanism = builder.getRequestRetryMechanism()
    var allowLogging = builder.getAllowLogging()

    /**
     * Get the base URL of the client.
     *
     * @return Base URL as a String.
     */
    internal fun getBaseUrl(): String {
        return baseUrl
    }

    /**
     * Get the connection timeout in milliseconds.
     *
     * @return Connection timeout in milliseconds.
     */
    internal fun getConnectionTimeout(): Int {
        return connectionTimeoutMs
    }

    /**
     * Get the read timeout in milliseconds.
     *
     * @return Read timeout in milliseconds.
     */
    internal fun getReadTimeout(): Int {
        return readTimeoutMs
    }

    /**
     * Get the default headers set for the client.
     *
     * @return List of default headers.
     */
    internal fun getDefaultHeaders(): List<Header> {
        return defaultHeaders
    }

    /**
     * Get the buffer size for file operations.
     *
     * @return Buffer size as an integer.
     */
    internal fun getBufferSize(): Int {
        return filesBufferSize
    }

    /**
     * Get the request retry mechanism.
     *
     * @return RequestRetryMechanism instance.
     */
    internal fun getRequestRetryMechanism(): RequestRetryMechanism? {
        return requestRetryMechanism
    }

    /**
     * Get the Gson instance used for JSON serialization and deserialization.
     *
     * @return Gson instance.
     */
    fun getGsonInstance(): Gson {
        return gson
    }

    /**
     * Remove all default headers from the client.
     */
    fun removeDefaultHeaders() {
        defaultHeaders = emptyList()
    }

    /**
     * Set new default headers for the client.
     *
     * @param headers List of new default headers.
     */
    fun setDefaultHeaders(headers: List<Header>) {
        defaultHeaders = headers
    }

    /**
     * Initiate a GET request asynchronously.
     *
     * @param endpoint Endpoint to append to the base URL.
     * @param queries List of query parameters to include in the URL.
     * @param headers List of headers for the request.
     * @param onComplete Callback for handling the HTTP response.
     * @return Job for the HTTP response or null.
     */
    inline fun <reified T> get(
        endpoint: String,
        queries: List<Query>? = null,
        headers: List<Header>? = null,
        noinline onComplete: (success: Response<T>?, failure: Exception?) -> Unit
    ): Job {
        return ZGet(this).processGet(
            endpoint, queries, headers, onComplete
        )


lock().unwrap(), 1);
        assert_eq!(recv(&mut rx).await, Some(1));
        assert_eq!(*done.lock().unwrap(), 2);
        assert_eq!(recv(&mut rx).await, None);
        assert_eq!(*done.lock().unwrap(), 3);
        let _ = send.await;
    }

    #[tokio::test]
    async fn send_errors_when_rx_dropped() {
        let (tx, rx) = channel::<u8>();
        drop(rx);
        tx.send(0).await.expect_err("rx half dropped");
    }
}
// Copyright 2016 <NAME>, <NAME> and <NAME>.
// See the README.md file at the top-level directory of this
// distribution.
//
// Licensed under the MIT license <LICENSE or
// http://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unused)]
//! The ESALP Scheduler™
//!
//! Round robin scheduler and threading

use alloc::collections::VecDeque;

use interrupts::{Context, SLEEP_INT};
use smp::current;

use self::thread::{KThread, State, TICKS};

mod thread;

/// Basic round-robin scheduler
pub struct Scheduler {
    // State::Ready
    threads: VecDeque<KThread>,
    // State::Sleeping -- delta queue
    sleeping: VecDeque<KThread>,
    // None => current == idle
    current: Option<KThread>,
    idle: KThread,
}

impl Scheduler {
    pub fn new() -> Scheduler {
        unsafe { Scheduler {
            threads: VecDeque::new(),
            sleeping: VecDeque::new(),
            current: Some(KThread::main()),
            idle: KThread::idle(),
        }}
    }
}

/// Create a new thread that will start with the `start` function
pub fn add(start: extern "C" fn()) -> Result<(), &'static str>{
    let thread = KThread::new(start)?;

    current().sched.lock().threads.push_back(thread);
    Ok(())
}

/// Yield the thread that `current_stack` belongs to to a new thread.
///
/// If there are no available threads then the idle thread will be run.
pub fn sched_yield(current_stack: &'static Context) -> &'static Context {
    let mut lock = current().sched.lock();
    let &mut Scheduler {
        ref mut threads,
        ref mut sleeping,
        ref mut current,
        ref mut idle,
    } = &mut *lock;

    let mut current_thread = current.take().unwrap();
    let mut next_thread = threads.pop_front();

    let ret = {
        let next = next_thread.as_mut().unwrap_or(idle);
        current_thread.swap(current_stack, next)
    };

    threads.push_back(current_thread);

    *current = next_thread;
    ret
}

/// Make the current thread sleep for `time` quanta
///
/// The thread is not guaranteed to run after `time` is complete, it will simply
/// be resumed.
/// `time` must not be zero
pub fn sched_sleep(current_stack: &'static Context, time: u8) -> &'static Context {
    let mut lock = current().sched.lock();
    let &mut Scheduler {
        ref mut threads,
        ref mut sleeping,
        ref mut current,
        ref mut idle,
    } = &mut *lock;

    // first, swap out with a new thread
    let mut current_thread = current.take().unwrap();
    let mut next_thread = threads.pop_front();

    let ret = {
        let next = next_thread.as_mut().unwrap_or(idle);
        current_thread.swap(current_stack, next)
    };
    *current = next_thread;

    // now put it in the sleeping list
    current_thread.state = State::Sleeping;
    current_thread.quanta = time;

    // calculate index fo


PI使用价格。

#### 核心功能

*   **高效长文本处理：** 通过DeepSeek Sparse Attention (DSA) 机制，优化了对长文本的理解和生成能力，大幅提高了处理效率。
*   **成本效益优化：** 显著降低了模型推理的计算和内存成本，并同步削减了API价格，使其成为经济实惠的AI解决方案。
*   **性能维持：** 在多个公开评测集上，DeepSeek-V3.2-Exp 的性能与DeepSeek-V3.1-Terminus 基本持平，显示出在效率提升的同时保持了高准确性。
*   **多模态能力（隐含）：** 结合DeepSeek AI工具集，模型具备AI写作、AI编程、AI聊天助手等多种AI应用能力。

#### 技术原理

DeepSeek-V3.2-Exp 的核心技术创新在于 **DeepSeek Sparse Attention (DSA)** 机制，该机制通过以下组件实现细粒度稀疏注意力：

*   **闪电索引器 (Lightning Indexer)：** 作为DSA的核心，它计算查询标记与前序标记之间的索引分数，快速识别对查询标记最重要的关键值条目。
*   **细粒度标记选择：** 基于闪电索引器提供的索引分数，模型选择前k个关键值条目进行注意力计算，从而减少了不必要的计算开销，提升了推理速度和效率。
*   **Multi-Layer Attention (MLA) 架构：** DSA 在 MLA 架构下实现，并采用 Multi-Query Attention (MQA) 模式，允许每个关键值条目在多个查询之间共享，进一步提高了计算效率。
*   **持续训练与优化：** 模型从 DeepSeek-V3.1-Terminus 检查点开始，经过“密集热身”和“稀疏训练”两个阶段，对闪电索引器和整体模型进行了优化，以适应稀疏注意力模式。

#### 应用场景

*   **长文本内容生成与分析：** 适用于需要处理大量文本数据的任务，如长篇报告撰写、文档摘要、代码生成与分析、合同审查等。
*   **智能客服与问答系统：** 能够更高效地处理包含复杂或长对话历史的客户咨询，提供更精准的回答。
*   **AI编程辅助：** 利用其长文本处理能力，辅助开发者进行代码编写、错误排查和项目文档生成。
*   **教育与研�


作用、退相干時間等方面還存在一定的限制，這使得QAOA在大規模問題上的應用受到挑戰。隨著量子硬體的進步，QAOA的應用將會得到更好的發展。

2. **經典優化的困難**：
   - QAOA需要使用經典優化算法來調整量子電路的參數。對於某些問題，經典優化可能會陷入局部最小值，無法找到全局最優解。因此，如何設計更加高效和穩定的經典優化算法仍然是一個挑戰。

3. **參數選擇和收斂速度**：
   - QAOA的效果依賴於選擇合適的參數。不同的參數選擇會影響到優化結果的質量和演化過程的收斂速度。尋找最佳參數配置是QAOA算法的一個挑戰。

4. **量子錯誤糾正與噪聲控制**：
   - 當前的量子硬體面臨噪聲和退相干的問題，這可能會影響QAOA的準確性和效果。隨著量子錯誤糾正技術的進步，QAOA有可能在未來的量子計算機上實現更高效的運行。

#### **結論**

QAOA作為一種量子近似優化算法，展現了在解決組合優化問題方面的巨大潛力。它將量子計算與經典優化相結合，使得量子計算能夠在NISQ設備上發揮實際應用。儘管目前還面臨量子硬體、經典優化算法和噪聲控制等挑戰，但隨著量子技術的發展，QAOA有望成為解決現實世界中複雜優化問題的強大工具。### 工業界的量子計算實踐

量子計算在科研領域的理論突破之外，正在快速進入工業界，並逐步應用於現實世界的挑戰。越來越多的企業和研究機構正在積極探索量子計算的商業應用，並投入大量資源來克服量子計算的現實障礙。以下是一些量子計算在工業界的實踐和應用範疇。

---

### 1. **量子計算在製造業的應用**

#### (1) **材料科學與新材料發現**
量子計算在材料科學領域的應用主要體現在模擬和設計新型材料。由於量子力學的複雜性，經典計算方法無法有效地模擬原子級別的互動。量子計算可以在分子和原子層面提供


        # 检查公式长度
        if len(formula) > self.max_formula_length:
            result['is_safe'] = False
            result['errors'].append(f"公式长度超过限制 ({len(formula)} > {self.max_formula_length})")
            result['security_score'] -= 30

        # 检查危险函数 - 宽松版本
        formula_upper = formula.upper()
        for dangerous_func in self.dangerous_functions:
            if dangerous_func in formula_upper:
                # 只记录警告，不阻止执行
                result['warnings'].append(f"检测到潜在风险函数: {dangerous_func}")
                result['security_score'] -= 10  # 减少扣分

        # 检查嵌套层级
        nesting_level = self._calculate_nesting_level(formula)
        if nesting_level > self.max_nesting_level:
            result['warnings'].append(f"嵌套层级过深: {nesting_level}")
            result['security_score'] -= 10

        # 检查可疑模式
        suspicious_patterns = {
            '../': '相对路径遍历',
            '~/': '用户目录访问',
            '/etc/': '系统配置访问',
            '/var/': '系统变量访问',
            'C:\\': 'Windows系统盘访问',
            'D:\\': 'Windows其他盘访问',
            'javascript:': 'JavaScript代码注入',
            'vbscript:': 'VBScript代码注入'
        }

        for pattern, description in suspicious_patterns.items():
            if pattern.lower() in formula.lower():
                result['warnings'].append(f"检测到可疑模式: {description}")
                result['security_score'] -= 15

        # 检查大数组操作
        array_patterns = re.findall(r'([A-Z]+\d+:[A-Z]+\d+)', formula)
        for pattern in array_patterns:
            if self._estimate_array_size(pattern) > self.max_array_size:
                result['warnings'].append(f"数组范围过大: {pattern}")
                result['security_score'] -= 20

        # 确定风险级别
        if result['security_score'] >= 80:
            result['risk_level'] = 'low'
        elif result['security_score'] >= 60:
            result['risk_level'] = 'medium'
        elif result['security_score'] >= 40:
            result['risk_level'] = 'high'
        else:
            result['risk_level'] = 'critical'
            result['is_safe'] = False

        return result

    def _calculate_nesting_level(self, formula: str) -> int:
        """计算嵌套层级"""
        max_level = 0
        current_level = 0

        for char in formula:
            if char == '(':
                current_level += 1
                max_level = max(max_level, current_level)
            elif char == ')':
                current_level -= 1

        return max_level

    def _estimate_array_size(self, range_pattern: str) -> int:
        """估算数组大小"""
        try:
            # 解析范围如 A1:Z100
            start, end = range_pattern.split(':')

            # 提取列和行
            start_col = re.match(r'([A-Z]+)', start).group(1)
            start_row = int(re.search(r'(\d+)', start).group(1))
            end_col = re.match(r'([A-Z]+)', end).group(1)
            end_row = int(re.search(r'(\d+)', end).group(1))

            # 计算列数（简化计算）
            col_count = ord(end_col[-1]) - ord(start_col[-1]) + 1
            row_count = end_row - start_row + 1

            return col_count * row_count
        except:
            return 0

class FormulasToolsManager:
    """Excel 公式工具管理器 - 增强版"""

    def __init__(self):
        self.security_manager = FormulasSecurityManager()
        self.template_manager = FormulaTemplateManager()
        self.intelligent_recommender = IntelligentRecommender(self.template_manager)
        self.multi_workbook_processor = MultiWorkbookProcessor()
        self.performance_analyzer = PerformanceAnalyzer()
        self.temp_dir = Path(tempfile.gettempdir()) / "chatexcel_formulas"
        self.temp_dir.mkdir(exist_ok=True)

    def _check_formulas_availability(self) -> bool:
        """检查 formulas 库是否可用"""
        if formulas is None:
            logger.error("formulas 库未安装或导入失败")
            return False
        return True

    def parse_formula(self, formula: str, validate_security: bool = False,
                     include_recommendations: bool = False,
                     analyze_performance: bool = False) -> Dict[str, Any]:
        """解析 Excel 公式 - 增强版

        Args:
            formula: Excel 公式字符串
            validate_security: 是否进行安全验证
            include_recommendations: 是否包含优化建议
            analyze_performance: 是否进行性能分析

        Returns:
            解析结果字典
        """
        if not self._che


  const agents = await Promise.all([
      mesh.neural.spawnAgent({ type: 'mlp', task: 'classification' }),
      mesh.neural.spawnAgent({ type: 'lstm', task: 'sequence_processing' }),
      mesh.neural.spawnAgent({ type: 'cnn', task: 'image_recognition' })
    ]);

    console.log(`Spawned ${agents.length} agents`);

    // Start distributed training
    const training = await mesh.neural.startTraining({
      agents: agents.map(a => a.id),
      dataset: { source: './training_data.json' },
      config: {
        epochs: 50,
        strategy: TrainingStrategy.Federated
      }
    });

    // Monitor training progress
    const trainingMonitor = setInterval(async () => {
      const progress = await mesh.neural.getTrainingStatus(training.id);
      console.log(`Training progress: ${(progress.progress * 100).toFixed(1)}%`);

      if (progress.status === 'completed') {
        clearInterval(trainingMonitor);
        console.log('Training completed!');
      }
    }, 5000);

    // Connect to mesh network
    await mesh.mesh.connectPeer('/ip4/bootstrap.synaptic-mesh.net/tcp/8080/p2p/12D3...');

    // Submit some transactions
    await mesh.dag.submitTransaction({
      type: 'agent_result',
      data: JSON.stringify({ accuracy: 0.95 })
    });

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await mesh.disconnect();
  }
}

completeExample();
```

This API reference provides comprehensive coverage of all Synaptic Neural Mesh interfaces, enabling developers to build sophisticated distributed neural applications.

**Next**: Check out our [Integration Examples](../examples/integrations/) for real-world usage patterns.# Gym Track Database Queries

## Running SQL Queries

### User Management

```bash
# Register a new user
psql -U rsstdd -d gym_track -f ./queries/users/user_registration.sql

# Authenticate a user
psql -U rsstdd -d gym_track -f ./queries/users/user_authentication.sql

# Get user profile
psql -U rsstdd -d gym_track -f ./queries/users/get_user_profile.sql

# Update user profile
psql -U rsstdd -d gym_track -f ./queries/users/update_user_profile.sql

# Get user's current program
psql -U rsstdd -d gym_track -f ./queries/users/get_user_current_program.sql
```

## Exercise Database

```bash
# Add a new exercise
psql -U rsstdd -d gym_track -f ./queries/exercises/add_new_exercise.sql

# Count all exercises
psql -U rsstdd -d gym_track -f ./queries/exercises/count_exercises.sql

# Get all exercises
psql -U rsstdd -d gym_track -f ./queries/exercises/get_all_exercises.sql

# Get exercise by ID
psql -U rsstdd -d gym_track -f ./queries/exercises/get_exercises_by_id.sql

# Get exercises by muscle group
psql -U rsstdd -d gym_track -f ./queries/exercises/get_exercises_by_muscle_group.sql

```

## Workout Programs

```bash
# Create a new program
psql -U rsstdd -d gym_track -f ./queries/workout-programs/create_new_program.sql

# Get all programs
psql -U rsstdd -d gym_track -f ./queries/workout-programs/get_all_programs.sql

# Get program by ID
psql -U rsstdd -d gym_track -f ./queries/workout-programs/get_program_by_id.sql


setoption' series of functions check for a so-called option that is set on
        the invoking character. 'Options' are used to store status conditions and a lot
        of other non-permanent character data of the yes-no kind. For most common cases,
        it is better to use 'checkcart','checkfalcon','checkriding' and other similar
        functions, but there are some options which you cannot get at this way. They
        return 1 if the option is set and 0 if the option is not set.

        Option numbers valid for the first (option) version of this command are:

        0x1       - Sight in effect.
        0x2       - Hide in effect.
        0x4       - Cloaking in effect.
        0x8       - Cart number 1 present.
        0x10      - Falcon present.
        0x20      - Peco Peco present.
        0x40      - GM Perfect Hide in effect.
        0x80      - Cart number 2 present.
        0x100     - Cart number 3 present.
        0x200     - Cart number 4 present.
        0x400     - Cart number 5 present.
        0x800     - Orc head present.
        0x1000    - The character is wearing a wedding sprite.
        0x2000    - Ruwach is in effect.
        0x4000    - Chasewalk in effect.
        0x8000    - Flying or Xmas suit.
        0x10000   - Sighttrasher.
        0x100000  - Warg present.
        0x200000  - The character is riding a warg.

        Option numbers valid for the second version (opt1) of this command are:

        1 - Petrified.
        2 - Frozen.
        3 - Stunned.
        4 - Sleeping.
        6 - Petrifying (the state where you can still walk)

        Option numbers valid for the third version (opt2) of this command are:

        0x1  - Poisoned.
        0x2  - Cursed.
        0x4  - Silenced.
        0x8  - Signum Crucis (plays a howl-like sound effect, but otherwise no visible effects are displayed)
        0x10 - Blinded.
        0x80 - Deadly poisoned.

        Option numbers (except for opt1) are bit-masks - you can add them up to check
        for several states, but the functions will return true if at least one of them
        is in effect.

        'setoption' will set options on the invoking character. There are no second and
        third versions of this command, so you can only change the values in the first
        list (cloak, cart, ruwach, etc). if flag is 1 (default when omitted),
        the option will be added to what the character currently has; if 0, the option is removed.

        This is definitely not a complete list of available option flag numbers. Ask a
        core developer (or read the source: src/map/status.hpp) for the full list.

setcart

setcart {<type>{,<char_id>}};
checkcart({<char_id>});

        If <type> is 0 this command will remove the cart from the character.
        Otherwise it gives the invoking character a cart. The cart given will be
        cart number <type> and will work regardless of whether the character is a
        merchant class or not.
        Note: the character needs to have the skill MC_PUSHCART to gain a cart

        The accompanying function will return 1 if the


rgID))
				continue
			}
			podIPModel.SubnetLcuuid = subnetLcuuid
		}
	}
	for _, v := range podIPsMap {
		podIPs = append(podIPs, *v)
	}

	// 处理nodeIP，生成port，ip，cidrs信息
	nodeVinterfaceLcuuids := mapset.NewSet()
	for _, vItem := range vData {
		if vItem.KubernetesClusterID != k.ClusterID {
			continue
		}
		deviceType := vItem.DeviceType
		if deviceType != "docker-host" && deviceType != "kvm-host" {
			continue
		}
		hostIP := vItem.HostIP
		nMAC := vItem.Mac
		nName := vItem.Name

		// 对于没有IP的网卡，如果名称符合PortNameRegex，则进行网卡挂载
		if vItem.IPs == "" && k.PortNameRegex != "" && portNameRegex.MatchString(nName) {
			vinterfaceLcuuid := common.GetUUIDByOrgID(k.orgID, k.UuidGenerate+nMAC)
			nodeLcuuid, ok := hostIPToNodeLcuuid[hostIP]
			if !ok {
				log.Infof("vinterface,ip node mac (%s) not match node", nMAC, logger.NewORGPrefix(k.orgID))
				continue
			}
			vinterface := model.VInterface{
				Lcuuid:        vinterfaceLcuuid,
				Type:          common.VIF_TYPE_WAN,
				Mac:           nMAC,
				NetnsID:       vItem.NetnsID,
				VTapID:        vItem.VtapID,
				DeviceLcuuid:  nodeLcuuid,
				DeviceType:    common.VIF_DEVICE_TYPE_POD_NODE,
				NetworkLcuuid: k.nodeNetworkLcuuidCIDRs.networkLcuuid,
				VPCLcuuid:     k.VPCUUID,
				RegionLcuuid:  k.RegionUUID,
			}
			nodeVInterfaces = append(nodeVInterfaces, vinterface)
			nodeVinterfaceLcuuids.Add(vinterfaceLcuuid)
			// 对于没有IP的网卡，无须处理IP信息
			continue
		}

		nIPs, ok := hostIPToNodeIPs[hostIP]
		if !ok {
			log.Infof("vinterface,ip node (%s) not found", hostIP, logger.NewORGPrefix(k.orgID))
			continue
		}
		// 如果该host所对应的ip里面有能够获取到lcuuid的则说明这个ip是有效的node ip
		nodeIPSlice := []string{}
		for _, nodeIP := range nIPs {
			_, ok := k.nodeIPToLcuuid[nodeIP]
			if ok {
				nodeIPSlice = append(nodeIPSlice, nodeIP)
			}
		}
		if len(nodeIPSlice) == 0 {
			log.Infof("vinterface,ip (%s) node not found", nMAC, logger.NewORGPrefix(k.orgID))
			continue
		}

		nodeIP := nodeIPSlice[0]
		IPs := strings.Split(vItem.IPs, ",")
		for _, ipString := range IPs {
			if ipString == "" {
				continue
			}
			ipPrefix, err := netaddr.ParseIPPrefix(ipString)
			if err != nil {
				log.Infof("vinterface,ip parse cidrs (%s) error: (%s)", ipString, err.Error(), logger.NewORGPrefix(k.orgID))
				continue
			}
			switch {
			// K8s API的容器节点IP，直接处理port和ip
			// 如果上报的node相关ip在node ip中，则使用上报ip的cidr替换掉聚合的node cid