The only handler which needs a frame is the clock handler, and it
 * only needs a few bits.  Xdoreti() needs a trap frame for handling ASTs, but
 * it could easily convert the frame on demand.
 *
 * The direct costs of setting up a trap frame are two pushl's (error code and
 * trap number), an addl to get rid of these, and pushing and popping the
 * callee-saved registers %esi, %edi, %ebx, and %ebp twice.
 *
 * If the interrupt frame is made more flexible,  INTR can push %eax first and
 * decide the ipending case with less overhead, e.g., by avoiding loading the
 * segment registers.
 *
 * XXX
 * Should we do a cld on every system entry to avoid the requirement for
 * scattered cld's?
 */

	.globl	_C_LABEL(isa_strayintr)

/*
 * Normal vectors.
 *
 * We cdr down the intrhand chain, calling each handler with its appropriate
 * argument (0 meaning a pointer to the frame, for clock interrupts).
 *
 * The handler returns one of three values:
 *   0 - This interrupt wasn't for me.
 *   1 - This interrupt was for me.
 *  -1 - This interrupt might have been for me, but I don't know.
 * If there are no handlers, or they all return 0, we flags it as a `stray'
 * interrupt.  On a system with level-triggered interrupts, we could terminate
 * immediately when one of them returns 1; but this is a PC.
 *
 * On exit, we jump to Xdoreti(), to process soft interrupts and ASTs.
 */

#define MY_COUNT _C_LABEL(uvmexp)

#define	XINTR(irq_num)		Xintr/**/irq_num
#define	XHOLD(irq_num)		Xhold/**/irq_num
#define	XSTRAY(irq_num)		Xstray/**/irq_num

#define	INTR(irq_num, icu, ack) \
IDTVEC(resume/**/irq_num)						;\
	cli								;\
	jmp	1f							;\
IDTVEC(recurse/**/irq_num)						;\
	movq	%rsp,%r10						;\
	movl	%ss,%r11d						;\
	pushq	%r11							;\
	pushq	%r10							;\
	pushfq								;\
	movl	%cs,%r11d						;\
	pushq	%r11							;\
	pushq	%r12							;\
	cli								;\
XINTR(irq_num):								;\
	pushq	$0			/* dummy error code */		;\
	pushq	$T_ASTFLT		/* trap # for doing ASTs */	;\
	INTRENTRY							;\
	MAKE_FRAME							;\
	MASK(irq_num, icu)		/* mask it in hardware */	;\
	ack(irq_num)			/* and allow other intrs */	;\
	incl	(MY_COUNT+V_INTR)(%rip)		/* statistical info */	;\
	leaq	_C_LABEL(cpl)(%rip),%rdi				;\
	testb	$IRQ_BIT(irq_num),IRQ_BYTE(irq_num)(%rdi)		;\
	jnz	XHOLD(irq_num)		/* currently masked; hold it */	;\


, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (WooshopStoresDto wooshopStores : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("店铺名称", wooshopStores.getStoresName());
            map.put("店铺信息", wooshopStores.getStoresInfo());
            map.put("店铺联系手机号码", wooshopStores.getTelephone());
            map.put("店铺联系称呼", wooshopStores.getContactName());
            map.put("省市区", wooshopStores.getStoresAddress());
            map.put("详细地址", wooshopStores.getDetailedAddress());
            map.put("门店logo", wooshopStores.getStoresLogo());
            map.put("店铺地址纬度", wooshopStores.getLatitude());
            map.put("店铺地址经度", wooshopStores.getLongitude());
            map.put("允许核销有效日期", wooshopStores.getValidTime());
            map.put("营业时间", wooshopStores.getDayTime());
            map.put("店铺状态:1开启 0隐藏", wooshopStores.getIsStart());
            map.put("是否删除", wooshopStores.getIsDel());
            map.put("是否允许自提:1允许 0不允许", wooshopStores.getIsTake());
            map.put("添加时间", wooshopStores.getCreateTime());
            map.put("更新时间", wooshopStores.getUpdateTime());
            map.put("管理用户id", wooshopStores.getUid());
            map.put("0 需要审核 并且待审核，1 不需要审核 2需要审核 且审核通过 3 需要审核 且审核未通过", wooshopStores.getIsAuth());
            map.put("审核信息", wooshopStores.getAuthMessage());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @CachePut(cacheNames=CacheKey.WOOSHOP_STORES_ID,key = "#p0.id")
    @CacheRemove(value = CacheKey.WOOSHOP_STORES_QUERY, key = "*")
    public PageResult<WooshopStoresDto> addAndUpdate(WooshopStores resources) {
        if (resources.getId() == null) {
            save(resources);
        } else {
            updateById(resources);
        }
        List<WooshopStores> resList=new ArrayList<>();
        resList.add(resources);
        PageInfo<WooshopStores> page = new PageInfo<>(resList);
//        PageResult<WooshopStoresDto> dtoPageResult =
        return generator.convertPageInfo(page, WooshopStoresDto.class);
    }

    @Override
//    @CacheEvict(cacheNames=CacheKey.WOOSHOP_STORES_ID,key = "#p0.id")
    @CacheRemove(value = CacheKey.WOOSHOP_STORES_QUERY, key = "*")
    public void cacheRemoveById(Long id) {
        removeById(id);
    }

}

package com.wooshop.modules.goodsEvaluation.domain;

import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import cn.hutool.core.bean.BeanUtil;

import com.wooshop.domain.BaseDomain;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import


_work_ctx: std::ptr::null_mut(),
    };
    // INIT - FOREIGN CONTEXT
    let data = Box::new(data);
    let data = Box::into_raw(data);
    let async_resource = std::ptr::null_mut();
    let async_resource_name = to_napi_value(env, "web_images_async_task");
    let mut async_handle: NapiAsyncWork = std::ptr::null_mut();
    let status = napi_create_async_work(
        env,
        async_resource,
        async_resource_name,
        Some(worker),
        Some(on_complete::<I, O>),
        data as *mut libc::c_void,
        &mut async_handle,
    );
    if status != NAPI_OK {
        return Err(String::from("napi_create_async_work failed"));
    }
    // SET - FOREIGN HANDLE
    let data_tmp = Box::from_raw(data as *mut AsyncData<I, O>);
    let data_tmp: &mut AsyncData<I, O> = Box::leak(data_tmp);
    data_tmp.async_work_ctx = async_handle;
    // RUN - FOREIGN HANDLE
    let status = napi_queue_async_work(env, async_handle);
    if status != NAPI_OK {
        return Err(String::from("napi_queue_async_work failed"));
    }
    // DONE
    Ok(promise)
}

#[macro_export]
macro_rules! offload_work {
    ($env:expr, $input:expr, $in_ty:ty, $out_ty:ty, $worker:ident, $finalize:ident $(,)*) => {{
        use $crate::utils::*;
        unsafe extern "C" fn on_exec(env: NapiEnv, data: *mut std::os::raw::c_void) {
            let f: fn($in_ty)->$out_ty = $worker;
            assert!(!data.is_null());
            let data = Box::from_raw(data as *mut AsyncData<$in_ty, $out_ty>);
            let data: &mut AsyncData<$in_ty, $out_ty> = Box::leak(data);
            let input: Option<$in_ty> = data.input.replace(None);
            let input: $in_ty = input.expect("offload_work macro and offload_work_impl failed");
            data.output = Some(f(input));
        }
        let input: $in_ty = $input;
        let output = unsafe {
            offload_work_impl($env, input, on_exec, $finalize)
        };
        output
    }};
}

///////////////////////////////////////////////////////////////////////////////
// JS OBJECTS
///////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone, PartialEq)]
pub struct JsObject(NapiValue);

impl JsObject {
    pub fn into_raw(self) -> NapiValue {
        self.0
    }
    pub fn from_raw(env: NapiEnv, value: NapiValue) -> Result<Self, String> {
        if value.is_null() {
            return Err(String::from("invalid argument"));
        }
        let value_type = get_value_type(env, value)?;
        if value_type == NAPI_OBJECT {
            Ok(JsObject(value))
        } else {
            Err(String::from("[JsObject::from_raw] value is not an object"))
        }
    }
    pub fn new(env: NapiEnv) -> Result<Self, String> {
        unsafe {
            let mut output: NapiValue = std::mem::uninitialized();
            let status = napi_create_object(env, &mut output);
            if status != NAPI_OK {
                return Err(String::from("napi_create_object failed"));
            }
            if output.is_null() {
                return Err(String::from("napi_create_object output is null"));
            }
            Ok(JsObject(output))
        }
    }
    pub fn insert_raw<K: Serialize>(&mut self, env: NapiEnv, ke


= nil {
		return err
	}

	conn.schemata = Schemata{
		Databases: map[string]Database{},
	}

	return nil
}

func (conn *BaseConn) setContext(ctx context.Context, concurrency int) {
	c := g.NewContext(ctx, concurrency)
	if conn.context != nil {
		c.Map = conn.context.Map
	}
	conn.context = c
}

// Self returns the respective connection Instance
// This is useful to refer back to a subclass method
// from the superclass level. (Aka overloading)
func (conn *BaseConn) Self() Connection {
	return *conn.instance
}

// Db returns the sqlx db object
func (conn *BaseConn) Db() *sqlx.DB {
	return conn.db
}

// DbX returns the DbX object
func (conn *BaseConn) DbX() *DbX {
	return &DbX{db: conn.db}
}

// Tx returns the current sqlx tx object
func (conn *BaseConn) Tx() Transaction {
	return conn.tx
}

// GetType returns the type db object
func (conn *BaseConn) GetType() dbio.Type {
	return conn.Type
}

// Context returns the db context
func (conn *BaseConn) Context() *g.Context {
	return conn.context
}

// Schemata returns the Schemata object
func (conn *BaseConn) Schemata() Schemata {
	return conn.schemata
}

// Template returns the Template object
func (conn *BaseConn) Template() dbio.Template {
	return conn.template
}

// GetProp returns the value of a property
func (conn *BaseConn) GetProp(key ...string) string {
	conn.context.Mux.Lock()
	defer conn.context.Mux.Unlock()
	for _, k := range key {
		if val, ok := conn.properties[strings.ToLower(k)]; ok {
			return val
		}
	}
	return ""
}

// SetProp sets the value of a property
func (conn *BaseConn) SetProp(key string, val string) {
	conn.context.Mux.Lock()
	if conn.properties == nil {
		conn.properties = map[string]string{}
	}
	conn.properties[strings.ToLower(key)] = val
	conn.context.Mux.Unlock()
}

// PropArr returns an array of properties
func (conn *BaseConn) PropArr() []string {
	return conn.PropArrExclude() // don't exclude any key
}

func (conn *BaseConn) PropArrExclude(exclude ...string) []string {
	props := []string{}
	conn.context.Mux.Lock()
	for k, v := range conn.properties {
		if g.In(k, exclude...) {
			continue
		}
		props = append(props, g.F("%s=%s", k, v))
	}
	conn.context.Mux.Unlock()
	return props
}

// ReplaceProps used when reusing a connection
// since the provided props can change, this is used
// to delete old original props and set new ones
func (conn *BaseConn) ReplaceProps(newProps map[string]string) {
	oldPropKeys := []string{}

	g.Unmarshal(conn.GetProp("orig_prop_keys"), oldPropKeys)

	conn.context.Mux.Lock()
	for _, k := range oldPropKeys {
		delete(conn.properties, k)
	}

	// set new props
	for k, v := range newProps {
		conn.properties[k] = v
	}

	conn.context.Mux.Unlock()
}

// Props returns a map properties
func (conn *BaseConn) Props() map[string]string {
	m := map[string]string{}
	conn.context.Mux.Lock()
	for k, v := range conn.properties {


,0x536d
bfc66990:	3c030f7b 	lui	v1,0xf7b
bfc66994:	34630ee9 	ori	v1,v1,0xee9
bfc66998:	01091020 	add	v0,t0,t1
bfc6699c:	1443039f 	bne	v0,v1,bfc6781c <inst_error>
bfc669a0:	00000000 	nop
/home/ghj/Desktop/func/inst/n21_add.S:146
bfc669a4:	3c08ca45 	lui	t0,0xca45
bfc669a8:	350844c4 	ori	t0,t0,0x44c4
bfc669ac:	3c0925e6 	lui	t1,0x25e6
bfc669b0:	3529b2fa 	ori	t1,t1,0xb2fa
bfc669b4:	3c03f02b 	lui	v1,0xf02b
bfc669b8:	3463f7be 	ori	v1,v1,0xf7be
bfc669bc:	01091020 	add	v0,t0,t1
bfc669c0:	14430396 	bne	v0,v1,bfc6781c <inst_error>
bfc669c4:	00000000 	nop
/home/ghj/Desktop/func/inst/n21_add.S:147
bfc669c8:	3c08e86d 	lui	t0,0xe86d
bfc669cc:	3508ce88 	ori	t0,t0,0xce88
bfc669d0:	3c09eef5 	lui	t1,0xeef5
bfc669d4:	35291a30 	ori	t1,t1,0x1a30
bfc669d8:	3c03d762 	lui	v1,0xd762
bfc669dc:	3463e8b8 	ori	v1,v1,0xe8b8
bfc669e0:	01091020 	add	v0,t0,t1
bfc669e4:	1443038d 	bne	v0,v1,bfc6781c <inst_error>
bfc669e8:	00000000 	nop
/home/ghj/Desktop/func/inst/n21_add.S:148
bfc669ec:	3c081a92 	lui	t0,0x1a92
bfc669f0:	3508a5a0 	ori	t0,t0,0xa5a0
bfc669f4:	3c09d1ea 	lui	t1,0xd1ea
bfc669f8:	3529c31b 	ori	t1,t1,0xc31b
bfc669fc:	3c03ec7d 	lui	v1,0xec7d
bfc66a00:	346368bb 	ori	v1,v1,0x68bb
bfc66a04:	01091020 	add	v0,t0,t1
bfc66a08:	14430384 	bne	v0,v1,bfc6781c <inst_error>
bfc66a0c:	00000000 	nop
/home/ghj/Desktop/func/inst/n21_add.S:149
bfc66a10:	3c08dec0 	lui	t0,0xdec0
bfc66a14:	3508f040 	ori	t0,t0,0xf040
bfc66a18:	3c0959bc 	lui	t1,0x59bc
bfc66a1c:	35293412 	ori	t1,t1,0x3412
bf


ition-icon--bug:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7.72.22a.75.75 0 0 1 1.06 0l1.204 1.203A4.98 4.98 0 0 1 12 1c.717 0 1.4.151 2.016.423L15.22.22a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-.971.972A4.991 4.991 0 0 1 17 6v1.104a2.755 2.755 0 0 1 1.917 1.974l1.998-.999a.75.75 0 0 1 .67 1.342L19 10.714V13.5l3.25.003a.75.75 0 0 1 0 1.5L19 15.001V16c0 .568-.068 1.134-.204 1.686l.04.018 2.75 1.375a.75.75 0 1 1-.671 1.342l-2.638-1.319A6.998 6.998 0 0 1 12 23a6.998 6.998 0 0 1-6.197-3.742l-2.758 1.181a.752.752 0 0 1-1.064-.776.752.752 0 0 1 .474-.602l2.795-1.199A6.976 6.976 0 0 1 5 16v-.996H1.75a.75.75 0 0 1 0-1.5H5v-2.79L2.415 9.42a.75.75 0 0 1 .67-1.342l1.998.999A2.756 2.756 0 0 1 7 7.104V6a4.99 4.99 0 0 1 1.69-3.748l-.97-.972a.75.75 0 0 1 0-1.06ZM6.5 9.75V16a5.5 5.5 0 1 0 11 0V9.75c0-.69-.56-1.25-1.25-1.25h-8.5c-.69 0-1.25.56-1.25 1.25ZM8.5 7h7V6a3.5 3.5 0 1 0-7 0Z"/></svg>');--md-admonition-icon--example:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8 8.807V3.5h-.563a.75.75 0 0 1 0-1.5h9.125a.75.75 0 0 1 0 1.5H16v5.307l5.125 9.301c.964 1.75-.302 3.892-2.299 3.892H5.174c-1.998 0-3.263-2.142-2.3-3.892ZM4.189 18.832a1.123 1.123 0 0 0 .985 1.668h13.652a1.123 1.123 0 0 0 .985-1.668L17.7 15H6.3ZM14.5 3.5h-5V9a.75.75 0 0 1-.093.362L7.127 13.5h9.746l-2.28-4.138A.75.75 0 0 1 14.5 9Z"/></svg>');--md-admonition-icon--quote:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6.25a.75.75 0 0 1 .75-.75h13.5a.75.75 0 0 1 0 1.5H3.75A.75.75 0 0 1 3 6.25Zm5 6.063a.75.75 0 0 1 .75-.75h11.5a.75.75 0 0 1 0 1.5H8.75a.75.75 0 0 1-.75-.75Zm0 5.937a.75.75 0 0 1 .75-.75h11.5a.75.75 0 0 1 0 1.5


o(t,u(new Uint8Array([255,255,255,255]),[1,1,4]));c.generateMipmap(),c.minFilter=t.LINEAR_MIPMAP_LINEAR,c.magFilter=t.LINEAR;var f=i(t),p=i(t),g=i(t),y=i(t),m=i(t),x=a(t,[{buffer:f,type:t.FLOAT,size:4},{buffer:m,type:t.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:g,type:t.FLOAT,size:4},{buffer:y,type:t.FLOAT,size:2},{buffer:p,type:t.FLOAT,size:4}]),b=new h(t,c,s,l,f,p,m,g,y,x,r.traceType||"cone");return b.update(e),b}},7234:function(t,e,r){var n=r(6832),i=n(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u *


= entityRefChars.IndexOf((char)currCh) & 0xF;
							if (pos == 0xF) FatalErr(errors[7]);
							sbChars.Append((char)currCh);

							int path = "\uFF35\u3F8F\u4F8F\u0F5F\uFF78\uE1F4\u2299\uEEFF\uEEFF\uFF4F"[pos];
							int lBr = (path >> 4) & 0xF;
							int rBr = path & 0xF;
							int lPred = path >> 12;
							int rPred = (path >> 8) & 0xF;
							currCh = reader.Read();
							cl++;
							pos = 0xF;
							if (lBr != 0xF && currCh == entityRefChars[lBr]) {
								if (lPred < 0xE) entIdx = lPred;
//								pred = lPred;
								predShift = 12; // left
							} else if (rBr != 0xF && currCh == entityRefChars[rBr]) {
								if (rPred < 0xE) entIdx = rPred;
//								pred = rPred;
								predShift = 8; // right
							} else if (currCh == ';') {
								if (entIdx !


) {
      throw Exception(
        "The controller is not connected to any overlay or it had no time to connect yet.",
      );
    }
  }
}

abstract class ShellOverlay extends StatefulWidget {
  final String id;
  final ShellOverlayController _controller = ShellOverlayController();

  ShellOverlay({
    required this.id,
    super.key,
  });

  @override
  ShellOverlayState createState();
}

abstract class ShellOverlayState<T extends ShellOverlay> extends State<T>
    with TickerProviderStateMixin {
  late final AnimationController animationController = AnimationController(
    vsync: this,
    duration: Constants.animationDuration,
  );
  ShellOverlayController get controller => widget._controller;

  Animation<double> get animation => CurvedAnimation(
        parent: animationController,
        curve: Constants.animationCurve,
      );

  @override
  void initState() {
    controller._overlay = this;
    controller.showingNotifier.addListener(_showListener);
    super.initState();
  }

  @override
  void dispose() {
    controller.showingNotifier.removeListener(_showListener);
    animationController.dispose();
    super.dispose();
  }

  FutureOr<void> requestShow(Map<String, dynamic> args);

  FutureOr<void> requestDismiss(Map<String, dynamic> args);

  void _showListener() {
    setState(() {});
  }

  bool get shouldHide => !controller.showing && animationController.value == 0;
}
/*
Copyright 2021 The dahliaOS Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import 'package:dahlia_shared/dahlia_shared.dart';
import 'package:flutter/material.dart';
import 'package:pangolin/components/desktop/wallpaper_picker.dart';
import 'package:pangolin/services/application.dart';
import 'package:pangolin/services/wm.dart';
import 'package:pangolin/widgets/context_menu.dart';
import 'package:pangolin/widgets/resource/image/image.dart';
import 'package:provider/provider.dart';

class WallpaperLayer extends StatelessWidget
    with StatelessServiceListener<CustomizationService> {
  const WallpaperLayer({super.key});

  @override
  Widget buildChild(BuildContext context, CustomizationService service) {
    return SizedBox.expand(
      child: ChangeNotifierProvider.value(
        value: WindowManagerService.current.controller,
        child: _WallpaperContextMenu(
          child: ResourceImage(
            resource: service.wallpaper,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }
}

class _WallpaperContextMenu extends StatelessWidget {
  const _WallpaperContextMenu({
    required this.child,
  });

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return ContextMenu(
      entries: [
        ContextMenuItem(
          onTap: () {
            showDialog(
              barrierColor: Colors.transparent,
              context: context,
              builder: (context) {
                return const WallpaperPicker();
              },
            );
          },
          leading: const Icon(Icons.image),
          child: const Text("Change Wallpaper"),


ame(GTK_ABOUT_DIALOG(widget), "Socket NetPlay Driver");
	gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(widget), "0.21");
	gtk_about_dialog_set_authors(GTK_ABOUT_DIALOG(widget), authors);
	gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(widget), "http://www.codeplex.com/pcsxr/");

	gtk_dialog_run(GTK_DIALOG(widget));
	gtk_widget_destroy(widget);
}

long CFGmessage(char *args[], int num) {
	char msg[512];

	memset(msg, 0, sizeof(msg));
	while (num) {
		strcat(msg, *args); strcat(msg, " ");
		num--; args++;
	}
	cfgSysMessage(msg);

	return 0;
}

int main(int argc, char *argv[]) {
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
	textdomain(GETTEXT_PACKAGE);
#endif

	gtk_init(&argc, &argv);

	if (argc < 2) {
		printf ("Usage: cfgDFNet {about | configure | open | wait | pause | message}\n");
		return 0;
	}

	if (strcmp(argv[1], "about") != 0 &&
		strcmp(argv[1], "configure") != 0 &&
		strcmp(argv[1], "open") != 0 &&
		strcmp(argv[1], "wait") != 0 &&
		strcmp(argv[1], "pause") != 0 &&
		strcmp(argv[1], "message") != 0) {
		printf ("Usage: cfgDFNet {about | configure | open | wait | pause | message}\n");
		return 0;
	}

	if(argc > 1) {
		if (!strcmp(argv[1], "configure")) {
			CFGconfigure();
		} else if (!strcmp(argv[1], "about")) {
			CFGabout();
		} else if (!strcmp(argv[1], "open")) {
			return CFGopen();
		} else if (!strcmp(argv[1], "wait")) {
			CFGwait();
		} else if (!strcmp(argv[1], "pause")) {
			return CFGpause();
		} else if (!strcmp(argv[1], "message")) {
			CFGmessage(&argv[2], argc - 2);
		}
	}

	return 0;
}


 for the specific language governing permissions and
 * limitations under the License.
 *
*/

#if DEBUG
using ASC.Common.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ASC.Common.Tests.Utils
{
    [TestClass]
    public class MimeHeaderUtilsTest
    {
        [TestMethod]
        public void Encode()
        {
            Assert.AreEqual("=?utf-8?B?0YrRitGK?=", MimeHeaderUtils.EncodeMime("ъъъ"));
            Assert.AreEqual("ddd", MimeHeaderUtils.EncodeMime("ddd"));
        }
    }
}
#endif


     for (i = 0; i < 5; ++i)
                grad[i] = -grad[i];
        return -x7;
    } else if (which_constraint == 2) {
        return x7 - 294000;
    } else if (which_constraint == -3) {
        if (grad)
            for (i = 0; i < 5; ++i)
                grad[i] = -grad[i];
        return -x8;
    } else if (which_constraint == 3) {
        return x8 - 277200;
    }
    return 0;
}

int main(void)
{
    const double box_lb[5] = { 0, 1.2, 20, 9, 6.5 };
    const double box_ub[5] = { HUGE_VAL, 2.4, 60, 9.3, 7.0 };
    const double box_xmin[5] = { 4.53743, 2.4, 60, 9.3, 7.0 };

    int cdata[6] = { -1, 1, -2, 2, -3, 3 };
    double x[5] = { 2.52, 2, 37.5, 9.25, 6.8 };
    double minf;

    nlopt_minimize_constrained(NLOPT_LN_COBYLA, 5, box, NULL, 6, box_constraint, cdata, sizeof(int), box_lb, box_ub, x, &minf, -HUGE_VAL, 1e-10, 0, 0, NULL, 0, 0);
    printf("found f(%g,%g,%g,%g,%g) = %0.8f after %d iters\n", x[0], x[1], x[2], x[3], x[4], minf, testfuncs_counter);
    return 0;
}


ine that was executing when
// this event happened. It describes part of the execution context
// for this event.
//
// Note that for goroutine state transitions this always refers to the
// state before the transition. For example, if a goroutine is just
// starting to run on this thread and/or proc, then this will return
// NoGoroutine. In this case, the goroutine starting to run will be
// can be found at Event.StateTransition().Resource.
func (e Event) Goroutine() GoID {
	return e.ctx.G
}

// Proc returns the ID of the proc this event event pertains to.
//
// Note that for proc state transitions this always refers to the
// state before the transition. For example, if a proc is just
// starting to run on this thread, then this will return NoProc.
func (e Event) Proc() ProcID {
	return e.ctx.P
}

// Thread returns the ID of the thread this event pertains to.
//
// Note that for thread state transitions this always refers to the
// state before the transition. For example, if a thread is just
// starting to run, then this will return NoThread.
//
// Note: tracking thread state is not currently supported, so this
// will always return a valid thread ID. However thread state transitions
// may be tracked in the future, and callers must be robust to this
// possibility.
func (e Event) Thread() ThreadID {
	return e.ctx.M
}

// Stack returns a handle to a stack associated with the event.
//
// This represents a stack trace at the current moment in time for
// the current execution context.
func (e Event) Stack() Stack {
	if e.base.typ == evSync {
		return NoStack
	}
	if e.base.typ == tracev2.EvCPUSample {
		return Stack{table: e.table, id: stackID(e.base.args[0])}
	}
	spec := tracev2.Specs()[e.base.typ]
	if len(spec.StackIDs) == 0 {
		return NoStack
	}
	// The stack for the main execution context is always the
	// first stack listed in StackIDs. Subtract one from this
	// because we've peeled away the timestamp argument.
	id := stackID(e.base.args[spec.StackIDs[0]-1])
	if id == 0 {
		return NoStack
	}
	return Stack{table: e.table, id: id}
}

// Metric returns details about a Metric event.
//
// Panics if Kind != EventMetric.
func (e Event) Metric() Metric {
	if e.Kind() != EventMetric {
		panic("Metric called on non-Metric event")
	}
	var m Metric
	switch e.base.typ {
	case tracev2.EvProcsChange:
		m.Name = "/sched/gomaxprocs:threads"
		m.Value = uint64Value(e.base.args[0])
	case tracev2.EvHeapAlloc:
		m.Name = "/memory/classes/heap/objects:bytes"
		m.Value = uint64Value(e.base.args[0])
	case tracev2.EvHeapGoal:
		m.Name = "/gc/heap/goal:bytes"
		m.Value = uint64Value(e.base.args[0])
	default:
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Metric kind: %d", e.base.typ))
	}
	return m
}

// Label returns details about a Label event.
//
// Panics if Kind != EventLabel.
func (e Event) Label() Label {
	if e.Kind() != EventLabel {
		panic("Label called on non-Label event")
	}


's a non-trivial networking problem
and something Google certainly plan on supporting in the future. Keep in mind, Cloud Endpoints
is a combination or App Engine and Google's API Infrastructure."

## Generate client libs

Now that we have the discovery doc, let's generate some client libraries.

### Android

```
$ URL='https://my-app-id.appspot.com/_ah/api/discovery/v1/apis/greeting/v1/rest'
$ curl -s $URL > greetings.rest.discovery

# Optionally check the discovery doc
$ less greetings.rest.discovery

$ GO_SDK/endpointscfg.py gen_client_lib java greetings.rest.discovery
```

You should be able to find `./greetings.rest.zip` file with Java client source
code and its dependencies.

Once you have that, follow the official guide:
[Using Endpoints in an Android Client][8].

### iOS

```
# Note the rpc suffix in the URL:
$ URL='https://my-app-id.appspot.com/_ah/api/discovery/v1/apis/greeting/v1/rpc'
$ curl -s $URL > greetings.rpc.discovery

# Optionally check the discovery doc
$ less greetings.rpc.discovery
```

Then, feed `greetings.rpc.discovery` file to the library generator on OS X as
described in the official guide [Using Endpoints in an iOS Client][9].

### JavaScript

There's really nothing to generate for JavaScript, you just use it!

Here's the official guide: [Using Endpoints in a JavaScript client][10].

### Dart

```
# Clone or fork discovery_api_dart_client_generator
git clone https://github.com/dart-gde/discovery_api_dart_client_generator
cd discovery_api_dart_client_generator
pub install

# Generate your client library:
mkdir input
URL='https://my-app-id.appspot.com/_ah/api/discovery/v1/apis/greeting/v1/rest'
curl -s -o input/greeting.json $URL
bin/generate.dart package -i input -o ../dart_my-app-id_v1_api_client --package-name my-app-id_v1_api
```

Now you just have to add your endpoints client library to your dart application (assuming it is in the parent directory.)

```
cd ../my-app_dart/
cat >>pubspec.yaml <<EOF
  my-app-id_v1_api:
  path: ../dart_my-app-id_v1_api_client
EOF
```

Take a look at the api client [examples](https://github.com/dart-gde/dart_api_client_examples) to
get a feel on how to use your library.

## Docs

  - [Go endpoints package docs][11]
  - [Wiki of this repo][12]

## Samples

Check out the famous [TicTacToe app][3]. It has its own readme file.

Or you can just play it on the [live demo app][13].

## Running tests

You'll need Google App Engine SDK for Go to run tests.

Once you get that installed, use `goapp` tool to run all tests from the root
of this repo:

```
GO_APPENGINE_SDK/goapp test ./endpoints
```

The tool uses API server bundled with the SDK, which outputs lots of debugging
info. You can suppress that with:

```
GO_APPENGINE_SDK/goapp test -v ./endpoints 2> /dev/null
```

[Learn more about goapp tool][goapp].

[1]: https://cloud.google.com/appengine/docs/python/endpoints/
[2]: https://cloud.google.com/appengine/docs/java/endpoints/
[3]: https://github.com/crhym3/go-tictactoe
[5]: http://localhost:8080


"""
Feature: 2.2.3 Greater Than (>)
Category: Operators
Complexity: Low
Status: not_implemented
"""

import pytest

PYTHON_SOURCE = """
result = (5 > 3)  # True
"""

EXPECTED_RUST = """
// TODO: Add Rust equivalent
"""

@pytest.mark.complexity("low")
@pytest.mark.status("not_implemented")
def test_223_greater_than():
    """Test translation of 2.2.3 Greater Than (>)."""
    pytest.skip("Feature not yet implemented")


["trainer"] },
{ name: "Catch something from Safari Zone", types: ["safari"] },
{ name: "5 Valuable Items", types: ["multiitem"] }
];
bingoList[20] = [
{ name: "Burn a Kecleon", types: ["move"] },
{ name: "20 TMs", types: ["item"] },
{ name: "HM02 (Fly)", types: ["hm"] },
{ name: "Sea or Lax Incense", types: ["item"] }
];
bingoList[21] = [
{ name: "Featherbadge", types: ["badge"] },
{ name: "Magneton", types: ["pkmn"] },
{ name: "$50,000", types: ["cash"] },
{ name: "Put a Pokeblock into a Safari Zone Container", types: ["pokeblock"] }
];
bingoList[22] = [
{ name: "Two different non-key exchangeable items", types: ["multiitem"] },
{ name: "A Trade Evolution Item", types: ["multiitem"] },
{ name: "Wobbuffet", types: ["pkmn"] },
{ name: "3 different level 30 Pokemon", types: ["dex"] }
];
bingoList[23] = [
{ name: "TM21 (Frustration) or TM27 (Return)", types: ["tm"] },
{ name: "All rods", types: ["rods"] },
{ name: "Defeat 5 Ninja Boys", types: ["trainer"] },
{ name: "HM08 (Dive)", types: ["hm"] }
];
bingoList[24] = [
{ name: "Seadra", types: ["pkmn"] },
{ name: "Grovyle", types: ["starter", "pkmn"] },
{ name: "TM04 (Calm Mind)", types: ["tm"] },
{ name: "Relicanth or Wailord", types: ["pkmnpair"] }
];
bingoList[25] = [
{ name: "Defeat all 6 Trainers on Route 125", types: ["trainer"] },
{ name: "Catch a Dragon-type Pokemon", types: ["pkmn"] },
{ name: "All badges", types: ["badge"] },
{ name: "Heracross or Pinsir", types: ["pkmnpair"] }
];
var bingoGenerator = require("./generators/generator_bases/srl_generator_v5.js");

var thisVersion = "v3 beta 9";

var bingoList = [];
bingoList[1] = [
{ name: "10 Blue Coins from M Graffiti", jp: "", types: ["M_Graffiti", "Ricco_M"] },
{ name: "3 Fruit Lady Blue Coins", jp: "アルバイトの青コイン3枚", types: ["Fruit_Ladies"] },
{ name: "3 Red Coin Shines", jp: "赤コインのシャイン3枚", types: ["Red_Shines", "Plaza_Shines", "Hidden_Shines", "Low_Reds"] },
{ name: "10 Blue Coins from Delfino Plaza", jp: "ドルピックタウンの青コイン10枚", types: ["Plaza_Blues", "Fruit_Ladies"] },
{ name: "15 Blue Coins from Ricco Harbor", jp: "リコハーバーの青コイン15枚", types: ["Ricco_Blues", "Ricco_M", "Fast_20", "Ricco_Shines"] },
{ name: "100 Coin Shine from Pianta Village", jp: "モンテのむらの100枚コイン", types: ["X100_Coins"] }
];
bingoList[2] = [
{ name: "10 Blue Coins from Pinna Park", jp: "ピンナパークの青コイン10枚", types: ["Pinna_Blues", "Pinna_10", "Pinna_30"] },
{ name: "15 Blue Coins from Gelato Beach", jp: "マンマビーチの青コイン15枚", types: ["Gelato_Blues", "Fast_20"] },
{ name: "20 Blue Coins from Ricco Harbor", jp: "リコハーバーの青コイン20枚", types: ["


@ tmp3158,,, tmp3124
	vtbl.8	d11, {d16, d17}, d19	@,,,
	.loc 3 218 0
	vtbl.8	d18, {d8, d9}, d24	@ tmp3168,,, tmp3134
	.loc 3 205 0
	veor	q11, q11, q5	@ tmp3162, tmp3154, tmp3158
	.loc 3 195 0
	vtbl.8	d16, {d6, d7}, d20	@ tmp3163,,, tmp3129
	vtbl.8	d17, {d6, d7}, d21	@,,,
	.loc 3 218 0
	vtbl.8	d19, {d8, d9}, d25	@,,,
	veor	q10, q11, q8	@ tmp3167, tmp3162, tmp3163
	.loc 3 228 0
	veor	q5, q10, q9	@ prephitmp.786, tmp3167, tmp3168
.LVL215:
.LBE1414:
.LBE1417:
.LBE1423:
	.loc 3 58 0
	bne	.L131	@,
	.loc 3 93 0
	add	r4, r3, r0, lsl #4	@, tmp3207, tweakey, t,
	vstr	d0, [sp, #32]	@, %sfp
	vstr	d1, [sp, #40]	@, %sfp
	vmov	q6, q7  @ v16qi	@ prephitmp.786, prephitmp.786
	vldr	d8, [r4, #32]	@, *D.16895_1127
	vldr	d9, [r4, #40]	@, *D.16895_1127
	vldmia	r4, {d14-d15}	@ *D.16895_2161, *D.16895_2161
	vldr	d0, [sp, #224]	@, %sfp
	vldr	d1, [sp, #232]	@, %sfp
	vldr	d16, [r4, #48]	@, *D.16895_491
	vldr	d17, [r4, #56]	@, *D.16895_491
	veor	q13, q4, q0	@, *D.16895_1127,
	veor	q11, q8, q6	@, *D.16895_491, prephitmp.786
	vstr	d26, [sp, #112]	@, %sfp
	vstr	d27, [sp, #120]	@, %sfp
	vstr	d22, [sp, #128]	@, %sfp
	vstr	d23, [sp, #136]	@, %sfp
	vldr	d24, [sp, #192]	@, %sfp
	vldr	d25, [sp, #200]	@, %sfp
	veor	q12, q7, q12	@ tmp3210, *D.16895_2161,
.LVL216:
	vldr	d14, [r4, #96]	@, *D.16895_2735
	vldr	d15, [r4, #104]	@, *D.16895_2735
	veor	q4, q7, q2	@ tmp3270, *D.16895_2735, prephitmp.786
	vldr	d4, [r4, #112]	@, *D.16895_2752
	vldr	d5, [r4, #120]	@, *D.16895_2752
	veor	q14, q2, q14	@, *D.16895_2752, prephitmp.786
	vstr	d28, [sp, #16]	@, %sfp
	vstr	d29, [sp, #24]	@, %sfp


3v9mge2Budp1VPxpK2jBlpiygrs49bCBMn7acsIyhw+POmbaIWCNZGA== sig=DjKdQwGEy0LhEp0kmSz36WKnC/yM7Kr5uVpHG89yDug5XWK1ojomXeHSKulB6z081UFcr6fZLlExLoNTphOGDw== e=found last=13 s=29 in addShifted_NP",
            "pub=MCowBQYDK2VwAyEAgDofkq0/5UZIe7ZuGeUAevwMDP9rnemCmBPuDVz/Ze4= priv=MC4CAQAwBQYDK2VwBCIEIFLUzoYodONr4E9m/0YDjtiL0+Qe6XKksz/cLXKlUQoe msg=ViZvK1zby/g5NgXGJ5BsffUkz3BKCpvxUAA8LVLUzoYodONr4E9m/0YDjtiL0+Qe6XKksz/cLXKlUQoeE+l+SQ== sig=jeSuMXq6j7rmCXRrgSGoQkhokMME2Cfk4RQnocxoaJufYJ9th6vZeT+d1Jtyg8S4FY/jgjAoIICKQxjVfdxDDA== e=found last=13 s=30 in addShifted_NP",
            "pub=MCowBQYDK2VwAyEAKzRc+zT6RqQc5JpT6h86fryHv2+mZllEdrsnwQsUtIE= priv=MC4CAQAwBQYDK2VwBCIEIKm5UZRZXuN8EZXDwhsESptkGNZ8Hs7lh59p7eO6d6UB msg=BEqbZBjWfB7O5Yefae3junelAascYAIaue4TzLeyQYHvaUc9akhXpwL/0kMErGYWWJ2tJipXnJQzMHhaE6EHCg== sig=WwRz+nQ/SNUN1rjU7tt/AmfjnQRnRMNns1drxDGEbJcUBoIDHxJZxZaxvP5xBBpOzEqe+M+Ga7MRu3ePOMO9BA== e=found last=13 s=31 in addShifted_NP",
            "pub=MCowBQYDK2VwAyEAmZlleu/HD5HbPDf/cmpOLe0aiDY+3hksDgjeSgfvg6s= priv=MC4CAQAwBQYDK2VwBCIEIJXmL1p+KueyAWLyJ3DkXjAEyKps3I+SHBuuD4WwWhJZ msg=5sgIrM4cdQR4iHvCz/qerrKpcQZ8HiWS9YdOItHHHsdHt9ZH+QK6MLUVN7NgegGl/1MRVlPZ9oDvVzzcuZbnAQ== sig=v26b6Lj7k38MwRqchaT+Me5DGrUL4RpWq3PEbUDwePxGxCZmmpCk8mUXu+Bbf8Q3o9ic+Wb72noT1Q4VgnXdAA== e=found last=13 s=32 in addShifted_NP",
            "pub=MCowBQYDK2VwAyEAm+TQGrX9GHO4UnbOictk3C9r57tMuHii5sM2a8GMTbs= priv=MC4CAQAwBQYDK2VwBCIEICEN4iLrQutrk57jfvU4uGSQH5xk+JNJLuPh5Sbia2jq msg=O/chDeIi60Lra5Oe4371OLh


Triggers);

        var group = groupInstance.getLuaGroup();
        var toCreate = new ArrayList<GameEntity>();
        toCreate.addAll(getGadgetsInGroupSuite(groupInstance, suite));
        toCreate.addAll(getMonstersInGroupSuite(groupInstance, suite));
        addEntities(toCreate);

        registerRegionInGroupSuite(group, suite);
    }

    public void removeGroupSuite(SceneGroup group, SceneSuite suite) {
        deregisterTrigger(suite.sceneTriggers);
        removeMonstersInGroup(group, suite);
        removeGadgetsInGroup(group, suite);

        suite.sceneRegions.forEach(this::deregisterRegion);
    }

    public void killGroupSuite(SceneGroup group, SceneSuite suite) {
        deregisterTrigger(suite.sceneTriggers);

        killMonstersInGroup(group, suite);
        killGadgetsInGroup(group, suite);

        suite.sceneRegions.forEach(this::deregisterRegion);
    }

    public void startMonsterTideInGroup(
            String source, SceneGroup group, Integer[] ordersConfigId, int tideCount, int sceneLimit) {
        this.scriptMonsterTideService =
                new ScriptMonsterTideService(this, source, group, tideCount, sceneLimit, ordersConfigId);
    }

    public void unloadCurrentMonsterTide() {
        if (this.getScriptMonsterTideService() == null) {
            return;
        }
        this.getScriptMonsterTideService().unload();
    }

    public void spawnMonstersByConfigId(SceneGroup group, int configId, int delayTime) {
        // TODO delay
        var entity = scene.getEntityByConfigId(configId, group.id);
        if (entity != null && entity.getGroupId() == group.id) {
            Grasscutter.getLogger()
                    .debug("entity already exists failed in group {} with config {}", group.id, configId);
            return;
        }
        entity = createMonster(group.id, group.block_id, group.monsters.get(configId));
        if (entity != null) {
            getScene().addEntity(entity);
        } else {
            Grasscutter.getLogger()
                    .warn("failed to create entity with group {} and config {}", group.id, configId);
        }
    }
    // Events
    public Future<?> callEvent(int groupId, int eventType) {
        return callEvent(new ScriptArgs(groupId, eventType));
    }

    /**
     * 使用ThreadLocal传递SceneScriptManager的上下文到ScriptLib，以避免为每个场景实例的组触发器重复执行脚本评估。
     * 但当在ScriptLib的函数中调用callEvent时，可能导致空指针异常（NPE）：
     * 原因是内部调用会清理ThreadLocal，导致外部调用无法获取上下文（示例流程：CallEvent → 设置 → ScriptLib.xxx → CallEvent → 设置 → 移除 → NPE）。
     * 因此，通过线程池异步执行任务来清理调用栈，避免此问题。
     */
    public Future<?> callEvent(@Nonnull ScriptArgs params) {
        try {
            return eventExecutor.submit(() -> this.realCallEvent(params));
        } catch (RejectedExecutionException e) {
            Grasscutter.getLogger().warn("callEvent 任务被线程池拒绝，尝试同步执行", e);
            this.realCallEvent(params); // 直接在调用线程执行
            return null;
        }
    }

    private void realCallEvent(@Nonnull ScriptArgs params) {
        try {
            ScriptLoader.getScriptLib().setSceneScriptManager(this);

            var eventType = params.type;
            var relevantTriggers =
                    switch (eventType) {
                        case EventType.EVENT_ENTER_REGION, EventType.EVENT_LEAVE_REGION -> this
                                .getTriggersByEvent(eventType)
                                .stream()
                                .filter(
                                        t ->
                                                (t.getName().length() <= 12
                                                                || t.getName().substring(13).equals(String.valueOf(params.param1)))
                                                        && (t


  const l = new Line({
        p1: [0, 0, 0],
        length: Math.sqrt(8),
        direction: [1, 1, 0],
      });
      expect(l.p1).toEqual(point(0, 0, 0));
      expect(l.p2.round()).toEqual(point(2, 2, 0));
      expect(l.ends).toBe(2);
    });
    test('Mag and Direction Vector 2', () => {
      const l = new Line({
        p1: [0, 0, 0],
        length: Math.sqrt(3 * 2 * 2),
        direction: [1, 1, 1],
      });
      expect(l.p1).toEqual(point(0, 0, 0));
      expect(l.p2.round()).toEqual(point(2, 2, 2));
      expect(l.ends).toBe(2);
    });
    test('Ends', () => {
      const l = new Line([0, 0, 0], [1, 1, 1], 1);
      expect(l.p1).toEqual(point(0, 0, 0));
      expect(l.p2.round()).toEqual(point(1, 1, 1));
      expect(l.ends).toBe(1);
    });
    test('Options Ends override', () => {
      const l = new Line({
        p1: [0, 0, 0],
        p2: [1, 1, 1],
        ends: 1,
      }, [], 0);
      expect(l.p1).toEqual(point(0, 0, 0));
      expect(l.p2.round()).toEqual(point(1, 1, 1));
      expect(l.ends).toBe(1);
    });
  });
  describe('Distance and Angles', () => {
    test('[0, 0, 0], [1, 0, 0]', () => {
      const l = new Line([0, 0, 0], [1, 0, 0]);
      expect(round(l.theta())).toEqual(round(Math.PI / 2));
      expect(round(l.phi())).toEqual(round(0));
      expect(round(l.length())).toEqual(round(1));
    });
    test('[0, 0, 0], [0, 0, 1]', () => {
      const l = new Line([0, 0, 0], [0, 0, 1]);
      expect(round(l.theta())).toEqual(round(0));
      expect(round(l.phi())).toEqual(round(0));
      expect(round(l.length())).toEqual(round(1));
    });
    test('[0, 0, 0], [0, 1, 0]', () => {
      const l = new Line([0, 0, 0], [0, 1, 0]);
      expect(round(l.theta())).toEqual(round(Math.PI / 2));
      expect(round(l.phi())).toEqual(round(Math.PI / 2));
      expect(round(l.length())).toEqual(round(1));
    });
    test('[1, 1, 1], [1, 2, 1]', () => {
      const l = new Line([1, 1, 1], [1, 2, 1]);
      expect(round(l.theta())).toEqual(round(Math.PI / 2));
      expect(round(l.phi())).toEqual(round(Math.PI / 2));
      expect(round(l.length())).toEqual(round(1));
    });
    test('[1, 1, 1], [0, 0, 0]', () => {
      const l = new Line([1, 0, 1], [0, 0, 0]);
      expect(round(l.theta())).toEqual(round(Math.PI / 4 * 3));
      expect(round(l.phi())).toEqual(round(Math.PI));
      expect(round(l.length())).toEqual(round(Math.sqrt(2)));
    });
  });
  describe('reverse', () => {
    test('[0, 0, 0], [1, 0, 0]', () => {
      const l = new Line([0, 0, 0], [1, 0, 0


控制梳理检测的阀值。它实质上控制“强烈”或“可见”的交错必须被检测到。大的值意味着必须有更多差异才能被检验到，小的值则允许很少的交错（量）就会被检测到。有效值为-1（像素级的检测）到255（没有像素会被作为交错检验出来），这基本上是一个像素值的差异，好的范围是[8, 12].

    默认为9.
chroma

    决定是否把色度检测包含在匹配模式中。如果源中存在色度问题（彩虹）则必需要禁用。实际上设置`chroma=0`通常就足够可靠了，除非你确实在源中包含了色度需要被检测

    默认为0.
blockx
blocky

    设置检测窗的x和y轴尺寸。它协同`combpel`领域像素一起来声明梳理框架。参考`combpel`介绍了解更多信息。可能值是2的幂数，从4到512。

    默认为16.
combpel

    在梳理检测窗中梳理像素的数量。虽然`cthresh`控制了必须是“可见”的才被梳理（即精度），而这个参数控制了在局部（检测窗）中有“多少”则被检出，最小为0，最大为`blocky x blockx`（它们定义了整个检测窗）。它类似于TFM/VFM中的MI

    默认为80.

#### p/c/n/u/b的意义 ####

##### p/c/n #####
我们假定有下如下的电视电影流：

	Top fields:     1 2 2 3 4
	Bottom fields:  1 2 3 4 4

对应的数字对应需处理的场。在这里前2帧是需要的，3和4则被梳理，等等

当`fieldmatch`被配置运行在`field=bottom`时，输入流被如下传输：

	输入流:
		T     1 2 2 3 4
	    B     1 2 3 4 4   <-- 匹配参考

	匹配检测:  c c n n c

	输出流:
	    T     1 2 3 4 4
	    B     1 2 3 4 4

作为一个场匹配的结果，我们可以看到一些帧被复制了。为了完整实现电视电影的逆转换，你需要依靠后续的滤镜去除掉重复的帧。参考[`decimate`](#decimate)滤镜。

如果相同的处理但配置为`field=top`，结果会：

	输入流:
		T     1 2 2 3 4		<-- 匹配参考
	    B     1 2 3 4 4

	匹配检测:  c c p p c

	输出流:
	    T     1 2 2 3 4
	    B     1 2 2 3 4

在这些例子里，我们可以看出`p`、`c`和`n`的意义。基本上，它们指出参考帧的位置（关系）

- p，匹配于前一帧
- c，�


OINT(i)				(0x070 + ((i) * 0x4))
#define     H1_REG_CHECKPOINT_CHECK0(x)			(((x) & 0xffff))
#define     H1_REG_CHECKPOINT_CHECK1(x)			(((x) & 0xffff) << 16)
#define     H1_REG_CHECKPOINT_RESULT(x)			((((x) >> (16 - 16 \
							 * (i & 1))) & 0xffff) \
							 * 32)
#define H1_REG_CHKPT_WORD_ERR(i)			(0x084 + ((i) * 0x4))
#define     H1_REG_CHKPT_WORD_ERR_CHK0(x)		(((x) & 0xffff))
#define     H1_REG_CHKPT_WORD_ERR_CHK1(x)		(((x) & 0xffff) << 16)
#define H1_REG_VP8_BOOL_ENC				0x08c
#define H1_REG_CHKPT_DELTA_QP				0x090
#define     H1_REG_CHKPT_DELTA_QP_CHK0(x)		(((x) & 0x0f) << 0)
#define     H1_REG_CHKPT_DELTA_QP_CHK1(x)		(((x) & 0x0f) << 4)
#define     H1_REG_CHKPT_DELTA_QP_CHK2(x)		(((x) & 0x0f) << 8)
#define     H1_REG_CHKPT_DELTA_QP_CHK3(x)		(((x) & 0x0f) << 12)
#define     H1_REG_CHKPT_DELTA_QP_CHK4(x)		(((x) & 0x0f) << 16)
#define     H1_REG_CHKPT_DELTA_QP_CHK5(x)		(((x) & 0x0f) << 20)
#define     H1_REG_CHKPT_DELTA_QP_CHK6(x)		(((x) & 0x0f) << 24)
#define H1_REG_VP8_CTRL0				0x090
#define H1_REG_RLC_CTRL					0x094
#define     H1_REG_RLC_CTRL_STR_OFFS_SHIFT		23
#define     H1_REG_RLC_CTRL_STR_OFFS_MASK		(0x3f << 23)
#define     H1_REG_RLC_CTRL_RLC_SUM(x)			((x))
#define H1_REG_MB_CTRL					0x098
#define     H1_REG_MB_CNT_OUT(x)			(((x) & 0xffff))
#define     H1_REG_MB_CNT_SET(x)			(((x) & 0xffff) << 16)
#define H1_REG_ADDR_NEXT_PIC				0x09c
#define	H1_REG_JPEG_LUMA_QUAT(i)			(0x100 + ((i) * 0x4))
#define	H1_REG_JPEG_CHROMA_QUAT(i)			(0x140 + ((i) * 0x4))
#define H1_REG_STABILIZATION_OUTPUT			0x0A0
#define H1_REG_ADDR_CABAC_TBL				0x0cc
#define H1_REG_ADDR_MV_OUT				0x0d0
#define H1_REG_RGB_YUV_COEFF(i)				(0x0d4 + ((i) * 0x4))
#define H1_REG_RGB_MASK_MSB				0x0dc
#define H1_REG_INTRA_AREA_CTRL				0x0e0
#define H1_REG_CIR_INTRA_CTRL				0x0e4
#define H1_REG_INTRA_SLICE_BITMAP(i)			(0x0e8 + ((i) * 0x4))
#define H1_REG_ADDR_VP8_DCT_PART(i)			(0x0e8 + ((i) * 0x4))
#define H1_REG_FIRST_ROI_AREA				0x0f0
#define H1_REG_SECOND_ROI_AREA				0x0f4
#define H1_REG_MVC_CTRL					0x0f8
#define	H1_REG_MVC_CTRL_MV16X16_FAVOR(x)		((x) << 28)
#define H1_REG_VP8_INTRA_PENALTY(i)			(0x100 + ((i) * 0x4))
#define H1_REG_ADDR_VP8_SEG_MAP				0x11c
#define H1_REG_VP8_SEG_QP(i)				(0x120 + ((i) * 0x4))
#define H1_REG_DMV_4P_1P_PENALTY(i)			(0x180 + ((i) * 0x4))
#define     H1_REG_DMV_4P_1P_PENALTY_BIT(x, i)		((x) << (i) * 8)
#define H1_REG_DMV_QPEL_PENALTY(i)			(0x200 + ((i) * 0x4))
#define     H1_REG_DMV_QPEL_PENALTY_BIT(x, i)		((x) << (i) * 8)
#define H1_REG_VP8_CTRL1				0x280
#define H1_REG_VP8_BIT_COST_GOLDEN			0x284
#define H1_REG_VP8_LOOP_FLT_DELTA(i)			(0x288 + ((i) * 0x4))

#endif /* HANTRO_H1_REGS_H_ */


�ถของระบบ ด้วยเหตุนี้จึงส่งผลให้เกิดเวลาแฝงและการหยุดชะงักของสายที่กำลังโทร รวมถึงทำให้การโทรออกหรือรับสายใหม่ล้มเหลว

หากไม่มีการปกป้องอย่างเหมาะสม การรีบเร่งเพื่อสร้างประสบการณ์การโทรที่ยอดเยี่ยมจะมาพร้อมต้นทุนด้านความปลอดภัย ซึ่งผู้โจมตีก็เรียนรู้ที่จะใช้ประโยชน์จากสิ่งนี้

การโจมตีเซิร์ฟเวอร์ VoIP ด้วย DDoS

ผู้โจมตีสามารถใช้ประโยชน์จาก UDP และโปรโตคอล SIP ในการกระหน่ำจู่โจมเซิร์ฟเวอร์ VoIP ที่ไม่มีการปกป้องด้วยแพ็คเก็ต UDP จำนวนมหาศาลที่สร้างขึ้นมาเป็นพิเศษ วิธีการหนึ่งที่ผู้โจมตีกระหน่ำจู่โจมเซิร์ฟเวอร์ VoIP คือโดยการทำให้หลงเชื่อว่าเริ่มต้นการโทร โดยในแต่ละครั้งที่มีการส่งคำขอเริ่มต้นการโทรที่ประสงค์ร้ายไปหาเหยื่อ เซิร์ฟเวอร์ของเหยื่อจะใช้ความสามารถเชิงคำนวณและหน่วยความจำเพื่อยืนยันความถูกต้องของคำขอนั้นๆ หากสามารถสร้างการเริ่มต้นการโทรเป็นจำนวนที่มากพอ ผู้โจมตีก็จะสามารถกระหน่ำจู่โจมเซิร์ฟเวอร์ของเหยื่อ และป้องกันไม่ให้เซิร์ฟเวอร์ประมวลผลการโทรปกติได้ และนี่คือเทคนิค DDoS แบบคลาสสิกที่ใช้กับ SIP

	<figure class="kg-card k


  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 997;
  font-size: 13px;
  letter-spacing: 0.2px;
  font-weight: 500;
  height: 60px;
  padding: 0 20px;
  background-color: #FFFFFF;
  border-bottom: 1px solid #EAEDF3; }
@media (min-width: 1023px) {
  .topnav {
    font-size: 14px;
    height: 80px;
    padding: 0 36px;
    position: relative; } }
.topnav .logo, .topnav .language-selector {
  display: none; }
@media (min-width: 1023px) {
  .topnav .logo, .topnav .language-selector {
    display: block; } }
.topnav .logo > img {
  image-rendering: auto; }
.topnav .logo > img:first-of-type {
  margin-right: 8px;
  height: 26px; }
.topnav .logo > img:nth-of-type(2) {
  height: 21px;
  top: 1px;
  position: relative; }
.topnav .logo:hover {
  opacity: 0.9; }
.topnav .nav-link {
  padding: 12px;
  top: 3px;
  position: relative; }
.topnav .nav-link span.hide-mobile {
  display: none; }
@media (min-width: 1023px) {
  .topnav .nav-link span.hide-mobile {
    display: inline-block; } }
.topnav .avatar-menu .nav-link {
  padding: 12px 0 12px 12px;
  top: 0px; }
.topnav .avatar-menu .nav-link:hover {
  opacity: 0.9; }
.topnav .topnav-list {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: baseline;
  -webkit-align-items: baseline;
  -ms-flex-align: baseline;
  align-items: baseline;
  position: relative;
  top: -1px; }
.topnav .topnav-list .avatar-menu {
  display: none; }
@media (min-width: 1023px) {
  .topnav .topnav-list .avatar-menu {
    display: inline-block;
    top: 0; } }
.topnav a {
  color: #484B4A; }
.topnav a:hover {
  color: #0d2c4f; }
.topnav img.user-avatar {
  width: 36px;
  border-radius: 50%; }
@media (min-width: 1023px) {
  .topnav img.user-avatar {
    width: 45px; } }

.mobilemenu-top-home {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  position: relative;
  top: 2px; }
@media (min-width: 1023px) {
  .mobilemenu-top-home {
    display: none; } }
.mobilemenu-top-home svg {
  top: -1px;
  position: relative;
  margin-right: 1px; }
@media only screen and (max-width: 330px) {
  .mobilemenu-top-home span.hide-small-mobile {
    display: none


Holy Night's Embrace\"! Heck, this is Pulitzer Prize material!",
			flashout = {
				dur = 0.35,
				black = false,
				alpha = {
					0,
					1
				}
			},
			flashin = {
				delay = 1,


py random variable into a RandomVariableFromDoubleArray to ensure that an alternative implementation is used
		final RandomVariable[] randomVariablesValues = new RandomVariable[randomVariables.length];
		for(int j = 0; j < numberOfRandomVariables; j++) {
			randomVariablesValues[j] = new RandomVariableFromDoubleArray(randomVariables[j]);

		}

		final long startFD = System.currentTimeMillis();

		final RandomVariable[] gradientNumeric = new RandomVariable[numberOfRandomVariables];
		for(int j = 0; j < numberOfRandomVariables; j++) {

			final RandomVariable[] randomVariables_p = randomVariablesValues.clone();
			final RandomVariable[] randomVariables_m = randomVariablesValues.clone();

			randomVariables_p[j] = randomVariablesValues[j].add(epsilon);
			randomVariables_m[j] = randomVariablesValues[j].sub(epsilon);

			/* df(x_1,...,x_n)/dx_i = (f(x_1 ,...,x_i + \epsilon,...,x_n) - f(x_1 ,...,x_i - \epsilon,...,x_n))/(2 * \epsilon) */
			gradientNumeric[j] = testFunction(randomVariables_p).sub(testFunction(randomVariables_m)).div(2*epsilon);
		}
		final long endFD = System.currentTimeMillis();

		System.out.println("Time needed for AAD (" + randomVariableFactory.getClass().getSimpleName() + "): " + ((endAAD - startAAD) / 1000.0) + "s");
		System.out.println("Time needed for FD: " + ((endFD - startFD) / 1000.0) + "s");

		for(int i=0; i<gradientNumeric.length;i++) {
			final RandomVariable diffNumeric = gradientNumeric[i];
			final RandomVariable diffAutoDiff =  gradientAutoDiff.get(((RandomVariableDifferentiable)randomVariables[i]).getID());
			final double errorL1 = diffNumeric.sub(diffAutoDiff).abs().getAverage();
			/* if the average of the absolute error is not too big give okay*/
			Assert.assertEquals(0.0, errorL1, delta);
			//			Assert.assertEquals(0.0, gradientNumeric[i].sub(gradientAutoDiff.get(keys[i])).abs().getAverage(), delta);
		}
	}

	private RandomVariable testFunction(final RandomVariable[] randomVariables){

		RandomVariable result = randomVariables[0];
		for(int i = 1; i < randomVariables.length; i++) {
			result = result.addProduct(randomVariables[i-1].abs(), randomVariables[i].exp());
		}

		result = result.cap(randomVariables[randomVariables.length-1]).add(result.cap(randomVariables[randomVariables.length-1]));

		return result;
	}
}
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE129_Improper_Validation_of_Array_Index__Property_array_write_no_check_54d.java
Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml
Template File: sources-sinks-54d.tmpl.java
*/
/*
 * @description
 * CWE: 129 Improper Validation of Array Index
 * BadSource: Property Read data from a system property
 * GoodSource: A hardcoded non-zero, non-min, non-max, even number
 * Sinks: array_write_no_check
 *    GoodSink: Write to array after verifying index
 *    BadSink : Write to array without any verification of index
 * Flow Variant: 54 Data flow: data passed as an argument from one method through three others to a fifth; all five functions are in different classes in the same package
 *
 * */

package testcases.CWE129_Improper_Validation_of_Array_Index.s04;
import testcasesupport.*;

import javax.servlet.http.*;

public class CWE129_Improper_Validation_of_Array_Index__Property_array_write_no_check_54d
{
    public void badSink(int data ) throws Throwable
    {
        (new CWE129_Improper_Validation_of_Array_Index__Property


_struct.n == 1;
  if (x_struct.n != y_struct.m && !x_is_scalar && !y_is_scalar) {
    PyErr_Format(
        PyExc_ValueError, "Incompatible matrix sizes (%d, %d), (%d, %d)",
        (int)x_struct.m, (int)x_struct.n, (int)y_struct.m, (int)y_struct.n);
    return NULL;
  }
  npy_intp out_dims[2];
  if (x_is_scalar) {
    out_dims[0] = y_struct.m;
    out_dims[1] = y_struct.n;
  } else if (y_is_scalar) {
    out_dims[0] = x_struct.m;
    out_dims[1] = x_struct.n;
  } else {
    out_dims[0] = x_struct.m;
    out_dims[1] = y_struct.n;
  }
  PyArrayObject* out_item =
      (PyArrayObject*)PyArray_EMPTY(2, out_dims, NPY_FLOAT32, 0);
  float* out_data = (float*)PyArray_DATA(out_item);
  if (x_is_scalar) {
    const float x_val = *x_struct.data;
    const float* y_ptr = y_struct.data;
    for (npy_intp r = 0; r < y_struct.m; r++) {
      for (npy_intp c = 0; c < y_struct.n; c++)
        *out_data++ = x_val * *(y_ptr + c * y_struct.col_stride);
      y_ptr += y_struct.row_stride;
    }
  } else if (y_is_scalar) {
    const float* x_ptr = x_struct.data;
    const float y_val = *y_struct.data;
    for (npy_intp r = 0; r < x_struct.m; r++) {
      for (npy_intp c = 0; c < x_struct.n; c++)
        *out_data++ = *(x_ptr + c * x_struct.col_stride) * y_val;
      x_ptr += x_struct.row_stride;
    }
  } else {
    const float* x_ptr = x_struct.data;
    for (npy_intp r = 0; r < out_dims[0]; r++) {
      const float* y_ptr = y_struct.data;
      for (npy_intp c = 0; c < out_dims[1]; c++) {
        *out_data = 0.0f;
        for (npy_intp k = 0; k < x_struct.n; k++)
          *out_data += *(x_ptr + k * x_struct.col_stride) *
                       *(y_ptr + k * y_struct.row_stride);
        out_data++;
        y_ptr += y_struct.col_stride;
      }
      x_ptr += x_struct.row_stride;
    }
  }
  return (PyObject*)out_item;
}

static PyObject* _dot(PyObject* self, PyObject* args) {
  PyObject *X, *Y;
  ListItem x_struct, y_struct;
  Py_ssize_t x_len, y_len, out_len;
  if (!extract_operands_to_binop(out_len, X, x_len, x_struct, Y, y_len,
                                 y_struct, args))
    return NULL;

  PyObject* out_list = PyList_New(out_len);
  for (Py_ssize_t i = 0; i < out_len; i++) {
    if (x_len != 1) {
      PyObject* x_item = PyList_GetItem(X, i);
      if (!extract_scalar_or_array(x_struct, x_item, i, "left ")) return NULL;
    }
    if (y_len != 1) {
      PyObject* y_item = P


display_number(&display_pattern).to_string();
    }

    result
        .parse()
        .expect(&format!("Could not parse u32: {}", result))
}

fn get_unique_signal_pattern_wires(unique_signal_pattern: &str) -> HashSet<Wire> {
    unique_signal_pattern
        .chars()
        .map(|c| Wire::from(c))
        .collect()
}

fn get_patterns_and_displays(input: &str) -> (Vec<String>, Vec<String>) {
    let (patterns, displays) = input
        .split_once(" | ")
        .expect(&format!("Could not split ' | ' on: {}", input));

    let patterns_vec = patterns.split(' ').map(|s| s.to_string()).collect();
    let displays_vec = displays.split(' ').map(|s| s.to_string()).collect();

    (patterns_vec, displays_vec)
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_INPUT: &str =
        "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf";

    const TEST_UNIQUE_SIGNAL_PATTERNS: [&str; 10] = [
        "acedgfb", "cdfbe", "gcdfa", "fbcad", "dab", "cefabd", "cdfgeb", "eafb", "cagedb", "ab",
    ];
    const TEST_DISPLAY_PATTERNS: [&str; 4] = ["cdfeb", "fcadb", "cdfeb", "cdbaf"];
    const TEST_DATA: [&str; 10] = [
        "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe",
        "edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc",
        "fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg",
        "fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb",
        "aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea",
        "fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb",
        "dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe",
        "bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef",
        "egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb",
        "gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce",
    ];

    #[test]
    fn test_display_get_1_wires() {
        let input: Vec<String> = TEST_UNIQUE_SIGNAL_PATTERNS
            .iter()
            .map(|s| s.to_string())
            .collect();

        let expected = [Wire::A, Wire::B].into_iter().collect();

        let result = Display::get_1_wires(&input);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_display_get_4_wires() {
        let input: Vec<String> = TEST_UNIQUE_SIGNAL_PATTERNS
            .iter()
            .map(|s| s.to_string())
            .collect();

        let expected = [Wire::E, Wire::A, Wire::F, Wire::B].into_iter().collect();

        let result =


using Cofoundry.Domain.Data;

namespace Cofoundry.Domain.Internal;

public class GetUpdateCustomEntityDraftVersionCommandByIdQueryHandler
    : IQueryHandler<GetPatchableCommandByIdQuery<UpdateCustomEntityDraftVersionCommand>, UpdateCustomEntityDraftVersionCommand?>
    , IIgnorePermissionCheckHandler
{
    private readonly CofoundryDbContext _dbContext;
    private readonly ICustomEntityDataModelMapper _customEntityDataModelMapper;
    private readonly IPermissionValidationService _permissionValidationService;

    public GetUpdateCustomEntityDraftVersionCommandByIdQueryHandler(
        CofoundryDbContext dbContext,
        ICustomEntityDataModelMapper customEntityDataModelMapper,
        IPermissionValidationService permissionValidationService
        )
    {
        _dbContext = dbContext;
        _customEntityDataModelMapper = customEntityDataModelMapper;
        _permissionValidationService = permissionValidationService;
    }

    public async Task<UpdateCustomEntityDraftVersionCommand?> ExecuteAsync(GetPatchableCommandByIdQuery<UpdateCustomEntityDraftVe


 Expo.png)

 Circ:

 Displays a Circular transition.

 >Trans.Circ.easeIn
 >Trans.Circ.easeOut
 >Trans.Circ.easeInOut

 (see Circ.png)

 Sine:

 Displays a Sineousidal transition.

 >Trans.Sine.easeIn
 >Trans.Sine.easeOut
 >Trans.Sine.easeInOut

 (see Sine.png)

 Back:

 >Trans.Back.easeIn
 >Trans.Back.easeOut
 >Trans.Back.easeInOut

 (see Back.png)

 Bounce:

 Bouncy transition.

 >Trans.Bounce.easeIn
 >Trans.Bounce.easeOut
 >Trans.Bounce.easeInOut

 (see Bounce.png)

 Elastic:

 Elastic curve.

 >Trans.Elastic.easeIn
 >Trans.Elastic.easeOut
 >Trans.Elastic.easeInOut

 (see Elastic.png)

 Based on:

 Easing and Transition animation methods are based in the MooTools Framework <http://mootools.net>. Copyright (c) 2006-2010 Valerio Proietti, <http://mad4milk.net/>. MIT license <http://mootools.net/license.txt>.

*/
Options.Fx = {
  $extend: true,

  fps:40,
  duration: 2500,
  transition: $jit.Trans.Quart.easeInOut,
  clearCanvas: true
};

/*
 * File: Options.Label.js
 *
*/
/*
  Object: Options.Label

  Provides styling for Labels such as font size, family, etc. Also sets Node labels as HTML, SVG or Native canvas elements.

  Syntax:

  (start code js)
    Options.Label = {
      overridable: false,
      type: 'HTML', //'SVG', 'Native'
      style: ' ',
      size: 10,
      family: 'sans-serif',
      textAlign: 'center',
      textBaseline: 'alphabetic',
      color: '#fff'
    };
  (end code)

  Example:

  (start code js)
  var viz = new $jit.Viz({
    Label: {
      type: 'Native',
      size: 11,
      color: '#ccc'
    }
  });
  (end code)

  Parameters:

  overridable - (boolean) Default's *false*. Determine whether or not general label properties can be overridden by a particular <Graph.Node>.
  type - (string) Default's *HTML*. The type for the labels. Can be 'HTML', 'SVG' or 'Native' canvas labels.
  style - (string) Default's *empty string*. Can be 'italic' or 'bold'. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use <Options.Controller> methods to style individual labels.
  size - (number) Default's *10*. The font's size. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use <Options.Controller> methods to style individual labels.
  family - (string) Default's *sans-serif*. The font's family. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use <Options.Controller> methods to style individual labels.
  color - (string) Default's *#fff*. The font's color. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use <Options.Controller> methods to style individual labels.
*/
Options.Label = {
  $extend: false,

  overridable: false,
  type: 'HTML', //'SVG', 'Native'
  style: ' ',
  size: 10,
  family:


link" href="https://recipya.musicavis.ca/about/changelog/v1.3.0" target="_blank">release notes

 <button class="btn btn-sm" hx-get="/update/check" hx-target="#settings_about" hx-swap="outerHTML" hx-indicator="#settings_about_update_check">Check for updates</button>

`,
		}
		assertStringsInHTML(t, getBodyHTML(rr), want)
	})
}

func TestHandlers_Settings_BackupsRestore(t *testing.T) {
	srv, ts, c := createWSServer()
	defer c.CloseNow()

	originalFiles := srv.Files
	originalRepo := srv.Repository

	uri := ts.URL + "/settings/backups/restore"

	t.Run("must be logged in", func(t *testing.T) {
		assertMustBeLoggedIn(t, srv, http.MethodPost, uri)
	})

	testcases := []struct {
		name string
		in   string
	}{
		{name: "empty body", in: ""},
		{name: "date is empty", in: "date="},
		{name: "date is invalid", in: "date=01/02/1999"},
		{name: "date contains letters", in: "date=01 January 2024"},
	}
	for _, tc := range testcases {
		t.Run(tc.name, func(t *testing.T) {
			rr := sendHxRequestAsLoggedIn(srv, http.MethodPost, uri, formHeader, strings.NewReader(tc.in))

			assertStatus(t, rr.Code, http.StatusBadRequest)
			_, after, _ := strings.Cut(tc.in, "=")
			message := fmt.Sprintf(`{"type":"toast","fileName":"","data":"","toast":{"action":"","background":"alert-error","message":"%s is an invalid backup.","title":"Form Error"}}`, after)
			assertWebsocket(t, c, 1, message)
		})
	}

	t.Run("backup user data failed", func(t *testing.T) {
		srv.Files = &mockFiles{
			backupUserDataFunc: func(_ services.RepositoryService, _ int64) error {
				return errors.New("could not backup data")
			},
		}
		defer func() {
			srv.Files = originalFiles
		}()

		rr := sendHxRequestAsLoggedIn(srv, http.MethodPost, uri, formHeader, strings.NewReader("date=2006-01-02"))

		assertStatus(t, rr.Code, http.StatusInternalServerError)
		assertWebsocket(t, c, 1, `{"type":"toast","fileName":"","data":"","toast":{"action":"","background":"alert-error","message":"Failed to backup current data.","title":"Files Error"}}`)
	})

	t.Run("extract user backup failed", func(t *testing.T) {
		srv.Files = &mockFiles{
			extractUserBackupFunc: func(date string, userID int64) (*models.UserBackup, error) {
				return nil, errors.New("backup failed")
			},
		}
		defer func() {
			srv.Files = originalFiles
		}()

		rr := send


 mdmsDocs.map(mdmsDoc => {
    let applicationDocument = {}
    applicationDocuments && applicationDocuments.map(appDoc => {
      if (appDoc.documentType == mdmsDoc.code) {
        applicationDocument = { ...appDoc }
      }
    })
    return applicationDocument;
  }
  ).filter(docObj => Object.keys(docObj).length > 0)
  applicationDocuments = [...orderedApplicationDocuments];
  dispatch(
    prepareFinalObject("FireNOCs[0].fireNOCDetails.additionalDetail.documents", applicationDocuments)
  );

  let uploadedDocuments = {};
  let fileStoreIds =
    applicationDocuments &&
    applicationDocuments.map(item => item.fileStoreId).join(",");
  const fileUrlPayload =
    fileStoreIds && (await getFileUrlFromAPI(fileStoreIds));
  applicationDocuments &&
    applicationDocuments.forEach((item, index) => {
      uploadedDocuments[index] =
      {
        fileName:
          (fileUrlPayload &&
            fileUrlPayload[item.fileStoreId] &&
            decodeURIComponent(
              getFileUrl(fileUrlPayload[item.fileStoreId])
                .split("?")[0]
                .split("/")
                .pop()
                .slice(13)
            )) ||
          `Document - ${index + 1}`,
        fileStoreId: item.fileStoreId,
        fileUrl: Object.values(fileUrlPayload)[index],
        documentType: item.documentType,
        tenantId: item.tenantId,
        id: item.id
      }

    });

  dispatch(
    prepareFinalObject("documentsUploadRedux", uploadedDocuments)
  );
};

export const createUpdateNocApplication = async (state, dispatch, status) => {
  let nocId = get(
    state,
    "screenConfiguration.preparedFinalObject.FireNOCs[0].id"
  );

  let method = nocId ? "UPDATE" : "CREATE";
  if (getQueryArg(window.location.href, "action") == 'edit') {
    method = 'edit'
  }
  try {
    let payload = get(
      state.screenConfiguration.preparedFinalObject,
      "FireNOCs",
      []
    );
    let tenantId = get(
      state.screenConfiguration.preparedFinalObject,
      "FireNOCs[0].fireNOCDetails.propertyDetails.address.city",
      getTenantId()
    );
    set(payload[0], "tenantId", tenantId);
    set(payload[0], "fireNOCDetails.action", status);

    // Get uploaded documents from redux
    let reduxDocuments = get(
      state,
      "screenConfiguration.preparedFinalObject.documentsUploadRedux",
      {}
    );

    let isDocumentValid = true;
    // Object.keys(reduxDocuments).map((key) => {
    //   // if (reduxDocuments[key].documentType === "OWNER" && reduxDocuments[key].documents && reduxDocuments[key].documents.length > 0 && !(reduxDocuments[key].dropdown && reduxDocuments[key].dropdown.value)) {
    //     if (reduxDocuments[key].documentType === "OWNER" && reduxDocuments[key].documents && reduxDocuments[key].documents.length > 0 && !(reduxDocuments[key].dropdown && reduxDocuments[key].dropdown.value)) {
    //     isDocumentValid = false;
    //   }
    // });
    if (!isDocumentValid) {
      dispatch(toggleSnackbar(true, { labelName: "Please select document type for uploaded document", labelKey: "ERR_DOCUMENT_TYPE_MISSING" }, "error"));
      return;
    }

    handleDeletedCards(payload[0], "fireNOCDetails.buildings", "id");
    handleDeletedCards(
      payload[0],
      "fireNOCDetails.applicantDetails.owners",
      "id"
    );

    let buildings = get(payload, "[0].fireNOCDetails.buildings", []);
    buildings.forEach((building, index) => {
      // GET UOMS FOR THE SELECTED BUILDING TYPE
      let requiredU


체했는지 확인
    final walletBTxList =
        ScriptSyncServiceMock.transactionRepository.getTransactionRecordList(testData.walletB.id);

    // 지갑 B에는 RBF 트랜잭션만 남아있어야 함 (초기 트랜잭션은 대체됨)
    final rbfTxExists =
        walletBTxList.any((tx) => tx.transactionHash == testData.rbfTx!.transactionHash);
    final initialTxExists =
        walletBTxList.any((tx) => tx.transactionHash == testData.mockTx.transactionHash);

    expect(rbfTxExists, true, reason: 'RBF 트랜잭션이 지갑 B에 존재해야 합니다.');
    expect(initialTxExists, false, reason: '초기 트랜잭션은 RBF로 인해 대체되어야 합니다.');

    final rbfTxRecord = ScriptSyncServiceMock.transactionRepository.getTransactionRecord(
      testData.walletA.id,
      testData.rbfTx!.transactionHash,
    )!;
    expect(rbfTxRecord.rbfHistoryList!.length, 2,
        reason: 'RBF 트랜잭션을 조회하면 RBF 트랜잭션 정보가 2개 존재해야 합니다.');

    // // B 지갑의 CPFP 트랜잭션이 제거되어야 함
    final cpfpTxExists =
        walletBTxList.any((tx) => tx.transactionHash == testData.cpfpTx!.transactionHash);
    expect(cpfpTxExists, false, reason: 'CPFP 트랜잭션은 부모 트랜잭션(초기 트랜잭션)이 RBF로 대체되면서 제거되어야 합니다.');

    // UTXO 상태도 확인
    final walletBUtxoList =
        ScriptSyncServiceMock.utxoRepository.getUtxoStateList(testData.walletB.id);
    final cpfpUtxoExists =
        walletBUtxoList.any((utxo) => utxo.transactionHash == testData.cpfpTx!.transactionHash);
    expect(cpfpUtxoExists, false,
        reason: 'CPFP 트랜잭션 관련 UTXO도 제거되어야 합니다. ${testData.cpfpTx!.transactionHash}');
  }
}
import 'package:coconut_wallet/model/utxo/utxo_state.dart';
import 'package:coconut_wallet/model/wallet/singlesig_wallet_list_item.dart';
import 'package:coconut_wallet/repository/realm/service/realm_id_service.dart';
import 'package:coconut_wallet/repository/realm/utxo_repository.dart';
import 'package:flutter_test/flutter_test.dart';

import '../../mock/transaction_mock.dart';
import '../../mock/utxo_mock.dart';
import '../../mock/wallet_mock.dart';
import 'test_realm_manager.dart';

void main() {
  late TestRealmManager realmManager;
  late UtxoRepository utxoRepository;
  SinglesigWalletListItem testWalletItem = WalletMock.createSingleSigWalletItem();
  const int testWalletId = 1;

  setUp(() async {
    realmManager = await setupTestRealmManager();
    utxoRepository = UtxoRepository(realmManager);
  });

  tearDown(() {
    realmManager.reset();
    realmManager.dispose();
  });

  group('UtxoRepository 기능 테스트', () {
    final testAddress = testWalletItem.walletBase.getAddress(0);
    final toAddress = testWalletItem.walletBase.getAddress(9999);
    g


	sv := VariableDecrypted{
		VariableMetadata: VariableMetadata{Namespace: "a"},
		Items:            VariableItems{"foo": "bar"},
	}

	testCases := []struct {
		path string
		ok   bool
	}{
		{path: ""},
		{path: "nomad"},
		{path: "nomad/other"},
		{path: "a/b/c", ok: true},
		{path: "nomad/jobs", ok: true},
		{path: "nomadjobs", ok: true},
		{path: "nomad/jobs/whatever", ok: true},
		{path: "example/_-~/whatever", ok: true},
		{path: "example/@whatever"},
		{path: "example/what.ever"},
		{path: "nomad/job-templates"},
		{path: "nomad/job-templates/whatever", ok: true},
	}
	for _, tc := range testCases {
		tc := tc
		sv.Path = tc.path
		err := sv.Validate()
		if tc.ok {
			must.NoError(t, err, must.Sprintf("should not get error for: %s", tc.path))
		} else {
			must.Error(t, err, must.Sprintf("should get error for: %s", tc.path))
		}
	}
}

func TestStructs_VariablesRenewLockRequest_Validate(t *testing.T) {
	ci.Parallel(t)

	testCases := []struct {
		name    string
		request *VariablesRenewLockRequest
		expErr  error
	}{
		{
			name: "missing_lockID",
			request: &VariablesRenewLockRequest{
				Path: "path",
			},
			expErr: errNoLock,
		},
		{
			name: "missing_path",
			request: &VariablesRenewLockRequest{
				LockID: "lockID",
			},
			expErr: errNoPath,
		},
		{
			name: "valid_request",
			request: &VariablesRenewLockRequest{
				Path:   "path",
				LockID: "lockID",
			},
			expErr: nil,
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			err := tc.request.Validate()
			if !errors.Is(err, tc.expErr) {
				t.Errorf("Expected error %v, but got error %v", tc.expErr, err)
			}
		})
	}
}

func TestStructs_Lock_Validate(t *testing.T) {
	ci.Parallel(t)

	testCases := []struct {
		name   string
		lock   *VariableLock
		expErr error
	}{
		{
			name: "lock_delay_is_negative",
			lock: &VariableLock{
				TTL:       5 * time.Second,
				LockDelay: -5 * time.Second,
			},
			expErr: errNegativeDelayOrTTL,
		},
		{
			name: "lock_ttl_is_negative",
			lock: &VariableLock{
				TTL:       -5 * time.Second,
				LockDelay: 5 * time.Second,
			},
			expErr: errNegativeDelayOrTTL,
		},
		{
			name: "lock_ttl_is_bigger_than_max",
			lock: &VariableLock{
				TTL:       maxVariableLockTTL + 5*time.Second,
				LockDelay: 5 * time.Second,
			},
			expErr: errInvalidTTL,
		},
		{
			name: "lock_ttl_is_smaller_than_min",
			lock: &VariableLock{
				TTL:       5 * time.Second,
				LockDelay: minVariableLockTTL - 5*time.Second,
			},
			expErr: errInvalidTTL,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			err := tc.lock.Validate()
			if !errors.Is(err, tc.expErr) {
				t.Errorf("Expected error %v, but got error %v", tc.expErr, err)
			}
		})
	}
}
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

package structs

import (
	"fmt"
	"regexp"
	"slices"
	"strings"
	"time"

	jwt "github.com/go-jose/go-jose/v3/jwt"
	"gi


in msi.gama.ext, is part of the source code of the
 * GAMA modeling and simulation platform (v.1.9.3).
 *
 * (c) 2007-2023 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU)
 *
 * Visit https://github.com/gama-platform/gama for license information and contacts.
 *
 ********************************************************************************************************/
package msi.gama.ext.kabeja.dxf;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import msi.gama.ext.kabeja.dxf.helpers.Point;

/**
 * @author Simon Mieth
 *
 */
public class DXFLeader extends DXFEntity {

	/** The style name. */
	protected String styleName = "";

	/** The arrow head size. */
	protected double arrowHeadSize = 0.0;

	/** The text gap. */
	protected double textGap;

	/** The scale factor. */
	protected double scaleFactor;

	/** The text width. */
	protected double textWidth;

	/** The text height. */
	protected double textHeight;

	/** The coordinates. */
	protected List<Point> coordinates = new ArrayList<>();

	/** The path type. */
	protected int pathType = 0;

	/** The creation type. */
	protected int creationType = 0;

	/** The hookline directon. */
	protected int hooklineDirecton = 0;

	/** The hookline. */
	protected boolean hookline = false;

	/** The horizontal direction. */
	protected Point horizontalDirection = new Point();

	/** The last offset text. */
	protected Point lastOffsetText = new Point();

	/** The last offset insertion. */
	protected Point lastOffsetInsertion = new Point();

	/** The arrow enabled. */
	protected boolean arrowEnabled = false;

	/** The text ID. */
	protected String textID = "";

	/**
	 * @return Returns the textID.
	 */
	public String getTextID() { return textID; }

	/**
	 * @param textID
	 *            The textID to set.
	 */
	public void setTextID(final String textID) { this.textID = textID; }

	/*
	 * (non-Javadoc)
	 *
	 * @see org.kabeja.dxf.DXFEntity#getBounds()
	 */
	@Override
	public Bounds getBounds() {
		Bounds bounds = new Bounds();
		bounds.setValid(false);

		return bounds;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.kabeja.dxf.DXFEntity#getType()
	 */
	@Override
	public String getType() { return DXFConstants.ENTITY_TYPE_LEADER; }

	/**
	 * @return Returns the arrowHeadSize.
	 */
	public double getArrowHeadSize() { return arrowHeadSize; }

	/**
	 * @param arrowHeadSize
	 *            The arrowHeadSize to set.
	 */
	public void setArrowHeadSize(final double arrowHeadSize) { this.arrowHeadSize = arrowHeadSize; }

	/**
	 * @return Returns the creationType.
	 */
	public int getCreationType() { return creationType; }

	/**
	 * @param creationType
	 *            The creationType to set.
	 */
	public void setCreationType(final int creationType) { this.creationType = creationType; }

	/**
	 * @return Returns the hookline.
	 */
	public boolean isHookline() { return hookline; }

	/**
	 * @param hookline
	 *            The hookline to set.
	 */
	public void setHookline(final boolean hookline) { this.hookline = hookline; }

	/**
	 * @return Returns the hooklineDirecton.
	 */
	public int getHooklineDirecton() { return hooklineDirecton; }

	/**
	 * @param hooklineDirecton
	 *            The hooklineDirecton to set.
	 */
	public void setHooklineDirecton(final int hooklineDirecton) { this.hooklineDirecton = hooklineDirecton; }

	/**
	 * @return Returns the horizontalDirection.
	 */
	publ


 != OpARM64SRLconst {
			break
		}
		c := x1.AuxInt
		y := x1.Args[0]
		if !(clobberIfDead(x1)) {
			break
		}
		v.reset(OpARM64BICshiftRL)
		v.AuxInt = c
		v.AddArg(x0)
		v.AddArg(y)
		return true
	}
	// match: (BIC x0 x1:(SRAconst [c] y))
	// cond: clobberIfDead(x1)
	// result: (BICshiftRA x0 y [c])
	for {
		_ = v.Args[1]
		x0 := v.Args[0]
		x1 := v.Args[1]
		if x1.Op != OpARM64SRAconst {
			break
		}
		c := x1.AuxInt
		y := x1.Args[0]
		if !(clobberIfDead(x1)) {
			break
		}
		v.reset(OpARM64BICshiftRA)
		v.AuxInt = c
		v.AddArg(x0)
		v.AddArg(y)
		return true
	}
	return false
}
func rewriteValueARM64_OpARM64BICshiftLL_0(v *Value) bool {
	// match: (BICshiftLL x (MOVDconst [c]) [d])
	// result: (ANDconst x [^int64(uint64(c)<<uint64(d))])
	for {
		d := v.AuxInt
		_ = v.Args[1]
		x := v.Args[0]
		v_1 := v.Args[1]
		if v_1.Op != OpARM64MOVDconst {
			break
		}
		c := v_1.AuxInt
		v.reset(OpARM64ANDconst)
		v.AuxInt = ^int64(uint64(c) << uint64(d))
		v.AddArg(x)
		return true
	}
	// match: (BICshiftLL x (SLLconst x [c]) [d])
	// cond: c==d
	// result: (MOVDconst [0])
	for {
		d := v.AuxInt
		_ = v.Args[1]
		x := v.Args[0]
		v_1 := v.Args[1]
		if v_1.Op != OpARM64SLLconst {
			break
		}
		c := v_1.AuxInt
		if x != v_1.Args[0] || !(c == d) {
			break
		}
		v.reset(OpARM64MOVDconst)
		v.AuxInt = 0
		return true
	}
	return false
}
func rewriteValueARM64_OpARM64BICshiftRA_0(v *Value) bool {
	// match: (BICshiftRA x (MOVDconst [c]) [d])
	// result: (ANDconst x [^(c>>uint64(d))])
	for {
		d := v.AuxInt
		_ = v.Args[1]
		x := v.Args[0]
		v_1 := v.Args[1]
		if v_1.Op != OpARM64MOVDconst {
			break
		}
		c := v_1.AuxInt
		v.reset(OpARM64ANDconst)
		v.AuxInt = ^(c >> uint64(d))
		v.AddArg(x)
		return true
	}
	// match: (BICshiftRA x (SRAconst x [c]) [d])
	// cond: c==d
	// result: (MOVDconst [0])
	for {
		d := v.AuxInt
		_ = v.Args[1]
		x := v.Args[0]
		v_1 := v.Args[1]
		if v_1.Op != OpARM64SRAconst {
			break
		}
		c := v_1.AuxInt


o
			dmin = hypot( imgx-1, imgy-1 )
		j = -1
		for i = 1, num_cells do
		d = hypot( nx[i]-x, ny[i]-y )
		if d < dmin then
	 	    dmin = d
			j = i
		end
		end
		love.graphics.setColor( { nr[j], ng[j], nb[j] } )
		love.graphics.points( x, y )
	end
	end
	--reset color
	love.graphics.setColor( { 1, 1, 1 } )
	--draw points
	for b = 1, num_cells do
	love.graphics.points( nx[b], ny[b] )
	end
	love.graphics.setCanvas( )
	return canvas
end

--RENDER
function love.draw( )
	--reset color
	love.graphics.setColor( { 1, 1, 1 } )
	--draw diagram
	love.graphics.draw( voronoiDiagram )
	--draw drop shadow text
	love.graphics.setColor( { 0, 0, 0 } )
	love.graphics.print( "space: regenerate\nesc: quit", 1, 1 )
	--draw text
	love.graphics.setColor( { 0.7, 0.7, 0 } )
	love.graphics.print( "space: regenerate\nesc: quit" )
end

--CONTROL
function love.keyreleased( key )
	if key == 'space' then
	voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
	elseif key == 'escape' then
	love.event.quit( )
	end
end


n' +
      '\n' +
      'Gradient Ascent. 약한 공격에서 강한 공격에 대한 LLM의 취약성을 고려할 때, 보다 효과적인 모델 정렬 접근법을 설계하도록 동기를 부여한다. 우리의 전략은 섹션 3.1의 분석에서 영감을 얻은 간단한 구배 상승 방어를 포함하며, Llama2-7B와 Llama2-13B 모두에서 200개의 유해한 명령 응답 쌍을 사용하여 100단계의 구배 상승을 수행한다. 그런 다음 AdvBench 및 MaliciousInstruct 데이터 세트에서 얻은 모델의 공격 성공률(ASR)을 테스트한다. 우리는 ASR 감소(%)를 새로운 ASR에서 원래의 ASR을 뺀 값으로 계산한다. 그림 4에서 볼 수 있듯이 향상된 모델에 대한 네 가지 공격 모두에 대해 상당한 ASR 하락을 관찰한다. 상기 획득된 모델은\n' +
      '\n' +
      '\\begin{table}\n' +
      '\\begin{tabular}{l l|c c c|c c c} \\hline \\hline \\multirow{2}{*}{**Family**} & \\multirow{2}{*}{**Model**} & \\multicolumn{3}{c|}{**AdvBench**} & \\multicolumn{3}{c}{**MaliciousInstruct**} \\\\  & & ASR \\(\\uparrow\\) & Harm Score \\(\\uparrow\\) & GPT-4 Score \\(\\uparrow\\) & ASR \\(\\uparrow\\) & Harm Score \\(\\uparrow\\) & GPT-4 Score \\(\\uparrow\\) \\\\ \\hline \\multirow{8}{*}{Llama2} & Unsafe-7B & 96.5 & 3.36 & 3.47 & 99.0 & 3.14 & 3.66 \\\\  & Safe-13B & 1.3 & 1.12 & 1.05 & 1.0 & 1.00 & 1.02 \\\\  & Attack-13B & 99.4 & 3.85 & 3.84 & 99.0 & 4.29 & 4.09 \\\\ \\cline{1-1} \\cline{2-8}  & Safe-70B & 0.2 & 0.77 & 1.00 & 0.0 & 0.77 & 1.00 \\\\  & Attack-70B & 99.2 & 3.90 & 4.07 & 100.0 & 4.30 & 4.22 \\\\ \\cline{1-1} \\cline{2-8}  & Vicuna-Safe-13B & 85.0 & 2.81 & 3.12 & 89.0 & 3.48 & 3.37 \\\\  & Vicuna-Att-13B & 100.0 & 4.31 & 4.23 & 100.0 & 4.43 & 4.48 \\\\ \\hline \\multirow{2}{*}{InternlM} & Unsafe-7B & 99.2 & 4.89 & 3.87 & 99.0 & 4.93 & 4.31 \\\\  & Safe-20B & 92.1


它控件相互关联和调用，若一个界面控件对象发生变化，需要跟踪与之关联的其它所有控件并进行处理，控件之间呈现一种较为复杂的 **网状结构**，控件之间耦合度太高，系统扩展性较差。

在本案例中，可以引入一个专门用于控制界面交互的中间类`Mediator`来降低界面控件之间的耦合。引入中间类之后，界面控件之间不再直接发生引用，而是将请求先转发给中间类，再由中间类来完成对其它控件的调用，需要依据 **迪米特法则** 进行重构。

重构后的结构如下图所示：

图21  重构后的结构图

通过引入一个合理的第三者`Mediator`来降低现有对象之间的耦合度。

> 定义：迪米特法则（Law of Demeter，LoD）又称为最小知识原则（Least Knowledge Principle，LKP）
> 一个软件实体应当尽可能少地与其它实体发生相互作用。

**迪米特法则** 来自于 1987年 美国东北大学（*Northeastern University*）一个名为 “*Demeter*” 的研究项目。该法则限制了软件实体之间通信的宽度和深度，可降低系统的耦合度，使类与类之间保持松散的耦合关系。如果一个系统符合 **迪米特法则**，那么当其中一个模块发生修改时，可以尽量少地影响其它模块，扩展相对容易。

**迪米特法则** 还有几种定义形式，包括：不要和“陌生人”说话，只与你的直接朋友通信等，在 **迪米特法则** 中，对于一个对象，其朋友包括以下几类：
- 当前对象本身（this）；
- 以参数形式传入到当前对象方法中的对象；
- 当前对象的成员对象；
- 如果当前对象的成员对象是一个集合，那么集合中的元素也都是朋友；
- 当前对象所创建的对象；

任何一个对象，如果满足上面的条件之一，就是当前对象的“朋友”，否则就是“陌生人”（如：局部变量）。

在应用 **迪米特法则** 时，一个对象只能与直接朋友发生交互，不要与“陌生人”发生直接交互，这样做可以降低系统的耦合度，一个对象的改变不会给太多其它对象带来


rase or private key (now we support only seed phrase).

Variant constructors:

```ts
function cryptoBoxSecretRandomSeedPhrase(dictionary: MnemonicDictionary, wordcount: number): CryptoBoxSecret;
function cryptoBoxSecretPredefinedSeedPhrase(phrase: string, dictionary: MnemonicDictionary, wordcount: number): CryptoBoxSecret;
function cryptoBoxSecretEncryptedSecret(encrypted_secret: string): CryptoBoxSecret;
```

## CryptoBoxHandle
```ts
type CryptoBoxHandle = number
```

## BoxEncryptionAlgorithmChaCha20Variant
```ts
type BoxEncryptionAlgorithmChaCha20Variant = {
    value: ChaCha20ParamsCB
}
```
- `value`: _[ChaCha20ParamsCB](mod\_crypto.md#chacha20paramscb)_

## BoxEncryptionAlgorithmNaclBoxVariant
```ts
type BoxEncryptionAlgorithmNaclBoxVariant = {
    value: NaclBoxParamsCB
}
```
- `value`: _[NaclBoxParamsCB](mod\_crypto.md#naclboxparamscb)_

## BoxEncryptionAlgorithmNaclSecretBoxVariant
```ts
type BoxEncryptionAlgorithmNaclSecretBoxVariant = {
    value: NaclSecretBoxParamsCB
}
```
- `value`: _[NaclSecretBoxParamsCB](mod\_crypto.md#naclsecretboxparamscb)_

## BoxEncryptionAlgorithm
```ts
type BoxEncryptionAlgorithm = ({
    type: 'ChaCha20'
} & BoxEncryptionAlgorithmChaCha20Variant) | ({
    type: 'NaclBox'
} & BoxEncryptionAlgorithmNaclBoxVariant) | ({
    type: 'NaclSecretBox'
} & BoxEncryptionAlgorithmNaclSecretBoxVariant)
```
Depends on value of the  `type` field.

When _type_ is _'ChaCha20'_

- `value`: _[ChaCha20ParamsCB](mod\_crypto.md#chacha20paramscb)_

When _type_ is _'NaclBox'_

- `value`: _[NaclBoxParamsCB](mod\_crypto.md#naclboxparamscb)_

When _type_ is _'NaclSecretBox'_

- `value`: _[NaclSecretBoxParamsCB](mod\_crypto.md#naclsecretboxparamscb)_

Variant constructors:

```ts
function boxEncryptionAlgorithmChaCha20(value: ChaCha20ParamsCB): BoxEncryptionAlgorithm;
function boxEncryptionAlgorithmNaclBox(value: NaclBoxParamsCB): BoxEncryptionAlgorithm;
function boxEncryptionAlgorithmNaclSecretBox(value: NaclSecretBoxParamsCB): BoxEncryptionAlgorithm;
```

## ChaCha20ParamsCB
```ts
type ChaCha20ParamsCB = {
    nonce: string
}
```
- `nonce`: _string_ – 96-bit nonce.

Must be encoded with `hex`.

## NaclBoxParamsCB
```ts
type NaclBoxParamsCB = {
    their_public: string,
    nonce: string
}
```
- `their_public`: _string_ – 256-bit key.

Must be encoded with `hex`.
- `nonce`: _string_ – 96-bit nonce.

Must be encoded with `hex`.

## NaclSecretBoxParamsCB
```ts
type NaclSecretBoxParamsCB = {
    nonce: string
}
```
- `nonce`: _string_ – Nonce in `hex`

## MnemonicDictionary
```ts
enum MnemonicDictionary {
    Ton = 0,
    English = 1,
    ChineseSimplified = 2,
    ChineseTraditional = 3,
    French = 4,
    Italian = 5,
    Japanese = 6,
    Korean = 7,
    Spanish = 8
}
```
One of the following value:

- `Ton = 0` – TON compatible dictionary
- `English = 1` – English BIP-39 dictionary
- `ChineseSimplified = 2` – Chinese simplified BIP-39 dictionary
- `ChineseTraditional = 3` – Chinese traditional BIP-39 dictionary
- `French = 4` – French BIP-39 dictionary
- `Italian = 5` – Italian BIP-39 dictionary
- `Japanese = 6` – Japanese BIP-39 dictionary
- `Korean = 7` – Korean BIP-39 dictionary
- `Spanish = 8` – Spanish BIP-39 dictionary

## ParamsOfFactorize
```ts
type ParamsOfFactorize = {
    composite: string
}
```
- `composite`: _string_ – Hex


#pragma once

#include "EditorSupport/EditorSupport.h"

#if HELIUM_TOOLS

#include <nvtt/nvtt.h>

namespace Helium
{
    /// NVIDIA Texture Tools OutputHandler implementation for outputting texture data to a memory buffer.
    class MemoryTextureOutputHandler : public nvtt::OutputHandler
    {
    public:
        /// Buffer type for mip level data.
        typedef DynamicArray< uint8_t > MipDataArray;
        /// Buffer type for an entire set of mip levels.
        typedef DynamicArray< MipDataArray > MipLevelArray;

        /// @name Construction/Destruction
        //@{
        MemoryTextureOutputHandler( uint32_t width, uint32_t height, bool bCubemap, bool bMipmaps );
        virtual ~MemoryTextureOutputHandler();
        //@}

        /// @name Output Handler Interface
        //@{
        virtual void beginImage( int size, int width, int height, int depth, int face, int miplevel );
		virtual void endImage();
        virtual bool writeData( const void* pData, int size );
        //@}

        /// @name Data Access
        //@{
        inline const MipLevelArray& GetFace( size_t faceIndex ) const;
        //@}

    private:
        /// Texture data for each face.
        MipLevelArray m_faces[ 6 ];
        /// Mip data buffer to which data is currently being written.
        MipDataArray* m_pCurrentMipLevel;
    };
}

#include "EditorSupport/MemoryTextureOutputHandler.inl"

#endif  // HELIUM_TOOLS


iption = "Name of the object. Stable. Should be meaningful. New versions can be added with the same name.",
        example = "holmes",
        required = true,
    )
    val name: String

    /**
     * Our version of this, from 1
     */
    @get:Schema(
        description = "The present version of this object, from 1",
        example = "6",
        required = true,
    )
    val version: Int

    /**
     * Just the versioned information from this object.
     * Allows a Versioned object to be serialized without excessive size from its fields
     */
    fun versionInfo(): Versioned = SimpleVersioned(this)

}

/**
 * Used in versionInfo() method and as Spring Data Neo4j projection.
 */
data class SimpleVersioned(
    override val name: String,
    override val version: Int,
    override val id: String? = null,
) : Versioned {

    constructor(versioned: Versioned) : this(versioned.name, versioned.version, versioned.id)

    override fun toString(): String =
        "$name v$version" + (id?.let { " ($it)" } ?: "")
}

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Requested version not found")
class NoSuchVersionException(versionSelection: VersionSelection, note: String) :
    Exception("$note: No version ${versionSelection.version ?: "*"} of ${versionSelection.name} found")
/*
 * Copyright 2024-2025 Embabel Software, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.embabel.agent.a2a.server.support

import com.fasterxml.jackson.databind.ObjectMapper
import io.a2a.spec.Message
import io.a2a.spec.SendStreamingMessageResponse
import io.a2a.spec.StreamingEventKind
import io.a2a.spec.Task
import io.a2a.spec.TaskArtifactUpdateEvent
import io.a2a.spec.TaskStatusUpdateEvent
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Profile
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

/**
 * Handles streaming functionality for A2A messages
 */
@Service
@Profile("a2a")
class A2AStreamingHandler(
    private val objectMapper: ObjectMapper
) {
    private val logger = LoggerFactory.getLogger(A2AStreamingHandler::class.java)
    private val activeStreams = ConcurrentHashMap<String, SseEmitter>()
    private val scheduler: ScheduledExecutorService = Executors.newScheduledThreadPool(1)

    /**
     * Creates a new SSE stream for the given stream ID
     */
    fun createStream(streamId: String): SseEmitter {
        logger.info("Creating SSE stream for streamId: {}", streamId)

        val emitter = SseEmitter(Long.MAX_VALUE)
        activeStreams[streamId] = emitter

        emitter.onCompletion {
            logger.info("Stream completed for streamId: {}", streamId)
            activeStreams.remove(streamId)
        }

        emitter.onTimeout {
            logger.info("Stream timed out for streamId: {}", streamId)
            activeStreams.remove(streamId)
        }

        // Send initial connection established event
        try {
            emitter.send(SseEmitter.event()


"""arXiv tool spec."""

from typing import Optional

from llama_index.readers.schema.base import Document
from llama_index.tools.tool_spec.base import BaseToolSpec

class ArxivToolSpec(BaseToolSpec):
    """arXiv tool spec."""

    spec_functions = ["arxiv_query"]

    def __init__(self, max_results: Optional[int] = 3):
        self.max_results = max_results

    def arxiv_query(self, query: str, sort_by: Optional[str] = "relevance"):
        """
        A tool to query arxiv.org
        ArXiv contains a variety of papers that are useful for answering
        mathematic and scientfic questions

        Args:
            query (str): The query to be passed to arXiv.
            sort_by (str): Either 'relevance' (default) or 'recent'

        """
        import arxiv

        sort = arxiv.SortCriterion.Relevance
        if sort_by == "recent":
            sort = arxiv.SortCriterion.SubmittedDate
        search = arxiv.Search(query, max_results=self.max_results, sort_by=sort)
        results = []
        for result in search.results():
            results.append(
                Document(text=f"{result.pdf_url}: {result.title}\n{result.summary}")
            )
        return results


>): (ys: ReadonlyArray) => ReadonlyArray
  (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray
}
export function union(
  E: Eq
): (xs: ReadonlyArray, ys?: ReadonlyArray) => ReadonlyArray | ((ys: ReadonlyArray) => ReadonlyArray) {
  const elemE = elem(E)
  return (xs, ys?) => {
    if (ys === undefined) {
      const unionE = union(E)
      return (ys) => unionE(ys, xs)
    }
    return concat(
      xs,
      ys.filter((a) => !elemE(a, xs))
    )
  }
}

// TODO: remove non-curried overloading in v3
/**
 * Creates an array of unique values that are included in all given arrays using a `Eq` for equality
 * comparisons. The order and references of result values are determined by the first array.
 *
 * @example
 * import { intersection } from 'fp-ts/ReadonlyArray'
 * import { eqNumber } from 'fp-ts/Eq'
 * import { pipe } from 'fp-ts/function'
 *
 * assert.deepStrictEqual(pipe([1, 2], intersection(eqNumber)([2, 3])), [2])
 *
 * @category combinators
 * @since 2.5.0
 */
export function intersection(
  E: Eq
): {
  (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray
  (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray
}
export function intersection(
  E: Eq
): (xs: ReadonlyArray, ys?: ReadonlyArray) => ReadonlyArray | ((ys: ReadonlyArray) => ReadonlyArray) {
  const elemE = elem(E)
  return (xs, ys?) => {
    if (ys === undefined) {
      const intersectionE = intersection(E)
      return (ys) => intersectionE(ys, xs)
    }
    return xs.filter((a) => elemE(a, ys))
  }
}

// TODO: remove non-curried overloading in v3
/**
 * Creates an array of array values not included in the other given array using a `Eq` for equality
 * comparisons. The order and references of result values are determined by the first array.
 *
 * @example
 * import { difference } from 'fp-ts/ReadonlyArray'
 * import { eqNumber } from 'fp-ts/Eq'
 * import { pipe } from 'fp-ts/function'
 *
 * assert.deepStrictEqual(pipe([1, 2], difference(eqNumber)([2, 3])), [1])
 *
 * @category combinators
 * @since 2.5.0
 */
export function difference(
  E: Eq
): {
  (xs: ReadonlyArray): (ys: ReadonlyArray) => ReadonlyArray
  (xs: ReadonlyArray, ys: ReadonlyArray): ReadonlyArray
}
export function difference(
  E: Eq
): (xs: ReadonlyArray, ys?: ReadonlyArray) => ReadonlyArray | ((ys: ReadonlyArray) => ReadonlyArray) {
  const elemE = elem(E)
  return (xs, ys?) => {
    if (ys === undefined) {
      const differenceE = difference(E)
      return (ys) => differenceE(ys, xs)
    }
    return xs.filter((a) => !elemE(a, ys))
  }
}

/**
 * Wrap a value into the type constructor.
 *
 * @category Applicative
 * @since 2.5.0
 */
export const of: Applicative1<URI>['of'] = (a


{0x0}}}, {{._mp_alloc = 0, ._mp_size = 1, ._mp_d = (mp_limb_t[]) {0x2ee}}}, {{._mp_alloc = 0, ._mp_size = 1, ._mp_d = (mp_limb_t[]) {0x133}}}}};
const quat_alg_elem_t COMMITMENT_IDEAL_DISTORTION_ENDO = {{{._mp_alloc = 0, ._mp_size = 1, ._mp_d = (mp_limb_t[]) {0x1}}}, {{{._mp_alloc = 0, ._mp_size = 1, ._mp_d = (mp_limb_t[]) {0xb3}}}, {{._mp_alloc = 0, ._mp_size = 1, ._mp_d = (mp_limb_t[]) {0x293}}}, {{._mp_alloc = 0, ._mp_size = 0, ._mp_d = (mp_limb_t[]) {0x0}}}, {{._mp_alloc = 0, ._mp_size = 1, ._mp_d = (mp_limb_t[]) {0x73}}}}};
#endif


"Bougie": [
        "NNP"
    ],
    "Alice": [
        "NNP",
        "NN"
    ],
    "hate-mongering": [
        "NN"
    ],
    "schematically": [
        "RB"
    ],
    "WATKINS-JOHNSON": [
        "NNP"
    ],
    "high-pressure": [
        "JJ"
    ],
    "realm": [
        "NN"
    ],
    "reusable": [
        "JJ"
    ],
    "Scotts": [
        "NNP"
    ],
    "Scotty": [
        "NNP",
        "NN"
    ],
    "competence": [
        "NN"
    ],
    "McKee": [
        "NNP"
    ],
    "consumer-warning": [
        "NN"
    ],
    "slouches": [
        "VBZ"
    ],
    "Scotto": [
        "NNP"
    ],
    "soar": [
        "VB",
        "VBP"
    ],
    "Flumenbaum": [
        "NNP"
    ],
    "Heretofore": [
        "RB"
    ],
    "Brandenburg": [
        "NNP"
    ],
    "Tiny": [
        "NNP",
        "JJ"
    ],
    "Ting": [
        "NNP"
    ],
    "rile": [
        "VBP",
        "VB"
    ],
    "fulminating": [
        "VBG"
    ],
    "Tina": [
        "NNP"
    ],
    "pl.": [
        "NNP"
    ],
    "Cartwright": [
        "NNP"
    ],
    "unrivaled": [
        "JJ"
    ],
    "cede": [
        "VB"
    ],
    "humor": [
        "NN",
        "VB"
    ],
    "sinking-fund": [
        "JJ",
        "NN"
    ],
    "reflexively": [
        "RB"
    ],
    "unavoidable": [
        "JJ"
    ],
    "Guilford": [
        "NNP",
        "NN"
    ],
    "leered": [
        "VBD"
    ],
    "Gifts": [
        "NNS"
    ],
    "Restructuring": [
        "NN"
    ],
    "disillusioned": [
        "VBN",
        "JJ"
    ],
    "honoured": [
        "VBN"
    ],
    "enticingly": [
        "RB"
    ],
    "unavoidably": [
        "RB"
    ],
    "singed": [
        "VBD"
    ],
    "School": [
        "NNP",
        "NN"
    ],
    "Obstacles": [
        "NNS"
    ],
    "Tandler": [
        "NNP"
    ],
    "marketing": [
        "NN",
        "VBG",
        "JJ",
        "VBG|NN"
    ],
    "conformation": [
        "NN"
    ],
    "ply": [
        "VBP",
        "VB"
    ],
    "Geodetic": [
        "NNP"
    ],
    "Seeds": [
        "NNS"
    ],
    "Evegeni": [
        "NNP"
    ],
    "Holders": [
        "NNS",
        "NNP"
    ],
    "descendent": [
        "NN"
    ],
    "properties": [
        "NNS"
    ],
    "Ostrovsky": [
        "NNP"
    ],
    "trophy": [
        "NN"
    ],
    "aerosols": [
        "NNS"
    ],
    "W.S.":


return;
            }

            _value = buffer.ReadInt();
            _max = buffer.ReadInt();
            if (buffer.version >= 2)
                _min = buffer.ReadInt();

            if (buffer.version >= 5)
            {
                string sound = buffer.ReadS();
                if (!string.IsNullOrEmpty(sound))
                {
                    float volumeScale = buffer.ReadFloat();
                    displayObject.onClick.Add(() =>
                    {
                        NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip;
                        if (audioClip != null && audioClip.nativeClip