"""
网易云一键LV10

[python 3.7.9]

* main2.0 测试较少，但功能相对增多，可自定义性提升，优化部分代码，若出现致命BUG请使用main.py *

=====================================
如何工作?->
[1]从喜欢列表随机挑选部分歌曲
[2]从歌曲中获取心动模式列表 / 推荐列表
[3]多线程将列表带入模拟播放器中
[4]刷完歌曲后待机一天
[5]新的一天开始，准时签到
=========================================

@im-cwuom - bilibili
       请关注我

注: 按下回车终止所有线程
"""

# ==============================================配置==============================================

"""
此项为你的网易云UID 如果值为auto则会自动获取UID
若程序无法自动获取您的UID，请删除"auto"并手动填写此项

* 如何获取?
> http://localhost:3000/qrlogin.html 中找到"id": xxxxx(xxx为纯数字)后复制 替换下面的UID
        http://localhost:3000/因需求改变，取决与你的服务器搭建在何处，若在此电脑上搭建请直接访问它
"""
UID = "auto"

# 选取次数 [因为推荐的内容很多是已知的，当无法刷到300首时可以适当增加p值]
p = 25

# 你的API接口 [最后不要加斜杠] eg http://127.0.0.1:3000
api = "http://localhost:3000"
# 你的歌单ID(喜欢列表)
sourceid = "1849703902"

"""
是否听完全曲
True -> 听完全曲(会多一份请求，可能对效率有影响)
False -> 听完部分(本地计算随机数, 60s以上算入听歌量)
"""
ListenAll = False

# 看你的歌单中的音乐有多少 设定数量不要少于[p + randomMax] 否则可能会报错(下标越界)
randomMax = 50
# 随机的最小数值 不要超过上面的变量就可以
randomMin = 0

"""
1 -> 当模式0无法使用时(无法稳定增加听歌量),使用播放1 可能对推荐算法有一定影响（刷官方推荐的歌单）
0 -> 根据心动模式来进行刷听歌量 对推荐算法影响微乎其微

*当启用MaxContinueNum时，也许会自动改变此数值来达到期望听歌量*
"""
PlayMode = 1  # 播放模式

"""
最大尝试次数
当每日播放未达到期望值时，重启程序并尝试达到期望听歌量

0 -> 关闭
1 -> 尝试1次后休眠
n -> 尝试n次后休眠
.....

-1 -> 一直尝试，直到达到期望值（慎用）
"""
MaxContinueNum = 2

"""
刷到300首后停止
会多一份请求，默认开启
"""
Enable300 = True

# 没有部分多线程的日志(还是有日志) 可以认真查看已经刷了多少听歌量了
NoThreadLogs = True

# 期望值，若达不到期望值则会推倒重来
ExpectationNum = 250

"""
给网易云喘息的机会，不然容易风控，如果你觉得影响效率可适当降低此数值
(主要原因是多线程吃带宽太快了，会影响听歌量的获取，若你没有开启Enable300则可以忽视)
"""
if Enable300:
    # 你应该调整这里
    SleepTime = 1.3
else:
    SleepTime = 0.1

# 忽略UID解析错误提示，将在提示过后自动变为True
IgnoreUidError = False

# ==============================================================================================

import sys
from threading import Thread
import time
import json
import random

import ctypes
import inspect
import requests
import keyboard

"""
使用前请先安装上面的库
=====================================
管理员运行CMD
> pip3 install 缺失的库名(import后面) -i https://pypi.tuna.tsinghua.edu.cn/simple
"""

# 记数器，不用管
x = 0
# 不用管，判断是否300首
Already300 = False
# 终止播放判断，不用管
StopPlay = False
PlayingMusicId = -1

# UID
uid = 0

# 记录听歌量
s = 0

# 储存所有线程
ThreadList = []

# 已经进入休眠
OnSleep = False

ListenerThread = []

while True:
    try:
        cookies = {}
        f = open("cookie.txt", "r")

        for line in f.read().split(';'):
            name, value = line.strip().split('=', 1)
            cookies[name] = value  # 为字典cookies添加内容

        break
    except:
        cookie = input(
            "未检测到cookie.txt中含有指定cookie，或是文件不存在? \n请输入有效的网易云cookie!\n=========================\n[cookie]")
        print("\n=========================")
        with open("cookie.txt", "w") as w:
            w.write(cookie)

headers = {'content-type': "application/json",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                         "Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.70"}

"""刷播放函数 心动模式"""

def startPlay(data):
    global ThreadList
    global SleepTime
    try:
        tlist = []
        # print(data)
        for id in data:
            if not Already300:
                id = id["id"]
                t1 = Thread(target=Play, args=(id,))
                t1.start()
                time.sleep(SleepTime)
                tlist.append(t1)
                ThreadList.append(t1)

        for t in tlist:
            t.join()
    except:
        print("\n[ERR] 播放模式出现问题，可能会影响使用，您可能被网易云风控了")

"""刷播放函数 若上一个用不了，请尝试这个(对推荐算法可能会产生影响)"""

def startPlay2():
    global SleepTime
    global Already300
    global ThreadList
    global NoThreadLogs
    try:
        sidList = []

        if not Already300:
            source_ids = json.loads(requests.get(api + "/recommend/resource", cookies=cookies, headers=headers).text)
            for ids in source_ids["recommend"]:
                id = ids["id"]
                sidList.append(id)
                log_print("推荐歌单->", id, "已加入播放列表!")

            musicIdsList = []
            for ids in sidList:
                # /playlist/track/all?id=24381616
                try:
                    musicList = json.loads(
                        requests.get(api + "/playlist/track/all?id=" + str(ids), cookies=cookies, headers=headers).text)
                    for id in musicList["privileges"]:
                        log_print("获取到音乐:", id["id"])
                        musicIdsList.append(id["id"])
                except:


      if (partner.remarks?.contains(str) == true) {
        return
      }
      if (partner.remarks.isNullOrBlank()) {
        partner.remarks = str
      } else {
        partner.remarks = "$str\n${partner.remarks}"
      }
    }

    internal fun checkBillAddress(partner: TradingPartner, invoice: RechnungDO?) {
      invoice ?: return
      val customerAddress = invoice.customerAddress
      if (customerAddress.isNullOrBlank() || checkIfGiven(partner.billToCity, partner.billToZip)) {
        // Nothing to do.
        return
      }
      var lines = customerAddress.lines().filter { it.isNotBlank() } // lines of address without blank lines.
      if (lines.size < 2) {
        // Can't parse address.
        return
      }
      if (lineEquals(lines[0], "herr", "frau", "firma", "an", "portal", "klinikdienst")) {
        lines = lines.drop(1)
      }
      // Assuming first line is Customer's name
      var pos = lines.size - 1 // Start with last line
      // Last line is country or zip code with city:
      var zipCodeAndCity = extractZipCodeCity(lines[pos])
      var country: String? = null
      if (zipCodeAndCity == null) {
        country = lines[pos].trim()
        pos -= 1
        zipCodeAndCity = extractZipCodeCity(lines[pos]) ?: return // No zip code and city found.
      }
      pos -= 1
      if (pos < 0) {
        return // No street found.
      }
      val street = lines[pos].trim()
      pos -= 1
      val additionalAddressLines = mutableListOf<String>()
      while (pos > 0) {
        // An additional line is found before street.
        additionalAddressLines.add(0, lines[pos].trim())
        pos -= 1
      }
      if (additionalAddressLines.isNotEmpty()) {
        partner.billToAddressAdditional = additionalAddressLines.joinToString(" ")
      }
      partner.billToZip = zipCodeAndCity.first
      partner.billToCity = zipCodeAndCity.second
      partner.billToStreet = street
      partner.billToCountry = country
    }

    private fun lineEquals(line: String, vararg strs: String): Boolean {
      val trim = line.trim()
      strs.forEach {
        if (trim.equals(it, ignoreCase = true)) {
          return true
        }
      }
      return false
    }

    internal fun extractZipCodeCity(line: String): Pair<String, String>? {
      var str = line.trim()
      if (str.startsWith("D-") || str.startsWith("D ")) {
        str = str.substring(2)
      }
      val zipCodeMatch = "^[0-9 ]{5,10}".toRegex()
      val match = zipCodeMatch.find(str) ?: return null
      val zipCode = match.value.trim()
      val city = str.removePrefix(zipCode).trim()
      if (city.isBlank()) {
        return null
      }
      return Pair(zipCode, city)
    }

    private fun checkIfGiven(vararg str: String?): Boolean {
      return str.any { !it.isNullOrBlank() }
    }

    private fun createVendor(number: String, kreditor: String, konto: KontoDO): TradingPartner {
      val vendor = TradingPartner()
      vendor.number = number
      vendor.company = kreditor
      vendor.datevKonto = konto.nummer
      prependRemarks(vendor, konto)
      vendor.organization = TradingPartner.Organization(organizationId)
      vendor.type = TradingPartner.Type(TradingPartner.TypeValue.VENDOR)
      vendor.contactType = TradingPartner.ContactType(TradingPartner.ContactTypeValue.COMPANY)
      vendor.active = TradingPartner.Active(TradingPartner.ActiveValue.TRUE) // Nothing known about activity.
      return vendor
    }

    private fun createCustomer(
      invoice: RechnungDO?,
      number: String? = null,
      kundeName: String? = null,
      kundeShortName: String? = null,
      active: Boolean = tr


ants__["a" /* default */].RENDERER)), _defineProperty(_gl$luma$info, __WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VERSION, gl.getParameter(__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VERSION)), _defineProperty(_gl$luma$info, __WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].SHADING_LANGUAGE_VERSION, gl.getParameter(__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].SHADING_LANGUAGE_VERSION)), _gl$luma$info);
  }

  return gl.luma.info;
}

var GL_UNMASKED_VENDOR_WEBGL = 0x9245; // vendor string of the graphics driver.
var GL_UNMASKED_RENDERER_WEBGL = 0x9246; // renderer string of the graphics driver.

function getGLContextInfo2(gl) {
  var vendorMasked = gl.getParameter(__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VENDOR);
  var rendererMasked = gl.getParameter(__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].RENDERER);
  var ext = gl.getExtension('WEBGL_debug_renderer_info');
  var vendorUnmasked = ext && gl.getParameter(ext.UNMASKED_VENDOR_WEBGL || __WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VENDOR);
  var rendererUnmasked = ext && gl.getParameter(ext.UNMASKED_RENDERER_WEBGL || __WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].RENDERER);
  return {
    vendor: vendorUnmasked || vendorMasked,
    renderer: rendererUnmasked || rendererMasked,
    vendorMasked: vendorMasked,
    rendererMasked: rendererMasked,
    version: gl.getParameter(__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VERSION),
    shadingLanguageVersion: gl.getParameter(__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].SHADING_LANGUAGE_VERSION)
  };
}

function getContextInfo(gl) {
  var limits = getContextLimits(gl);
  var info = getGLContextInfo(gl);
  return {
    // basic information
    vendor: info[GL_UNMASKED_VENDOR_WEBGL] || info[__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VENDOR],
    renderer: info[GL_UNMASKED_RENDERER_WEBGL] || info[__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].RENDERER],
    version: info[__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].VERSION],
    shadingLanguageVersion: info[__WEBPACK_IMPORTED_MODULE_0__gl_constants__["a" /* default */].SHADING_LANGUAGE_VERSION],
    // info, caps and limits
    info: info,
    limits: limits,
    webgl1MinLimits: gl.luma.webgl1MinLimits,
    webgl2MinLimits: gl.luma.webgl2MinLimits
  };
}

// DEBUG INFO

/**
 * Provides strings identifying the GPU vendor and driver.
 * https://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/
 * @param {WebGLRenderingContext} gl - context
 * @return {Object} - 'vendor' and 'renderer' string fields.
 */
function glGetDebugInfo(gl) {
  return getGLContextInfo2(gl);
  // const info = gl.getExtension('WEBGL_debug_renderer_info');
  // // We can't determine if 'WEBGL_debug_renderer_info' is supported by
  // // checking whether info is null here. Firefox doesn't follow the
  // // specs by returning null for unsupported extension. Instead,
  // // it returns an object without GL_


, func(t *testing.T) {
			t.Parallel()
			d := tt.d.Clone()
			got := d.Merge(tt.args.xmlDict, tt.args.dicts...)
			assert.Equal(t, tt.want, got)
		})
	}
}

func Test_dict_Values(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		d    xmlDict
		want xmlIList
	}{
		{"Empty", nil, xmlList{}},
		{"Map", dictFixture, xmlList{1.23, 123, xmlList{1, "two"}, xmlList{1, 2, 3}, xmlDict{"sub1": 1, "sub2": "two"}, xmlDict{"1": 1, "2": "two"}, "Foo bar"}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			assert.Equal(t, tt.want, tt.d.GetValues())
		})
	}
}

func Test_dict_Pop(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name       string
		d          xmlDict
		args       []interface{}
		want       interface{}
		wantObject xmlIDict
	}{
		{"Nil", dictFixture, nil, nil, dictFixture},
		{"Pop one element", dictFixture, []interface{}{"float"}, 1.23, dictFixture.Omit("float")},
		{"Pop missing element", dictFixture, []interface{}{"undefined"}, nil, dictFixture},
		{"Pop element twice", dictFixture, []interface{}{"int", "int", "string"}, xmlList{123, 123, "Foo bar"}, dictFixture.Omit("int", "string")},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			d := tt.d.Clone()
			got := d.Pop(tt.args...)
			assert.Equal(t, tt.want, got)
			assert.Equal(t, tt.wantObject, d)
		})
	}
}

func Test_dict_Add(t *testing.T) {
	t.Parallel()

	type args struct {
		key interface{}
		v   interface{}
	}
	tests := []struct {
		name string
		d    xmlDict
		args args
		want xmlIDict
	}{
		{"Empty", nil, args{"A", 1}, xmlDict{"A": 1}},
		{"With element", xmlDict{"A": 1}, args{"A", 2}, xmlDict{"A": xmlList{1, 2}}},
		{"With element, another value", xmlDict{"A": 1}, args{"B", 2}, xmlDict{"A": 1, "B": 2}},
		{"With list element", xmlDict{"A": xmlList{1, 2}}, args{"A", 3}, xmlDict{"A": xmlList{1, 2, 3}}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			assert.Equal(t, tt.want, tt.d.Add(tt.args.key, tt.args.v))
		})
	}
}

func Test_dict_Set(t *testing.T) {
	t.Parallel()

	type args struct {
		key interface{}
		v   interface{}
	}
	tests := []struct {
		name string
		d    xmlDict
		args args
		want xmlIDict
	}{
		{"Empty", nil, args{"A", 1}, xmlDict{"A": 1}},
		{"With element", xmlDict{"A": 1}, args{"A", 2}, xmlDict{"A": 2}},
		{"With element, another value", xmlDict{"A": 1}, args{"B", 2}, xmlDict{"A": 1, "B": 2}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			assert.Equal(t, tt.want, tt.d.Set(tt.args.key, tt.args.v))
		})
	}
}


委名义发。

中共中央军委办事组一九六八年八月十六日送毛泽东等审阅的《关于加强我军组织纪律性的指示》稿指出，目前全军形势大好，但“有少数单位、少数人员，甚至个别中高级干部，仍然严重地存在着无政府主义、资产阶级派性和无组织无纪律现象”。为此，提出如下要求：一、全军必须紧跟毛主席的伟大战略部署，坚决反对“多中心即无中心论”，反对破坏集中统一、破坏组织纪律、各自为政、各行其是的行为。二、要在全军普遍进行组织纪律和法纪教育，提高全体人员对纪律的重要意义的认识，澄清各种错误思想和胡涂观念。三、对个别严重违法乱纪、屡教不改的人，必须给以必要的纪律制裁。四、各级干部特别是中高级干部，要加强领导，带头遵守纪律，维护纪律。认真贯彻严格管理与耐心说服相结合的原则。严格区分两类不同性质的矛盾。五、要把加强组织纪律性问题，作为部队革命化建设的重要内容，经常抓紧，反复落实。毛泽东审阅时，将这个指示的署名由“军委办事组”改为“中央军委”，并写了这个批语。八月二十二日，中央军委发出这个指示。

CCRADB

---
layout: default
title: "1622.吴德在首都红卫兵代表会议上的讲话"
weight: 1622
---

吴德1966-8-26

吴德在首都红卫兵代表会议上的讲话

吴德

1966.08.26

今天和大家商量一个问题，首都有红卫兵、赤卫队和其他各种组织，为了使大家能够联络，我们有个提议，全市建立一个联络总站，各区成立一个联合分站，这是周总理的提议，地点大家讨论。

我们想，这是劳动人民文化宫，在这个地方作为办公地方行不行？当前文化革命是一件大事，红卫兵的成立也是一件大事。我相信大家一定会同意这个，同意成立联络组织的。首都红卫兵的联络站是在伟大的领袖、伟大的舵手毛主席亲自指挥下成立的，红卫兵联络站也联络其他革命组织，以首都联络站为中心，具体任务要大家来讨论，大家来创造，联络站过渡到总指挥部。

用毛


�

### 误差传播的数学原理

误差从输出层向输入层传播，每一层的误差都依赖于后一层的误差：

$$\delta^{(l)} = \delta^{(l+1)} \cdot W^{(l+1)T} \cdot f'^{(l)}(z^{(l)})$$

### 梯度计算

权重梯度：

$$\frac{\partial L}{\partial W^{(l)}} = \delta^{(l)} \cdot a^{(l-1)T}$$

偏置梯度：

$$\frac{\partial L}{\partial b^{(l)}} = \sum_i \delta_i^{(l)}$$

### 完整的反向传播算法

```python
def backpropagation(self, X, y, learning_rate=0.1):
    """完整的反向传播算法"""
    m = X.shape[0]

    # 前向传播
    self.forward(X)

    # 计算输出层误差
    delta2 = self.a2 - y

    # 反向传播误差
    delta1 = np.dot(delta2, self.W2.T) * self.sigmoid_derivative(self.z1)

    # 计算梯度
    dW2 = np.dot(self.a1.T, delta2) / m
    db2 = np.sum(delta2, axis=0, keepdims=True) / m
    dW1 = np.dot(X.T, delta1) / m
    db1 = np.sum(delta1, axis=0, keepdims=True) / m

    # 更新参数
    self.W2 -= learning_rate * dW2
    self.b2 -= learning_rate * db2
    self.W1 -= learning_rate * dW1
    self.b1 -= learning_rate * db1

    return dW1, db1, dW2, db2
```

## 权重更新规则

### 基本更新规则

$$\theta_{t+1} = \theta_t - \alpha \nabla J(\theta_t)$$

其中：
- $\theta_t$ 是第t次迭代的参数
- $\alpha$ 是学习率
- $\nabla J(\theta_t)$ 是损失函数在$\theta_t$处的梯度

### 不同优化器的更新规则

#### 1. 随机梯度下降（SGD）

```python
def sgd_update(weights, gradients, learning_rate):
    """SGD更新规则"""
    for w, g in zip(weights, gradients):
        w -= learning_rate * g
```

#### 2. 带动量的SGD

```python
def momentum_sgd_update(weights, gradients, velocities, learning_rate, momentum=0.9):
    """带动量的SGD更新规则"""
    for i, (w, g, v) in enumerate(zip(weights, gradients, velocities)):
        velocities[i] = momentum * v + learning_rate * g
        w -= velocities[i]
```

## 在深度学习框架中的实现

### PyTorch中的反向传播

```python
import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self, input_size, hidden_siz


idMap.remove(id)
                continue
            }

            objectMap[k] = item
        }

        for ((id, factory) in deferredRegistrations) {
            val k = objectRegistry[id]
            if (k == null) {
                Cynosure.error("Could not get object key for deferred registration $id")
                continue
            }

            val value = factory(k)
            idMap[id] = value
            objectMap[k] = value
        }

        deferredRegistrations.clear()
    }

    internal companion object {
        private val ALL: MutableList<AttachedRegistry<*, *>> = mutableListOf()

        @CynosureInternal
        fun unwrapAll() {
            ALL.forEach(AttachedRegistry<*, *>::unwrap)
        }
    }
}@file:JvmName("NamedColors")
/**
 * Css colors
 */
package dev.mayaqq.cynosure.utils.colors

@JvmSynthetic
@JvmField
internal val colorByName: MutableMap<String, Color> = LinkedHashMap(148)

@JvmSynthetic
@JvmField
internal val nameByColor: MutableMap<Color, String> = HashMap(148)

private fun namedColor(name: String, color: UInt): Color = Color(color or 0xff000000u).also {
    colorByName[name] = it
    if (!nameByColor.contains(it)) nameByColor[it] = name
}

private fun namedColorWithAlpha(name: String, color: UInt): Color = Color(color).also {
    colorByName[name] = it
    if (!nameByColor.contains(it)) nameByColor[it] = name
}

// CSS Colors
public val AliceBlue: Color = namedColor("aliceblue", 0xf0f8ffu)

public val AntiqueWhite: Color = namedColor("antiquewhite", 0xfaebd7u)

public val Aqua: Color = namedColor("aqua", 0x00ffffu)

public val Aquamarine: Color = namedColor("aquamarine", 0x7fffd4u)

// omg azure reference
public val Azure: Color = namedColor("azure", 0xf0ffffu)

public val Beige: Color = namedColor("beige", 0xf5f5dcu)

public val Bisque: Color = namedColor("bisque", 0xffe4c4u)

public val Black: Color = namedColor("black", 0x000000u)

public val BlanchedAlmond: Color = namedColor("blanchedalmond", 0xffebcdu)

public val Blue: Color = namedColor("blue", 0x0000ffu)

public val BlueViolet: Color = namedColor("blueviolet", 0x8a2be2u)

public val BohemianBlue: Color = namedColor("bohemianblue", 0x0000aau)

public val Brown: Color = namedColor("brown", 0xa52a2au)

public val Burlywood: Color = namedColor("burlywood", 0xdeb887u)

public val CadetBlue: Color = namedColor("cadetblue", 0x5f9ea0u)

public val Chartreuse: Color = namedColor("chartreuse", 0x7fff00u)

public val Chocolate: Color = namedColor("chocolate", 0xd2691eu)

public val Coral: Color = namedColor("coral", 0xff7f50u)

public val CornflowerBlue: Color = namedColor("cornflowerblue", 0x6495edu)

public val Cornsilk: Color = namedColor("cornsilk", 0xfff8dcu)

public val Crimson: Color = namedColor("crimson", 0xdc143cu)

public val Cyan: Color = namedColor("cyan", 0x00ffffu)

public val DarkBlue: Color = namedColor("darkblue", 0x00008bu)

public val DarkCyan: Color = namedColor("darkcyan", 0x008b8bu)

public val DarkGoldenRod: Color = namedColor("darkgoldenrod", 0xb8860bu)

public val DarkGray: Color = namedColor("darkgray", 0xa9a9a9u)

public val DarkGreen: Color = namedColor("darkgreen", 0x006400u)

public val DarkGrey: Color = namedColor("darkgrey", 0xa9a9a9u)

public val DarkKhaki: Color


# Copyright 2019 Google LLC
#
# 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.

"""Module for creating metrics in tensorflow for model training."""

import tensorflow as tf

def mean_acc(labels, predictions, num_classes):
    """Mean per class accuracy metrics
    Arguments:
        labels: tf.Tensor objects, True values of the dependent variable
        predictions: tf.Tensor objects, Predictions from the model

    Returns:
        The mean per class accuracy
    """
    return {'mean_class_acc': tf.metrics.mean_per_class_accuracy(
        labels,
        predictions['class_ids'], num_classes)
    }

def my_auc(labels, predictions):
    """Custom AUC metric using interpolation.

    Arguments:
        labels: tf.Tensor objects, True values of dependent variable
        predictions: tf.Tensor objects, Predictions from the model
    Returns:
        The AUC metric for the model
    """
    return {'auc_ci': tf.metrics.auc(
        labels,
        predictions['class_ids'],
        summation_method='careful_interpolation')
    }

def rmse(labels, predictions):
    """Root mean squared error metric for regression tasks.

    Arguments:
        labels: tf.Tensor objects, True values of dependent variable
        predictions: tf.Tensor objects, Predictions from the model

    Returns:
        Root mean squared error for regression model
    """
    return {'root_mean_square_error': tf.metrics.root_mean_squared_error(
        labels,
        predictions['predictions'])
    }

def mar(labels, predictions):
    """Mean absolute error for regression model.

    Arguments:
        labels: tf.Tensor objects, True values of dependent variable
        predictions: tf.Tensor objects, Predictions from the model

    Returns:
        Mean absolute error for the regression model
    """
    return {'mean_absolute_error': tf.metrics.mean_absolute_error(
        labels,
        predictions['predictions'])
    }


thMeta(lang.NewMap(kw_rettag, nil)).(lang.FnFunc)
		var_clojure_DOT_core_pr = ns.InternWithValue(tmp0, tmp1, true)
		if tmp0.Meta() != nil {
			var_clojure_DOT_core_pr.SetMeta(tmp0.Meta().(lang.IPersistentMap))
		}
		var_clojure_DOT_core_pr.SetDynamic()
	}
	// pr-str
	{
		tmp1 := reflect.TypeOf("")
		tmp0 := sym_pr_DASH_str.WithMeta(lang.NewMap(kw_tag, tmp1, kw_arglists, lang.NewList(lang.NewVector(sym__AMP_, sym_xs)), kw_doc, "pr to a string, returning it", kw_static, true, kw_file, "clojure/core.glj", kw_added, "1.0", kw_ns, lang.FindOrCreateNamespace(sym_clojure_DOT_core), kw_end_DASH_column, int(12), kw_column, int(7), kw_line, int(4757), kw_end_DASH_line, int(4757))).(*lang.Symbol)
		var tmp2 lang.FnFunc
		tmp2 = lang.NewFnFunc(func(args ...any) any {
			switch len(args) {
			default:
				checkArityGTE(args, 0)
				restArgs := args[0:]
				var v3 any
				if len(restArgs) > 0 {
					v3 = lang.NewList(restArgs...)
				}
				_ = v3
				var tmp4 any
				{ // let
					// let binding "s__0__auto__"
					tmp5 := new(strings8.Builder)
					var v6 any = tmp5
					_ = v6
					var tmp7 any
					{ // let
						tmp8 := checkDerefVar(var_clojure_DOT_core_push_DASH_thread_DASH_bindings)
						tmp9 := checkDerefVar(var_clojure_DOT_core_hash_DASH_map)
						tmp10 := lang.InternVarName(sym_clojure_DOT_core, sym__STAR_out_STAR_)
						tmp11 := lang.Apply(tmp9, []any{tmp10, v6})
						tmp12 := lang.Apply(tmp8, []any{tmp11})
						_ = tmp12
						var tmp13 any
						func() {
							defer func() {
								tmp14 := checkDerefVar(var_clojure_DOT_core_pop_DASH_thread_DASH_bindings)
								tmp15 := lang.Apply(tmp14, nil)
								_ = tmp15
							}()
							tmp16 := checkDerefVar(var_clojure_DOT_core_apply)
							tmp17 := checkDerefVar(var_clojure_DOT_core_pr)
							tmp18 := lang.Apply(tmp16, []any{tmp17, v3})
							_ = tmp18
							tmp19 := checkDerefVar(var_clojure_DOT_core_str)
							tmp20 := lang.Apply(tmp19, []any{v6})
							tmp13 = tmp20
						}()
						tmp7 = tmp13
					} // end let
					tmp4 = tmp7
				} // end let
				return tmp4
			}
		})
		tmp3 := reflect.TypeOf("")
		tmp2 = tmp2.WithMeta(lang.NewMap(kw_rettag, tmp3)).(lang.FnFunc)
		var_clojure_DOT_core_pr_DASH_str = ns.InternWithValue(tmp0, tmp2, true)
		if tmp0.Meta() != nil {
			var_clojure_DOT_core_pr_DASH_str.SetMeta(tmp0.Meta().(lang.IPersistentMap))
		}
	}
	// print
	{
		tmp0 := sym_print.WithMeta(lang.NewMap(kw_arglists, lang.NewList(lang.NewVector(sym__AMP_, sym_more)), kw_doc


e %3c/svg%3e"},37453:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' viewBox='0 0 18 18'%3e %3cpath fill='%23616161' d='M5.2 5.9 9 9.7l3.8-3.8L14 7.1l-4.9 5-4.9-5z' class='jp-icon3' shape-rendering='geometricPrecision'/%3e %3c/svg%3e"},32225:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' viewBox='0 0 18 18'%3e %3cpath fill='%23616161' d='M5.2 7.5 9 11.2l3.8-3.8H5.2z' class='jp-icon3' shape-rendering='geometricPrecision'/%3e %3c/svg%3e"},50394:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' viewBox='0 0 18 18'%3e %3cpath fill='%23616161' d='M10.8 12.8 7.1 9l3.8-3.8v7.6z' class='jp-icon3' shape-rendering='geometricPrecision'/%3e %3c/svg%3e"},59025:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' viewBox='0 0 18 18'%3e %3cpath fill='%23616161' d='M7.2 5.2 10.9 9l-3.8 3.8V5.2z' class='jp-icon3' shape-rendering='geometricPrecision'/%3e %3c/svg%3e"},84666:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' viewBox='0 0 20 20'%3e %3cpath fill='%23616161' d='M15.4 13.3 9.9 7.7l-5.5 5.5-.8-.7 6.3-6.2 6.2 6.3z' class='jp-icon3' shape-rendering='geometricPrecision'/%3e %3c/svg%3e"},17150:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' viewBox='0 0 18 18'%3e %3cpath fill='%23616161' d='M5.2 10.5 9 6.8l3.8 3.8H5.2z' class='jp-icon3' shape-rendering='geometricPrecision'/%3e %3c/svg%3e"},28047:e=>{"use strict";e.exports="data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3e %3cg fill='%23616161' class='jp-icon3'%3e %3cpath d='M16.48 17.248A7.5 7.5 0 0 0 6.32 7.706a7 7 0 1 1 10.16 9.542'/%3e %3cpath d='M19.16 14.248A7.5 7.5 0 0 0 9 4.706a7 7 0 1 1 10.16 9.542M16 15a7 7 0 1 1-14 0 7 7 0 0 1 14 0m-4.209-4L13 12.209


onResize(self, width, height)
	db.width = width
	db.height = height
	proxAnchor.tooltip:SetWidth(width)
end

local locked = nil
local function lockDisplay()
	if locked then return end
	proxAnchor:EnableMouse(false)
	proxAnchor:SetMovable(false)
	proxAnchor:SetResizable(false)
	proxAnchor:RegisterForDrag()
	proxAnchor:SetScript("OnSizeChanged", nil)
	proxAnchor:SetScript("OnDragStart", nil)
	proxAnchor:SetScript("OnDragStop", nil)
	proxAnchor.drag:Hide()
	locked = true
end
local function unlockDisplay()
	if not locked then return end
	proxAnchor:EnableMouse(true)
	proxAnchor:SetMovable(true)
	proxAnchor:SetResizable(true)
	proxAnchor:RegisterForDrag("LeftButton")
	proxAnchor:SetScript("OnSizeChanged", onResize)
	proxAnchor:SetScript("OnDragStart", onDragStart)
	proxAnchor:SetScript("OnDragStop", onDragStop)
	proxAnchor.drag:Show()
	locked = nil
end

local function onControlEnter(self)
	GameTooltip:ClearLines()
	GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT")
	GameTooltip:AddLine(self.tooltipHeader)
	GameTooltip:AddLine(self.tooltipText, 1, 1, 1, 1)
	GameTooltip:Show()
end
local function onControlLeave() GameTooltip:Hide() end

function plugin:RestyleWindow()
	if not proxAnchor then return end

	updateSoundButton()
	for k, v in next, db.objects do
		if proxAnchor[k] then
			if v then
				proxAnchor[k]:Show()
			else
				proxAnchor[k]:Hide()
			end
		end
	end
	proxAnchor.text:SetFont(media:Fetch(FONT, db.fontName), db.fontSize)
	--if db.lock then
	--	locked = nil
	--	lockDisplay()
	--else
		locked = true
		unlockDisplay()
	--end

	local x = db.posx
	local y = db.posy
	if x and y then
		local s = proxAnchor:GetEffectiveScale()
		proxAnchor:ClearAllPoints()
		proxAnchor:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x / s, y / s)
	else
		proxAnchor:ClearAllPoints()
		proxAnchor:SetPoint("CENTER", UIParent, "CENTER", 450, -20)
	end
end

-------------------------------------------------------------------------------
-- Proximity Updater
--

local normalProximityText, reverseTargetProximityText, targetProximityText, multiTargetProximityText, reverseMultiTargetProximityText, reverseProximityText
do
	local lastplayed = 0 -- When we last played an alarm sound for proximity.

	local tooClose = {}
	local coloredNames = plugin:GetColoredNameTable()

	local function setText(players)
		if type(players) == "table" then
			proxAnchor.text:SetText(tconcat(players, "\n"))
			wipe(players)
		else
			proxAnchor.text:SetText(players)
		end
	end

	--------------------------------------------------------------------------------
	-- Normal Proximity
	--

	function normalProximityText()
		if functionToFire then CTimerAfter(0.05, functionToFire) else return end

		local anyoneClose = 0
		local _, _, _, mapId = UnitPosition("player")
		for i = 1, maxPlayers do
			local n = unitList[i]
			local _, _, _, tarMapId = UnitPosition(n)
			if mapId == tarMapId and isInRange(n) and myGUID ~= plugin:UnitGUID(n) and not UnitIsDead(n) and UnitInPhase(n) then
				anyoneClose = anyoneClose + 1
				if anyoneClose < 6 then
					local player = plugin:UnitName(n)
					tinsert(tooCl


yet
        if (node.localName == 'h1' && title == null && current == null) {
          title = headerText;
          continue;
        }
      }

      // collect nodes for description (before any version) or current release
      nodes.add(node);
    }

    // complete last section
    finalizeNodes();

    return Changelog(
      title: title,
      description: description,
      releases: releases,
    );
  }

  /// Parses the release header line or return `null` when no version part was recognized.
  ///
  /// Handles some of the common formats:
  /// - `1.2.0`
  /// - `v1.2.0`
  /// - `[1.2.0] - 2025-07-14`
  /// - `unreleased`
  /// - `next release (...)`
  _ParsedHeader? _tryParseAsHeader(html.Element elem, String input) {
    assert(input == input.trim());
    final level = _acceptedHeaderTags.indexOf(elem.localName!);

    final anchor = elem.attributes['id'];
    // special case: unreleased
    final inputLowerCase = input.toLowerCase();
    final unreleasedTexts = ['unreleased', 'next release'];
    for (final unreleasedText in unreleasedTexts) {
      if (inputLowerCase == unreleasedText) {
        return _ParsedHeader(level, 'Unreleased', null, null, anchor, null);
      }
      if (inputLowerCase.startsWith('$unreleasedText ')) {
        String? label = input.substring(unreleasedText.length + 1).trim();
        if (label.isEmpty) {
          label = null;
        }
        return _ParsedHeader(level, 'Unreleased', label, null, anchor, null);
      }
    }

    // remove leading 'Version' label
    const versionLabelPrefix = 'version ';
    if (inputLowerCase.startsWith(versionLabelPrefix)) {
      input = input.substring(versionLabelPrefix.length).trim();
    }

    // extract version
    final versionPart = input.split(' ').firstWhereOrNull((e) => e.isNotEmpty);
    if (versionPart == null) {
      return null;
    }
    final version = _parseVersionPart(versionPart.trim());
    if (version == null) {
      return null;
    }

    // rest of the release header
    String? label = input
        .substring(input.indexOf(versionPart) + versionPart.length)
        .trim();
    if (label.startsWith('- ')) {
      label = label.substring(2).trim();
    }
    if (label.isEmpty) {
      label = null;
    }

    DateTime? date;
    String? note;

    if (label != null) {
      final parts = label.split(' ');
      date = _parseDatePart(parts[0].trim());
      if (date != null) {
        parts.removeAt(0);
      }

      if (parts.isNotEmpty) {
        note = parts.join(' ');
      }
    }

    return _ParsedHeader(
      level,
      version,
      label,
      date,
      anchor ?? version.replaceAll('.', ''),
      note,
    );
  }

  /// Parses the version part of a release title.
  ///
  /// Returns the extracted version string, or null if no version was recognized.
  String? _parseVersionPart(String input) {
    // remove brackets or 'v' if present
    if (input.startsWith('[') && input.endsWith(']')) {
      input = input.substring(1, input.length - 1).trim();
    }
    if (input.startsWith('v')) {
      input = input.substring(1).trim();
    }

    // sanity check if it's a valid semantic version
    try {
      final version = Version.parse(input);
      if (!version.isEmpty && !version.isAny) {
        return input;
      }
    } on FormatException catch (_) {}

    return null;
  }

  final _yyyymmddDateFormats = <RegExp>[
    RegExp(r'^(\d{


late(302535920001353--[[Thread info]])
			.. ":\nIsValidThread(): "
		local is_valid = IsValidThread(obj)
		if is_valid then
			list_obj_str[c] = list_obj_str[c]
				.. self:ConvertValueToInfo(is_valid or nil)
				.. "\nGetThreadStatus(): "
				.. self:ConvertValueToInfo(GetThreadStatus(obj) or nil)
				.. "\nIsGameTimeThread(): "
				.. self:ConvertValueToInfo(IsGameTimeThread(obj))
				.. "\nIsRealTimeThread(): "
				.. self:ConvertValueToInfo(IsRealTimeThread(obj))
				.. "\nThreadHasFlags(), Persist: "
				.. self:ConvertValueToInfo(ThreadHasFlags(obj, 1048576) or false)
				.. " OnMap: "
				.. self:ConvertValueToInfo(ThreadHasFlags(obj, 2097152) or false)
				.. "\n"
		else
			list_obj_str[c] = list_obj_str[c]
				.. self:ConvertValueToInfo(is_valid or nil)
				.. "\n"
		end

		local info_list = ChoGGi_Funcs.Common.RetThreadInfo(obj)
		-- needed for the table that's returned if blacklist is enabled (it starts at 1, getinfo starts at 0)
		local starter = info_list[0] and 0 or 1

		for i = starter, #info_list do
			local info = info_list[i]
			c = c + 1
			list_obj_str[c] = "\ngetinfo(level " .. info.level .. "): "

			c = c + 1
			list_obj_str[c] = "func: " .. info.name .. ", "
				.. self:ConvertValueToInfo(info.func)

			if info.getlocal then
				for j = 1, #info.getlocal do
					local v = info.getlocal[j]
					c = c + 1
					list_obj_str[c] = "getlocal(" .. v.level .. ", " .. j .. "): " .. v.name .. ", "
						.. self:ConvertValueToInfo(v.value)
				end
			end

			if info.getupvalue then
				for j = 1, #info.getupvalue do
					local v = info.getupvalue[j]
					c = c + 1
					list_obj_str[c] = "getupvalue(" .. j .. "): " .. v.name .. ", "
						.. self:ConvertValueToInfo(v.value)
				end
			end
		end
		if info_list.gethook then
			c = c + 1
			list_obj_str[c] = self:ConvertValueToInfo(info_list.gethook)
		end

	end

		-- try to add translated string if it's one of these
	if obj_metatable == TMeta or obj_metatable == TConcatMeta then
		c = c + 1
		local translated_str = Translate(302535920000986--[[Translated]])
		list_obj_str[c] = (obj_metatable == TMeta
			and "\nTMeta " .. translated_str .. ": \n"
			or "\nTConcatMeta " .. translated_str .. ": \n")
			.. Translate(obj)
	end

	-- do we add a metatable to it?
	if not (obj == "nil" or self.is_valid_obj or obj_type == "userdata") and obj_metatable
			or self.is_valid_obj and obj:IsKindOf("BaseSocket")
			or self.is_valid_obj and obj:IsKindOf("XControl")
		then

		table.insert(list_obj_str, 1, "\t-- metatable: " .. self:ConvertValueToInfo(obj_metatable) .. " --")

		if self.enum_vars and next(self.enum_vars) then
			list_obj_str[1] = list_obj_str[1] .. self:HyperLink(obj, function()
				ChoGGi_Funcs.Common.OpenInExamineDlg(self.enum_vars,


elf, meta: WorkerMeta):
        """
        This function should only be called inside by WorkerGroup
        """
        assert isinstance(meta, WorkerMeta)
        self.__dict__.update(meta.to_dict())  # this is hacky
        # print(f"__dict__: {self.__dict__}")
        for key in WorkerMeta.keys:
            val = self.__dict__.get(f"_{key.lower()}", None)
            if val is not None:
                # print(f"set {key} to {val}")
                os.environ[key] = str(val)
        os.environ["REDIS_STORE_SERVER_HOST"] = (
            str(self._master_addr).replace("[", "").replace("]", "") if self._master_addr else ""
        )

    def get_master_addr_port(self):
        return self._master_addr, self._master_port

    def get_cuda_visible_devices(self):
        cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", "not set")
        return cuda_visible_devices

    def print_rank0(self, *args, **kwargs):
        if self.rank == 0:
            print(*args, **kwargs)

    @property
    def world_size(self):
        return self._world_size

    @property
    def rank(self):
        return self._rank

    @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO_WITH_FUNC)
    def execute_with_func_generator(self, func, *args, **kwargs):
        ret_proto = func(self, *args, **kwargs)
        return ret_proto

    @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO)
    def execute_func_rank_zero(self, func, *args, **kwargs):
        result = func(*args, **kwargs)
        return result


$v1, %lo(D_800777E8 + 0x8)($v1)
/* 1E05340 8007DD78 0F004224 */  addiu      $v0, $v0, 0xF
/* 1E05344 8007DD7C 19007214 */  bne        $v1, $s2, .Llevel_22_8007DDE4
/* 1E05348 8007DD80 7C00A2AF */   sw        $v0, 0x7C($sp)
/* 1E0534C 8007DD84 0780023C */  lui        $v0, %hi(g_HudMobys)
/* 1E05350 8007DD88 1057428C */  lw         $v0, %lo(g_HudMobys)($v0)
/* 1E05354 8007DD8C 00000000 */  nop
/* 1E05358 8007DD90 2B100202 */  sltu       $v0, $s0, $v0
/* 1E0535C 8007DD94 13004014 */  bnez       $v0, .Llevel_22_8007DDE4
/* 1E05360 8007DD98 00000000 */   nop
/* 1E05364 8007DD9C 21180000 */  addu       $v1, $zero, $zero
.Llevel_22_8007DDA0:
/* 1E05368 8007DDA0 0000828E */  lw         $v0, 0x0($s4)
/* 1E0536C 8007DDA4 00000000 */  nop
/* 1E05370 8007DDA8 80100200 */  sll        $v0, $v0, 2
/* 1E05374 8007DDAC 21104300 */  addu       $v0, $v0, $v1
/* 1E05378 8007DDB0 FF004230 */  andi       $v0, $v0, 0xFF
/* 1E0537C 8007DDB4 40100200 */  sll        $v0, $v0, 1
/* 1E05380 8007DDB8 21105300 */  addu       $v0, $v0, $s3
/* 1E05384 8007DDBC 00004294 */  lhu        $v0, 0x0($v0)
/* 1E05388 8007DDC0 00000000 */  nop
/* 1E0538C 8007DDC4 02120200 */  srl        $v0, $v0, 8
/* 1E05390 8007DDC8 460002A2 */  sb         $v0, 0x46($s0)
/* 1E05394 8007DDCC 0780023C */  lui        $v0, %hi(g_HudMobys)
/* 1E05398 8007DDD0 1057428C */  lw         $v0, %lo(g_HudMobys)($v0)
/* 1E0539C 8007DDD4 A8FF1026 */  addiu      $s0, $s0, -0x58
/* 1E053A0 8007DDD8 2B100202 */  sltu       $v0, $s0, $v0
/* 1E053A4 8007DDDC F0FF4010 */  beqz       $v0, .Llevel_22_8007DDA0
/* 1E053A8 8007DDE0 0C006324 */   addiu     $v1, $v1, 0xC
.Llevel_22_8007DDE4:
/* 1E053AC 8007DDE4 01005226 */  addiu      $s2, $s2, 0x1
.Llevel_22_8007DDE8:
/* 1E053B0 8007DDE8 01003126 */  addiu      $s1, $s1, 0x1
/* 1E053B4 8007DDEC 0600222A */  slti       $v0, $s1, 0x6
/* 1E053B8 8007DDF0 BFFF4014 */  bnez       $v0, .Llevel_22_8007DCF0
/* 1E053BC 8007DDF4 6666023C */   lui       $v0, (0x66666667 >>


L81 472.2c-4.3 17.1 6.1 34.5 23.3 38.8s34.5-6.1 38.8-23.3l13-52.1c9 3.4 18.4 6.2 28 8.2L177 472.2c-4.3 17.1 6.1 34.5 23.3 38.8s34.5-6.1 38.8-23.3l10.4-41.4c33.4-4.4 64.1-17.4 89.8-36.7c14.1-10.6 17-30.7 6.4-44.8s-30.7-17-44.8-6.4c-10.2 7.7-21.7 13.9-34 18.3L321 160c9.4-.3 18.5-4.7 24.6-12.8c10.6-14.1 7.8-34.2-6.4-44.8c-1.1-.8-2.2-1.6-3.3-2.4L351 39.8c4.3-17.1-6.1-34.5-23.3-38.8S293.2 7.1 289 24.2L277.2 71.5c-9.3-2.7-18.8-4.6-28.6-5.9L255 39.8zM163.2 143.3L117.3 326.8C103.9 306.5 96 282.2 96 256c0-48.7 27.2-91 67.2-112.7zm8.6 229.5l61.1-244.6c9.9 .7 19.5 2.5 28.7 5.3l-62 248.1c-9.7-1.9-19-4.8-27.8-8.8z"],headset:[512,512,[],"f590","M256 48C141.1 48 48 141.1 48 256v40c0 13.3-10.7 24-24 24s-24-10.7-24-24V256C0 114.6 114.6 0 256 0S512 114.6 512 256V400.1c0 48.6-39.4 88-88.1 88L313.6 488c-8.3 14.3-23.8 24-41.6 24H240c-26.5 0-48-21.5-48-48s21.5-48 48-48h32c17.8 0 33.3 9.7 41.6 24l110.4 .1c22.1 0 40-17.9 40-40V256c0-114.9-93.1-208-208-208zM144 208h16c17.7 0 32 14.3 32 32V352c0 17.7-14.3 32-32 32H144c-35.3 0-64-28.7-64-64V272c0-35.3 28.7-64 64-64zm224 0c35.3 0 64 28.7 64 64v48c0 35.3-28.7 64-64 64H352c-17.7 0-32-14.3-32-32V240c0-17.7 14.3-32 32-32h16z"],"badger-honey":[640,512,[129441],"f6b4","M164.6 389.3l16-37.3H298.7l16.9 101.3c2.6 15.4 15.9 26.7 31.6 26.7h31.1c19.8 0 34.8-17.8 31.6-37.3L393 342.1c27.9-29 80.6-70.8 144.1-90.8l16.1 25.8c3.1 5 10.4 5 13.6 0l22.8-36.5c12.9-2.1 25.2-7.4 34.4-16.6c10.2-10.2 16-24.1 16-38.6v-3.8c0-23.2-12.6-44.5-32.8-55.8L525.3 80.3C506.1 69.6 484.5 64 462.5


353 XX XXX XXXX",
        flagEmoji = "🇮🇪",
        flagResourceName = "flag_ie",
    ),
)
/*
 * Copyright 2025 Mifos Initiative
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * See See https://github.com/openMF/kmp-project-template/blob/main/LICENSE
 */
package template.core.base.platform.update

/**
 * Manages application update detection and processing.
 *
 * This interface abstracts platform-specific implementations for checking
 * and managing application updates. It provides methods to initiate update checks
 * and verify the state of previously initiated update processes.
 *
 * Platform-specific implementations of this interface typically integrate with:
 * - Google Play In-App Updates API on Android
 * - AppStoreKit on iOS
 * - Other platform-specific update mechanisms
 *
 * The update management process is essential for ensuring users have access to
 * the latest features, security patches, and performance improvements.
 */
interface AppUpdateManager {

    /**
     * Initiates a check for available application updates.
     *
     * This method communicates with the relevant app distribution platform to
     * determine if a newer version of the application is available for download.
     * The implementation may handle the entire update flow, including presenting
     * update dialogs to the user and facilitating the download and installation
     * process, depending on platform capabilities.
     */
    fun checkForAppUpdate()

    /**
     * Verifies if there is an update process that was previously initiated but not completed.
     *
     * This method is typically called during application startup to determine if
     * an update process needs to be resumed. Update processes may be interrupted
     * by application termination, system restart, or other events, and this method
     * allows the application to recover and continue the update process.
     */
    fun checkForResumeUpdateState()
}
/*
 * Copyright 2025 Mifos Initiative
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * See See https://github.com/openMF/kmp-project-template/blob/main/LICENSE
 */
package template.core.base.platform.model

/**
 * Represents standardized MIME (Multipurpose Internet Mail Extensions) types for various file formats.
 *
 * This enum provides a structured representation of common MIME types organized by categories
 * (images, videos, audio, documents, archives) with their corresponding string values and file extensions.
 * It offers utility methods to determine the appropriate MIME type from file extensions or filenames.
 *
 * @property value The standard MIME type string representation (e.g., "image/jpeg")
 * @property extensions The file extensions associated with this MIME type (e.g., "jpg", "jpeg")
 */
enum class MimeType(val value: String, vararg val extensions: String) {
    /**
     * JPEG image format - "image/jpeg"
     * Extensions: jpg, jpeg
     */
    IMAGE_JPEG("image/jpeg", "jpg", "jpeg"),

    /**
     * PNG image format - "image/png"
     * Extension: png
     */
    IMAGE_PNG("image/png", "png"),

    /**
     * GIF image format - "


er
  /// Guide.
  /// </important>
  ///
  /// May throw [BadRequestException].
  /// May throw [ForbiddenException].
  /// May throw [UnauthorizedClientException].
  /// May throw [ConflictException].
  /// May throw [ResourceLimitExceededException].
  /// May throw [ThrottledClientException].
  /// May throw [ServiceUnavailableException].
  /// May throw [ServiceFailureException].
  ///
  /// Parameter [channelArn] :
  /// The ARN of the ban request.
  ///
  /// Parameter [memberArn] :
  /// The ARN of the member being banned.
  ///
  /// Parameter [chimeBearer] :
  /// The AppInstanceUserArn of the user that makes the API call.
  @Deprecated(
      'Replaced by CreateChannelBan in the Amazon Chime SDK Messaging Namespace')
  Future<CreateChannelBanResponse> createChannelBan({
    required String channelArn,
    required String memberArn,
    String? chimeBearer,
  }) async {
    final headers = <String, String>{
      if (chimeBearer != null) 'x-amz-chime-bearer': chimeBearer.toString(),
    };
    final $payload = <String, dynamic>{
      'MemberArn': memberArn,
    };
    final response = await _protocol.send(
      payload: $payload,
      method: 'POST',
      requestUri: '/channels/${Uri.encodeComponent(channelArn)}/bans',
      headers: headers,
      exceptionFnMap: _exceptionFns,
    );
    return CreateChannelBanResponse.fromJson(response);
  }

  /// Adds a user to a channel. The InvitedBy response field is
  /// derived from the request header. A channel member can:
  ///
  ///

  ///

  /// List messages
  ///

  ///

  /// Send messages
  ///

  ///

  /// Receive messages
  ///

  ///

  /// Edit their own messages
  ///

  ///

  /// Leave the channel
  ///

  ///

  /// Privacy settings impact this action as follows:
  ///
  ///

  ///

  /// Public Channels: You do not need to be a member to list messages, but you
  /// must be a member to send messages.
  ///

  ///

  /// Private Channels: You must be a member to list or send messages.
  ///

  ///
 <note>
  /// The x-amz-chime-bearer request header is mandatory. Use the
  /// AppInstanceUserArn of the user that makes the API call as the
  /// value in the header.
  /// </note> <important>
  /// This API is is no longer supported and will not be updated. We
  /// recommend using the latest version, CreateChannelMembership,
  /// in the Amazon Chime SDK.
  ///
  /// Using the latest version requires migrating to a dedicated namespace. For
  /// more information, refer to Migrating
  /// from the Amazon Chime namespace in the Amazon Chime SDK Developer
  /// Guide.
  /// </important>
  ///
  /// May throw [BadRequestException].
  /// May throw [ForbiddenException].
  /// May throw [UnauthorizedClientException].
  /// May throw [ConflictException].
  /// May throw [ResourceLimitExceededException].
  /// May throw [ThrottledClientException].
  /// May throw [ServiceUnavailableException].
  /// May throw [ServiceFailureException].
  ///
  /// Parameter [channelArn] :
  /// The ARN of the channel to which


a3, a3, 1
#if !XCHAL_HAVE_LOOPS
	addi	a4, a4, -1
	bnez	a4, .Lloop
#endif /* !XCHAL_HAVE_LOOPS */
.Lloopend:

	bltu	a6, a3, .Lreturn
	addi	a2, a2, 1	/* increment if udividend >= udivisor */
.Lreturn:
	neg	a5, a2
	movltz	a2, a5, a7	/* return (sign < 0) ? -quotient : quotient */
	abi_ret_default

.Lle_one:
	beqz	a3, .Lerror
	neg	a2, a6		/* if udivisor == 1, then return... */
	movgez	a2, a6, a7	/* (sign < 0) ? -udividend : udividend */
	abi_ret_default

.Lspecial:
	bltu	a6, a3, .Lreturn0 /* if dividend < divisor, return 0 */
	movi	a2, 1
	movi	a4, -1
	movltz	a2, a4, a7	/* else return (sign < 0) ? -1 : 1 */
	abi_ret_default

.Lerror:
	/* Divide by zero: Use an illegal instruction to force an exception.
	   The subsequent "DIV0" string can be recognized by the exception
	   handler to identify the real cause of the exception.  */
	ill
	.ascii	"DIV0"

.Lreturn0:
	movi	a2, 0
#endif /* XCHAL_HAVE_DIV32 */
	abi_ret_default

ENDPROC(__divsi3)
EXPORT_SYMBOL(__divsi3)


cent-success a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link):not(.page-link):not(.badge):not(.btn){color:#00bc8c}.dark-mode .accent-success .btn-link:hover,.dark-mode .accent-success .nav-tabs .nav-link:hover,.dark-mode .accent-success a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link):not(.page-link):not(.badge):not(.btn):hover{color:#007053}.dark-mode .accent-success .dropdown-item.active,.dark-mode .accent-success .dropdown-item:active{background-color:#00bc8c;color:#fff}.dark-mode .accent-success .custom-control-input:checked~.custom-control-label::before{background-color:#00bc8c;border-color:#005640}.dark-mode .accent-success .custom-control-input:checked~.custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E")}.dark-mode .accent-success .custom-control-input:focus:not(:checked)~.custom-control-label::before,.dark-mode .accent-success .custom-file-input:focus~.custom-file-label,.dark-mode .accent-success .custom-select:focus,.dark-mode .accent-success .form-control:focus:not(.is-invalid):not(.is-warning):not(.is-valid){border-color:#3dffcd}.dark-mode .accent-success .page-item .page-link{color:#00bc8c}.dark-mode .accent-success .page-item.active .page-link,.dark-mode .accent-success .page-item.active a{background-color:#00bc8c;border-color:#00bc8c;color:#fff}.dark-mode .accent-success .page-item.disabled .page-link,.dark-mode .accent-success .page-item.disabled a{background-color:#fff;border-color:#dee2e6;color:#6c757d}.dark-mode .accent-success [class*=sidebar-dark-] .sidebar a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link){color:#c2c7d0}.dark-mode .accent-success [class*=sidebar-dark-] .sidebar a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link):hover{color:#fff}.dark-mode .accent-success [class*=sidebar-light-] .sidebar a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link){color:#343a40}.dark-mode .accent-success [class*=sidebar-light-] .sidebar a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link):hover{color:#212529}.dark-mode .dark-mode.accent-success .page-item .page-link:focus,.dark-mode .dark-mode.accent-success .page-item .page-link:hover{color:#00d69f}.dark-mode .accent-info .btn-link,.dark-mode .accent-info .nav-tabs .nav-link,.dark-mode .accent-info a:not(.dropdown-item):not(.btn-app):not(.nav-link):not(.brand-link):not(.page-link):not(.badge):not(.btn){color:#3498db}.dark-mode .accent-info .btn-link:hover,.dark-mode .accent-info .nav-tabs .nav-link:hover,.dark-mode .a


>{@link #GL_COLOR_ATTACHMENT19 COLOR_ATTACHMENT19}

{@link #GL_COLOR_ATTACHMENT20 COLOR_ATTACHMENT20}	{@link #GL_COLOR_ATTACHMENT21 COLOR_ATTACHMENT21}	{@link #GL_COLOR_ATTACHMENT22 COLOR_ATTACHMENT22}	{@link #GL_COLOR_ATTACHMENT23 COLOR_ATTACHMENT23}

{@link #GL_COLOR_ATTACHMENT24 COLOR_ATTACHMENT24}	{@link #GL_COLOR_ATTACHMENT25 COLOR_ATTACHMENT25}	{@link #GL_COLOR_ATTACHMENT26 COLOR_ATTACHMENT26}	{@link #GL_COLOR_ATTACHMENT27 COLOR_ATTACHMENT27}

{@link #GL_COLOR_ATTACHMENT28 COLOR_ATTACHMENT28}	{@link #GL_COLOR_ATTACHMENT29 COLOR_ATTACHMENT29}	{@link #GL_COLOR_ATTACHMENT30 COLOR_ATTACHMENT30}	{@link #GL_COLOR_ATTACHMENT31 COLOR_ATTACHMENT31}

{@link #GL_DEPTH_ATTACHMENT DEPTH_ATTACHMENT}	{@link #GL_STENCIL_ATTACHMENT STENCIL_ATTACHMENT}	{@link #GL_DEPTH_STENCIL_ATTACHMENT DEPTH_STENCIL_ATTACHMENT}

     * @param texTarget  the type of texture
     * @param texture    the texture object to attach to the framebuffer attachment point named by {@code attachment}
     * @param level      the mipmap level of {@code texture} to attach
     * @param layer      the layer of a 2-dimensional image within the 3-dimensional texture.
     *
     * @see Reference Page
     */
    fun framebufferTexture3D(target: FramebufferTarget, attachment: Attachment, texTarget: TextureTarget, texture: GlTexture, level: Int, layer: Int) =
            GL30C.glFramebufferTexture3D(target.i, attachment.i, texTarget.i, texture.name, level, layer)

    /**
     * Attaches a layer of a 3D texture object as a logical buffer to the currently bound framebuffer object.
     *
     * @param attachment the attachment point of the framebuffer. One of:

{@link #GL_COLOR_ATTACHMENT0 COLOR_ATTACHMENT0}	{@link #GL_COLOR_ATTACHMENT1 COLOR_ATTACHMENT1}	{@link #GL_COLOR_ATTACHMENT2 COLOR_ATTACHMENT2}	{@link #GL_COLOR_ATTACHMENT3 COLOR_ATTACHMENT3}

{@link #GL_COLOR_ATTACHMENT4 COLOR_ATTACHMENT4}	{@link #GL_COLOR_ATTACHMENT5 COLOR_ATTACHMENT5}	{@link #GL_COLOR_ATTACHMENT6 COLOR_ATTACHMENT6}	{@link #GL_COLOR_ATTACHMENT7 COLOR_ATTACHMENT7}

{@link #GL_COLOR_ATTACHMENT8 COLOR_ATTACHMENT8}	{@link #GL_COLOR_ATTACHMENT9 COLOR_ATTACHMENT9}	{@link #GL_COLOR_ATTACHMENT10 COLOR_ATTACHMENT10}	{@link #GL_COLOR_ATTACHMENT11 COLOR_ATTACHMENT11}

{@link #GL_COLOR_ATTACHMENT12 COLOR_ATTACHMENT12}	{@link #GL_COLOR_ATTACHMENT13 COLOR_ATTACHMENT13}	{@link #GL_COLOR_ATTACHMENT14 COLOR_ATTACHMENT14}	{@link #


    const months = [...new Set(data.map(item => item.Month))];
        monthSelect.innerHTML = months.map(month => `<option value="${month}">${month}</option>`).join('');
    }

    // Écouteur d'événements pour le bouton de chargement
    loadDataButton.addEventListener('click', () => {
        const selectedTicker = tickerSelect.value;
        const selectedYear = parseInt(yearSelect.value);
        const selectedMonth = parseInt(monthSelect.value);

        const filteredData = allData.filter(item =>
            item.Ticker === selectedTicker &&
            item.Year === selectedYear &&
            item.Month === selectedMonth
        );

        updateChart(filteredData);
    });

    // Mettre à jour ou créer le graphique
    function updateChart(data) {
        const ctx = document.getElementById('financeChart').getContext('2d');
        if (financeChart) {
            financeChart.destroy(); // Détruire l'ancien graphique
        }
        financeChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: data.map(item => `${item.Month}/${item.Year}`),
                datasets: [
                    {
                        label: 'Average ROI',
                        data: data.map(item => item.AverageROI),
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1,
                        yAxisID: 'y-axis-roi'
                    },
                    {
                        label: 'Volatility',
                        data: data.map(item => item.Volatility),
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderWidth: 1,
                        yAxisID: 'y-axis-vol'
                    }
                ]
            },
            options: {
                scales: {
                    'y-axis-roi': {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: {
                            display: true,
                            text: 'Average ROI'
                        }
                    },
                    'y-axis-vol': {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: 'Volatility'
                        },
                        grid: {
                            drawOnChartArea: false
                        }
                    }
                }
            }
        });
    }
});
// Copyright (c) 2024 steff393, MIT license

// ----------------------------- COMMON SECTION: START ------------------------------
function initNavBar() {
	for (const element of document.querySelectorAll('[top-nav-link]')) {
		element.addEventListener('click', function() {window.location.href = element.getAttribute('top-nav-link')});
	}
}

function assignValuesToHtml(values) {
	let valueContainerElements = document.querySelectorAll('[data-value]');
	for (const element of valueContainerElements) {
		const key = element.getAttribute('data-value');
		if (values[key] !== undefined) {
			element.innerHTML = values[key].toLocaleString('de-DE');
		}
	}
}

function setClass(element, className, state) {
	if (state) {
		element.classList.add(className)
	} else {
		element.classList.remove(className)
	}
}

function setSectionVisibility(sectionId, isVisible) {
	setClass(document.


onverter.gson.GsonConverterFactory
import java.security.NoSuchAlgorithmException

class RetrofitUtil private constructor() {

    /**
     * 获取retrofit
     * @return
     */
    fun retrofit(): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClient())
            .baseUrl(ContentValue.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())  //指定Gson作为解析Json数据的Converter
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //指定使用RxJava 作为CallAdapter
            .build()
    }

    companion object {
        val CONNECT_TIME_OUT = 30//连接超时时长x秒
        val READ_TIME_OUT = 30//读数据超时时长x秒
        val WRITE_TIME_OUT = 30//写数据接超时时长x秒
        private var mInstance: RetrofitUtil? = null
        var TAG = RetrofitUtil::class.java.simpleName
        fun get(): RetrofitUtil {
            if (mInstance == null) {
                synchronized(RetrofitUtil::class.java) {
                    if (mInstance == null) {
                        mInstance = RetrofitUtil()
                    }
                }
            }
            return mInstance!!
        }

        /**
         * 设置okhttp参数
         * @return
         */
        private fun okHttpClient(): OkHttpClient {
            //开启log
            return OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)
                /*.addInterceptor(object :Interceptor {
                    override fun intercept(chain: Interceptor.Chain): Response {
                        var oldRequest = chain.request();
                        var sign = getSign(oldRequest.url());
                        //添加sign参数
                        var newBuilder = oldRequest.url()
                            .newBuilder()
                            .scheme(oldRequest.url().scheme())
                            .host(oldRequest.url().host())
                            .addQueryParameter(ApiHelper.PARAM_SIGN, sign)
                        var newRequest = oldRequest.newBuilder()
                            .method(oldRequest.method(), oldRequest.body())
                            .url(newBuilder.build())
                            .build()
                        return chain.proceed(newRequest);
                    }

                })*/
                .build()
        }
    }

}
package com.camera.lingxiao.common.exception

import android.util.MalformedJsonException

import com.google.gson.JsonParseException

import org.json.JSONException

import java.net.ConnectException
import java.net.SocketTimeoutException
import java.text.ParseException

import retrofit2.HttpException

/**
 * @author lingxiao 异常处理类
 */
object ExceptionEngine {
    val UN_KNOWN_ERROR = 1000//未知错误
    val ANALYTIC_SERVER_DATA_ERROR = 1001//解析(服务器)数据错误
    val ANALYTIC_CLIENT_DATA_ERROR = 1002//解析(客户端)数据错误
    val CONNECT_ERROR = 1003//网络连接错误
    val TIME_OUT_ERROR = 1004//网络连接超时

    fun handlerException(e: Throwable): ApiException {
        val ex: ApiException
        if (e is HttpException) {             //HTTP错误
            ex = ApiException(e, e.code())
            ex.msg = "网络错误"  //均视为网络错误
            return ex
        } else if (e is ServerException) {    //服务器返回的错误
            ex = ApiException(e, e.code)
            ex.msg = e.msg
            return ex
        } else if (e is JsonParseException
            || e is JSONException


져가야 합니다."}},
[3635] = {"노움 기계공학", nil, {"노움 기계공학에 대해 더 알고 싶으면 무법항에 있는 오글소프 오브노티쿠스에게 기계공학 설명서를 가져가야 합니다."}},
[3636] = {"빛의 힘", nil, {"대주교 베네딕투스가 가시덩굴 구릉에 있는 혹한의 암네나르를 처치해달라고 부탁했습니다."}},
[3637] = {"노움 기계공학", nil, {"노움 기계공학에 대해 더 알고 싶으면 무법항에 있는 오글소프 오브노티쿠스에게 기계공학 설명서를 가져가야 합니다."}},
[3638] = {"비밀유지서약서", nil, {"고블린 기술자가 되는 데 동의하면 닉스의 비밀유지서약서를 마우스 오른쪽 단추로 클릭한 후 가젯잔에 있는 닉스 스프로켓스프링과 대화해야 합니다."}},
[3639] = {"직접 만든 물건", nil, {"가젯잔에 있는 닉스 스프링스프로켓에게 대형 철제 폭탄 20개, 조밀한 다이너마이트 20개, 그리고 양 폭탄 5개를 가져가야 합니다."}},
[3640] = {"비밀유지 서약서", nil, {"노움 기술자가 되는 데 동의하면 비밀유지서약서를 마우스 오른쪽 단추로 클릭해 서명을 한 후 아이언포지의 수석땜장이 오버스파크와 다시 한번 대화하십시오."}},
[3641] = {"직접 만든 물건", nil, {"아이언포지에 있는 수석땜장이 오버스파크에게 미스릴관 6개, 정밀한 조준경 1개, 그리고 고급 표적 허수아비 2개를 가져가야 합니다."}},
[3642] = {"비밀유지서약서", nil, {"노움 기술자가 되는 데 동의하면 비밀


),
                canEdit = canEditNodeIds.contains(it.nodeId),
                canDelete = canDeleteNodeIds.contains(it.nodeId),
                canView = canViewNodeIds.contains(it.nodeId),
                gateway = gatewayShowName,
                displayName = NodeStringIdUtils.getRefineDisplayName(nodeStringId, it.displayName),
                createTime = if (null == it.createdTime) {
                    ""
                } else {
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(it.createdTime)
                },
                lastModifyTime = if (null == it.lastModifyTime) {
                    ""
                } else {
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(it.lastModifyTime)
                },
                lastModifyUser = it.lastModifyUser ?: "",
                agentStatus = getAgentStatus(it),
                agentVersion = it.agentVersion,
                agentHashId = HashUtil.encodeLongId(thirdPartyAgent?.id ?: 0L),
                cloudAreaId = it.cloudAreaId,
                osType = if (OsType.UNIX.name == it.osType || OsType.FREEBSD.name == it.osType) {
                    OsType.LINUX.name // 节点管理中 UNIX，FREEBSD 这两种状态归属于LINUX
                } else {
                    it.osType
                },
                bkHostId = it.hostId,
                serverId = it.serverId,
                size = it.size,
                envNames = nodeEnvsGroups[it.nodeId],
                lastBuildTime = if (null == it.lastBuildTime) {
                    ""
                } else {
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(it.lastBuildTime)
                },
                tags = tagMaps[it.nodeId]
            )
        }
    }

    fun getNodeStatus(
        userId: String,
        projectId: String,
        nodeHashId: String?,
        nodeName: String?,
        agentHashId: String?
    ): NodeWithPermission {
        val hashId = when {
            nodeHashId != null -> nodeHashId
            nodeName != null -> nodeDao.getByDisplayName(dslContext, projectId, nodeName, null)
                .firstOrNull()?.nodeHashId

            agentHashId != null -> thirdPartyAgentDao.getAgent(dslContext, HashUtil.decodeIdToLong(agentHashId))
                ?.nodeId?.let { HashUtil.encodeLongId(it) }

            else -> null
        } ?: throw ErrorCodeException(
            errorCode = ERROR_NODE_NAME_OR_ID_INVALID
        )
        return listByHashIds(userId, projectId, listOf(hashId)).firstOrNull() ?: throw ErrorCodeException(
            errorCode = ERROR_NODE_NOT_EXISTS,
            params = arrayOf(hashId)
        )
    }

    fun listByHashIds(userId: String, projectId: String, hashIds: List<String>): List<NodeWithPermission> {
        val nodeIds = hashIds.map { HashUtil.decodeIdToLong(it) }
        val nodeRecordList = nodeDao.listAllByIds(dslContext, projectId, nodeIds)
        if (nodeRecordList.isEmpty()) {
            return emptyList()
        }

        val permissionMap = environmentPermissionService.listNodeByPermissions(
            userId, projectId,
            permissions = setOf(AuthPermission.USE, AuthPermission.EDIT, AuthPermission.DELETE)
        )

        val canViewNodeIds = environmentPermissionService.listNodeByRbacPermission(
            userId = userId,
            projectId = projectId,
            nodeRecordList = nodeRecordList,
            authPermission = AuthPermission.VIEW
        ).map { it.nodeId }

        val canUseNodeIds = if (permissionMap.containsKey(AuthPermission.USE)) {
            permissionMap[AuthPermission.USE]?.map { HashUtil.decodeIdToLong(it) } ?: emptyList()
        } else {
            emptyList()
        }
        val canEditNodeIds = if (permissionMap.containsKey(Aut


ptional, sharing)
        {}

        explicit NonCoherentUniformBuffer(std::shared_ptr<Device> device,
            bool mappedPersistently,
            uint32_t arraySize,
            std::shared_ptr<Allocator> allocator = nullptr,
            const Buffer::Initializer& optional = Buffer::Initializer(),
            const Sharing& sharing = Sharing()):
            TBaseUniformBuffer<Type>(std::move(device), arraySize,
                VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
                VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
                optional, sharing, std::move(allocator), mappedPersistently)
        {}

        bool flushMappedRange(const helpers::UniformArray<Type>& array) noexcept
        {
            if (!Buffer::memory->mapped())
                return false;
            const VkDeviceSize alignment = BaseUniformBuffer::getAlignment();
            const VkDeviceSize nonCoherentAtomSize = BaseUniformBuffer::getNonCoherentAtomSize();
            VkDeviceSize offset = array.getFirstIndex() * alignment;
            if (offset % nonCoherentAtomSize)
                offset = offset / nonCoherentAtomSize * nonCoherentAtomSize;
            VkDeviceSize size = array.getUpdatedRange() * alignment;
            const VkDeviceSize minFlushSize = std::min(Buffer::memory->getSize(), nonCoherentAtomSize);
            size = std::max(size, minFlushSize);
            return Buffer::memory->flushMappedRange(offset + BaseUniformBuffer::getMapOffset(), size);
        }
    };

    template<class T> using UniformBufferUPtr = std::unique_ptr<UniformBuffer<T>>;
    template<class T> using UniformBufferSPtr = std::shared_ptr<UniformBuffer<T>>;
    template<class T> using NonCoherentUniformBufferUPtr = std::unique_ptr<NonCoherentUniformBuffer<T>>;
    template<class T> using NonCoherentUniformBufferSPtr = std::shared_ptr<NonCoherentUniformBuffer<T>>;
} // namespace magma


;max-width:100%;overflow-wrap:break-word}.cList .lDiv div{padding:.2em .5em .2em;padding-left:.2em;white-space:nowrap}.cList .lDiv div:hover{background:#377796;cursor:pointer;color:#fff}.cList .lDiv div input{cursor:pointer}.showAllColBtn{border-bottom:solid 1px #ccc;border-top:solid 1px #ccc;cursor:pointer;font-size:.9em;font-family:"Open Sans Bold",sans-serif;padding:.35em 1em;text-align:center;font-weight:normal}.showAllColBtn:hover{background:#377796;cursor:pointer;color:#fff}#page_content{line-height:1.5}.navigation_separator{color:#eee;display:inline-block;font-size:1.5em;text-align:center;height:1.4em}.navigation{width:100%;background-color:#377796;color:#eee}.navigation td{margin:0;padding:0;vertical-align:middle;white-space:nowrap}.navigation input[type=submit]{background:#377796;color:#eee;border:none;filter:none;margin:5px;padding:.4em}.navigation input[type=submit]:hover{color:#fff;cursor:pointer;background-color:#666}.navigation input.edit_mode_active{color:#fff;cursor:pointer;background-color:#666}.navigation select{margin:0 .8em;border:none}.navigation input[type=text]{border:none}.navigation_goto{width:100%}.insertRowTable td,.insertRowTable th{vertical-align:middle}.cEdit{margin:0;padding:0;position:absolute}.cEdit input[type=text],.cEdit input[type=password],.cEdit input[type=number]{background:#fff;height:100%;margin:0;padding:0}.cEdit .edit_area{background:#fff;border:1px solid #999;min-width:10em;padding:.3em .5em}.cEdit .edit_area select,.cEdit .edit_area textarea{width:97%}.cEdit .cell_edit_hint{color:#555;font-size:.8em;margin:.3em .2em}.cEdit .edit_box{overflow-x:hidden;overflow-y:scroll;padding:0;margin-top:10px}.cEdit .edit_box_posting{background:#fff url("../img/ajax_clock_small.gif") no-repeat right center;padding-right:1.5em}.cEdit .edit_area_loading{background:#fff url("../img/ajax_clock_small.gif") no-repeat center;height:10em}.cEdit .goto_link{background:#eee;color:#555;padding:.2em .3em}.saving_edited_data{background:url("../img/ajax_clock_small.gif") no-repeat left;padding-left:20px}.relationalTable select{width:125px;margin-right:5px}.ui-timepicker-div .ui-widget-header{margin-bottom:8px}.ui-timepicker-div dl{text-align:left}.ui-timepicker-div dl dt{height:25px;margin-bottom:-25px}.ui-timepicker-div dl dd{margin:0 10px 10px 85px}.ui-timepicker-div td{font-size:90%}.ui-tpicker-grid-label{background:none;border:none;margin:0;padding:0}.ui-timepicker-rtl{direction:rtl}.ui-timepicker-rtl dl{text-align:right}.ui-timepicker-rtl dl dd{margin:0 65px 10px 10px}.ui_tpicker_time_input{width:100%}body .ui-widget{font-size:1em}body #ui-datepicker-div{z-index:9999 !important}.ui-dialog .pma-fieldset legend a{color:#235a81}div#page_content div#tableslistcontainer{margin-top:1em}div#page_content div#tableslistcontainer table.data{border-top:.1px solid #eee}div#page_content div.result_query{margin-top:1em}table.show_create{margin-top:1em}table.show_create


                if discr < fit {
                    bug!("Integer::repr_discr: `#[repr]` hint too small for \
                          discriminant range of enum `{}", ty)
                }
                return (discr, ity.is_signed());
            }
            attr::ReprExtern => {
                match &tcx.sess.target.target.arch[..] {
                    // WARNING: the ARM EABI has two variants; the one corresponding
                    // to `at_least == I32` appears to be used on Linux and NetBSD,
                    // but some systems may use the variant corresponding to no
                    // lower bound.  However, we don't run on those yet...?
                    "arm" => I32,
                    _ => I32,
                }
            }
            attr::ReprAny => I8,
            attr::ReprPacked => {
                bug!("Integer::repr_discr: found #[repr(packed)] on enum `{}", ty);
            }
            attr::ReprSimd => {
                bug!("Integer::repr_discr: found #[repr(simd)] on enum `{}", ty);
            }
        };

        // If there are no negative values, we can use the unsigned fit.
        if min >= 0 {
            (cmp::max(unsigned_fit, at_least), false)
        } else {
            (cmp::max(signed_fit, at_least), true)
        }
    }
}

/// Fundamental unit of memory access and layout.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Primitive {
    Int(Integer),
    F32,
    F64,
    Pointer
}

impl Primitive {
    pub fn size(self, dl: &TargetDataLayout) -> Size {
        match self {
            Int(I1) | Int(I8) => Size::from_bits(8),
            Int(I16) => Size::from_bits(16),
            Int(I32) | F32 => Size::from_bits(32),
            Int(I64) | F64 => Size::from_bits(64),
            Pointer => dl.pointer_size
        }
    }

    pub fn align(self, dl: &TargetDataLayout) -> Align {
        match self {
            Int(I1) => dl.i1_align,
            Int(I8) => dl.i8_align,
            Int(I16) => dl.i16_align,
            Int(I32) => dl.i32_align,
            Int(I64) => dl.i64_align,
            F32 => dl.f32_align,
            F64 => dl.f64_align,
            Pointer => dl.pointer_align
        }
    }
}

/// Path through fields of nested structures.
// FIXME(eddyb) use small vector optimization for the common case.
pub type FieldPath = Vec<u32>;

/// A structure, a product type in ADT terms.
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct Struct {
    pub align: Align,

    /// If true, no alignment padding is used.
    pub packed: bool,

    /// If true, the size is exact, otherwise it's only a lower bound.
    pub sized: bool,

    /// Offsets for the first byte of each field.
    /// FIXME(eddyb) use small vector optimization for the common case.
    pub offsets: Vec<Size>,

    pub min_size: Size,
}

impl<'a, 'gcx, 'tcx> Struct {
    pub fn new(dl: &TargetDataLayout, packed: bool) -> Struct {
        Struct {
            align: if packed { dl.i8_align } else { dl.aggregate_align },
            packed: packed,
            sized: true,
            offsets: vec![],
            min_size: Size::from_bytes(0),
        }
    }

    /// Extend the Struct with more fields.
    pub fn extend<I>(&mut self, dl: &TargetDataLayout,
                     fields: I,
                     scapegoat: Ty<'gcx>)
                     -> Result<(), LayoutError<'gcx>>
    where I: Iterator<Item=Result<&'a Layout, Layo


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

namespace SnowBank.Data.Binary
{
	using System;
	using System.Buffers;
	using System.Buffers.Binary;
	using System.Text;
	using SnowBank.Data.Tuples;

	/// Encoders that can encode primitive types into binary form
	public static class SpanEncoders
	{

		#region Encoding Helper Methods...

		/// Encodes a value, using a pool if necessary
		/// <typeparam name="TEncoder">Encoder used for this operation</typeparam>
		/// <typeparam name="TValue">Type of the encoded value</typeparam>
		/// <param name="value">Value to encode</param>
		/// <param name="pool">Pool used to allocate buffers</param>
		/// <param name="maxSize">If specified, maximum allowed size for the buffer. If 0, allows the buffer to grow up to the maximum size supported by the CLR.</param>
		/// <param name="result">Receives the span that points to the encoded result</param>
		/// <param name="buffer">Receives the buffer allocated from the pool to hold the result, or <c>null</c> if the result is already hosted somewhere else in memory.</param>
		/// <param name="range">Receives the range in <paramref name="buffer"/> that contains <paramref name="result"/> (only if buffer is not <c>null</c>)</param>
		/// <exception cref="ArgumentException">If the buffer size would exceed the maximum allowed size (or maximum limit supported by the CLR)</exception>
		/// <remarks>
		/// <para>The method will call <see cref="ISpanEncoder{TValue}.TryGetSpan"/> to extract any already encoded result.</para>
		/// <para>If no span could be extracted, then it will call <see cref="ISpanEncoder{TValue}.TryGetSizeHint"/>, and rent a buffer from the pool with a safe initial size.</para>
		/// <para>The method will call <see cref="ISpanEncoder{TValue}.TryEncode"/> repeatedly, with a larger and larger buffer, until it returns <c>true</c>, throws, or the buffer reaches the maximum allowed size.</para>
		/// </remarks>
		public static void Encode<TEncoder, TValue>(in TValue? value, ArrayPool<byte>


["medals"]) + len(awardsTorn["honors"]), "hof": Paginator(hof, 50).get_page(request.GET.get("p_hof"))}
        )

    except Exception as e:
        return returnError(exc=e, session=request.session)

def showPinned(request):
    try:
        if request.session.get("player") and request.method == "POST":
            player = getPlayer(request.session["player"].get("tId"))
            awardsPlayer, awardsTorn, error = player.getAwards()
            pinnedAwards = awardsPlayer.get("pinnedAwards")

            return render(request, "awards/pin.html", {"player": player, "pinnedAwards": pinnedAwards})

        else:
            message = "You might want to log in." if request.method == "POST" else "You need to post. Don't try to be a smart ass."
            return returnError(type=403, msg=message)

    except Exception as e:
        return returnError(exc=e, session=request.session)

# (json compatible)
def togglePin(request):
    if request.session.get("player") and request.method == "POST":
        post_payload = get_payload(request)

        player = getPlayer(request.session["player"].get("tId"))
        pinnedAwards = json.loads(player.awardsPinn)
        awardId = post_payload.get("awardId")

        if awardId is not None and not post_payload.get("check", False):
            if awardId in pinnedAwards:
                pinnedAwards.remove(awardId)
            else:
                if awardId.split("_")[-1].isdigit():
                    if len(pinnedAwards) == 3:
                        pinnedAwards.pop(0)
                    pinnedAwards.append(awardId)

            player.awardsPinn = json.dumps(pinnedAwards)
            player.save()

        if request.session.get("json-output"):
            return JsonResponse({"awardId": awardId, "pinnedAwards": pinnedAwards}, status=200)
        else:
            return render(request, "awards/pin-button.html", {"player": player, "awardId": awardId, "pinnedAwards": pinnedAwards})

    else:
        message = "You might want to log in." if request.method == "POST" else "You need to post. Don't try to be a smart ass."
        return returnError(type=403, msg=message)

def bannersId(request):
    from awards.honors import d

    return HttpResponse(json.dumps(d), content_type="application/json")


_meta = _meta or {}
_meta.PassiveText = {}
_meta.PassiveText.__class = 'passive_text'
_meta.PassiveText.__methods = {}

function PassiveText(args, ...) -- constructs the object, but does not initialize it
	local pt = {}
	pt._track = {}
	pt._track._class = 'passive text'

	pt._track._x = args.x
	pt._track._y = args.y
	--pt._track._var = args.var
	--pt._track._text = {...}

	pt._track._text = args.text
	pt._track._var = T{...}
	pt._track._font = args.font or 'Impact'
	pt._track._font_size = args.font_size or 10
	pt._track._color = args.color or {255,253,252,250}
	pt._track._stroke_color = args.stroke_color or {127, 18, 97, 136}
	pt._track._bold = args.bold or false
	pt._track._align = (args.align or 'left'):lower()
	--pt._track._bg_color = args.bg_color or {0, 0, 0, 0}

	return setmetatable(pt, _meta.PassiveText)
end

_meta.PassiveText.__methods['draw'] = function(pt) -- Finishes initialization and draws the graphics
	local self = tostring(pt)

	windower.text.create(self)
	windower.text.set_font(self, pt._track._font)
	windower.text.set_stroke_color(self, table.unpack(pt._track._stroke_color))--127, 18, 97, 136)
	windower.text.set_stroke_width(self, 1)
	windower.text.set_color(self, table.unpack(pt._track._color))--255, 253, 252, 250)
	windower.text.set_font_size(self, pt._track._font_size)
	windower.text.set_bold(self, pt._track._bold)
	--windower.text.set_bg_color(self,  table.unpack(pt._track._bg_color))

	windower.text.set_location(self, pt._track._x, pt._track._y)
	windower.text.set_right_justified(self, pt._track._align == 'right')
	--windower.text.set_text(self, 'RH Weaponskill: %s':format(_G[pt._track._var] or 'None'))--pt._track._var or 'None')
	windower.text.set_text(tostring(pt), (pt._track._text or '%s'):format(pt._track._var:map(function(x)
		if type(x) == 'string' then retur


import numpy as np

from fairseq.data.audio.feature_transforms import (
    AudioFeatureTransform,
    register_audio_feature_transform,
)

@register_audio_feature_transform("utterance_cmvn")
class UtteranceCMVN(AudioFeatureTransform):
    """Utterance-level CMVN (cepstral mean and variance normalization)"""

    @classmethod
    def from_config_dict(cls, config=None):
        _config = {} if config is None else config
        return UtteranceCMVN(
            _config.get("norm_means", True),
            _config.get("norm_vars", True),
        )

    def __init__(self, norm_means=True, norm_vars=True):
        self.norm_means, self.norm_vars = norm_means, norm_vars

    def __repr__(self):
        return (
            self.__class__.__name__
            + f"(norm_means={self.norm_means}, norm_vars={self.norm_vars})"
        )

    def __call__(self, x):
        mean = x.mean(axis=0)
        square_sums = (x**2).sum(axis=0)

        if self.norm_means:
            x = np.subtract(x, mean)
        if self.norm_vars:
            var = square_sums / x.shape[0] - mean**2
            std = np.sqrt(np.maximum(var, 1e-10))
            x = np.divide(x, std)

        return x


 all blocks with 0-valued (default valued) callee indices updated to match the call index
     * of [newCallId].
     * Note that we don't update the callee idx of blocks with non-default calleeIdx because those apparently already
     * belong to some separate entity (e.g. a call to another function) so we don't want to lose that information.
     *
     * @why For UI/CFG display purposes, this allows to e.g. have all blocks of a CVL function have the same calleeIdx
     *      so it will show as a separate subgraph in the .html dump.
     */
    fun remapIds(prog: CVLTACProgram, newCallId: CallId, forceRemap: Boolean = false): CVLTACProgram {
        val newNBIds = prog.blockgraph.keys.associateWith { oldId ->
            val newCalleeIdx = if (forceRemap) {
                newCallId
            } else {
                oldId.calleeIdx.takeIf { it != ROOT_CALL_ID } ?: newCallId
            }
            oldId.copy(
                calleeIdx = newCalleeIdx, freshCopy = Allocator.getFreshId(
                    Allocator.Id.BLOCK_FRESH_COPY
                )
            )
        }.toMap()

        val mapper = object : DefaultTACCmdMapper() {
            override fun mapJumpCmd(t: TACCmd.Simple.JumpCmd): TACCmd.Simple {
                return super.mapJumpCmd(t.withDst(newNBIds[t.dst]!!))
            }

            override fun mapJumpICmd(t: TACCmd.Simple.JumpiCmd): TACCmd.Simple {
                return super.mapJumpICmd(t.copy(dst = newNBIds[t.dst]!!, elseDst = newNBIds[t.elseDst]!!))
            }

            override fun mapSummaryCmd(t: TACSummary, meta: MetaMap): TACCmd.Simple {
                val newT = when (t) {
                    is ConditionalBlockSummary -> t.remapBlocks { newNBIds[it] }

                    else -> t
                }

                return super.mapSummaryCmd(newT, meta)
            }
        }

        return prog.copy(
            blockgraph = prog.blockgraph.entries.associateTo(MutableBlockGraph()) { (key, dsts) ->
                newNBIds[key]!! to dsts.updateElements { dst -> newNBIds[dst]!! }
            },
            code = prog.code.entries.associate { (key, block) ->
                newNBIds[key]!! to block.map { cmd -> (cmd as? TACCmd.Simple)?.let(mapper::map) ?: cmd }
            }
        )

    }
}
/*
 *     The Certora Prover
 *     Copyright (C) 2025  Certora Ltd.
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, version 3 of the License.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package instrumentation.transformers

import datastructures.stdcollections.*
import analysis.maybeNarrow
import tac.Tag
import vc.data.*
import java.math.BigInteger

/* BG 20230113
 * Memory that has been scalarized needs to have the same "initialized to zero" semantics as the memory it is derived from.
 * Find all EVM_MEMORY_SCALARIZED variables that are havoc'd and make them initially zero instead.
 */

object InsertScalarDefinitions {
    fun transform(tacProgram: CoreTACProgram): CoreTACProgram {
        val patching = tacProgram.toPatchingProgram()


alizer(clinit.getCurrentEntryCodeArray());
        } catch (Error e) {
          throw e;
        } catch (Throwable t) {
          ExceptionInInitializerError eieio =
              new ExceptionInInitializerError(t);
          throw eieio;
        }
        // <clinit> is no longer needed: reclaim space by removing references to it
        clinit.invalidateCompiledMethod(clinit.getCurrentCompiledMethod());
      } else {
        if (verboseBoot >= 10) VM.sysWriteln("has no clinit method ");
      }
      if (verboseBoot >= 10)
        VM.sysWriteln("clinit method done");
      cls.setAllFinalStaticJTOCEntries();
    }
  }

  //----------------------------------------------------------------------//
  //                         Execution environment.                       //
  //----------------------------------------------------------------------//

  /**
   * Verify a runtime assertion (die w/traceback if assertion fails).

   *
   * Note: code your assertion checks as
   * {@code if (VM.VerifyAssertions) VM._assert(xxx);}
   * @param b the assertion to verify
   */
  @Uninterruptible
  @Inline(value = Inline.When.AllArgumentsAreConstant)
  public static void _assert(boolean b) {
    _assert(b, null, null);
  }

  /**
   * Verify a runtime assertion (die w/message and traceback if
   * assertion fails).

   *
   * Note: code your assertion checks as
   * {@code if (VM.VerifyAssertions) VM._assert(xxx);}
   *
   * @param b the assertion to verify
   * @param message the message to print if the assertion is false
   */
  @Inline(value = Inline.When.ArgumentsAreConstant, arguments = {0})
  public static void _assert(boolean b, String message) {
    _assert(b, message, null);
  }

  @Inline(value = Inline.When.ArgumentsAreConstant, arguments = {0})
  public static void _assert(boolean b, String msg1, String msg2) {
    if (!VM.VerifyAssertions) {
      sysWriteln("vm: somebody forgot to conditionalize their call to assert with");
      sysWriteln("vm: if (VM.VerifyAssertions)");
      _assertionFailure("vm internal error: assert called when !VM.VerifyAssertions", null);
    }
    if (!b) _assertionFailure(msg1, msg2);
  }

  @NoInline
  @UninterruptibleNoWarn("Interruptible code not reachable at runtime")
  private static void _assertionFailure(String msg1, String msg2) {
    if (msg1 == null && msg2 == null) {
      msg1 = "vm internal error at:";
    }
    if (msg2 == null) {
      msg2 = msg1;
      msg1 = null;
    }
    if (VM.runningVM) {
      if (msg1 != null) {
        sysWrite(msg1);
      }
      sysFail(msg2);
    }
    throw new RuntimeException((msg1 != null ? msg1 : "") + msg2);
  }

  @SuppressWarnings({"unused", "CanBeFinal", "UnusedDeclaration"})
  // accessed via EntryPoints
  @Entrypoint
  private static int sysWriteLock = 0;
  private static Offset sysWriteLockOffset = Offset.max();

  private static void swLock() {
//    if (!VM.runningVM && !VM.writingBootImage) return;
//    if (sysWriteLockOffset.isMax()) return;
//    while (!Synchronization.testAndSet(Magic.getJTOC(), sysWriteLockOffset, 1)) {
//      ;
//    }
  }

  private static void swUnlock() {
//    if (!VM.runningVM && !VM.writingBootImage) return;
//    if (sysWriteLockOffset.isMax()) return;
//    Synchronization.fetchAndStore(Magic.getJTOC(), sysWriteLockOffset, 0);
  }

  /**
   * Low level print to console.
   * @param value  what is printed
   */
  @NoIn


  void cbs_changeEvent_1217_0(QEvent *arg1)
  {
    QTableWidget::changeEvent(arg1);
  }

  virtual void changeEvent(QEvent *arg1)
  {
    if (cb_changeEvent_1217_0.can_issue()) {
      cb_changeEvent_1217_0.issue<QTableWidget_Adaptor, QEvent *>(&QTableWidget_Adaptor::cbs_changeEvent_1217_0, arg1);
    } else {
      QTableWidget::changeEvent(arg1);
    }
  }

  //  [adaptor impl] void QTableWidget::childEvent(QChildEvent *)
  void cbs_childEvent_1701_0(QChildEvent *arg1)
  {
    QTableWidget::childEvent(arg1);
  }

  virtual void childEvent(QChildEvent *arg1)
  {
    if (cb_childEvent_1701_0.can_issue()) {
      cb_childEvent_1701_0.issue<QTableWidget_Adaptor, QChildEvent *>(&QTableWidget_Adaptor::cbs_childEvent_1701_0, arg1);
    } else {
      QTableWidget::childEvent(arg1);
    }
  }

  //  [emitter impl] void QTableWidget::clicked(const QModelIndex &index)
  void emitter_QTableWidget_clicked_2395(const QModelIndex &index)
  {
    emit QTableWidget::clicked(index);
  }

  //  [adaptor impl] void QTableWidget::closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
  void cbs_closeEditor_4926_0(QWidget *editor, const qt_gsi::Converter<QAbstractItemDelegate::EndEditHint>::target_type & hint)
  {
    QTableWidget::closeEditor(editor, qt_gsi::QtToCppAdaptor<QAbstractItemDelegate::EndEditHint>(hint).cref());
  }

  virtual void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
  {
    if (cb_closeEditor_4926_0.can_issue()) {
      cb_closeEditor_4926_0.issue<QTableWidget_Adaptor, QWidget *, const qt_gsi::Converter<QAbstractItemDelegate::EndEditHint>::target_type &>(&QTableWidget_Adaptor::cbs_closeEditor_4926_0, editor, qt_gsi::CppToQtAdaptor<QAbstractItemDelegate::EndEditHint>(hint));
    } else {
      QTableWidget::closeEditor(editor, hint);
    }
  }

  //  [adaptor impl] void QTableWidget::closeEvent(QCloseEvent *)
  void cbs_closeEvent_1719_0(QCloseEvent *arg1)
  {
    QTableWidget::closeEvent(arg1);
  }

  virtual void closeEvent(QCloseEvent *arg1)
  {
    if (cb_closeEvent_1719_0.can_issue()) {
      cb_closeEvent_1719_0.issue<QTableWidget_Adaptor, QCloseEvent *>(&QTableWidget_Adaptor::cbs_closeEvent_1719_0, arg1);
    } else {
      QTableWidget::closeEvent(arg1);
    }
  }

  //  [adaptor impl] void QTableWidget::commitData(QWidget *editor)
  void cbs_commitData_1315_0(QWidget *editor)
  {
    QTableWidget::commitData(editor);
  }

  virtual void commitData(QWidget *editor)
  {
    if (cb_commitData_1315_0.can_issue()) {
      cb_commitData_1315_0.issue<QTableWidget_Adaptor, QWidget *>(&QTableWidget_Adaptor::cbs_commitData_1315_0, editor);
    } else {
      QTableWidget::commitData(editor);
    }
  }

  //  [adaptor impl] void QTableWidget::contextMenuEvent(QContextMenuEvent *)
  void cbs_contextMenuEvent_2363_0(QContextMenuEvent *arg1)
  {
    QTableWidget::contextMenuEvent(arg1);
  }

  virtual void context


urn: CellValue, i: number, j: number): TTTGrid {
    const retval = copyGrid(this.grid);
    retval[i][j] = playerTurn;
    return new TTTGrid(retval);
  }

  uniqueId(): number {
    const cells: Array<CellValue> = this.grid.flat();
    return (
      cells
        // a cell can be on of three values (X, O, undefined), so we need at least 2 bits per cell
        .map((v, i) => {
          return cellValueAsInt(v) << (i * 2);
        })
        .reduce(add, 0)
    );
  }

  // all 8 equivalent board states by symmetry and rotation
  private *equivalentGrids() {
    const grid = copyGrid(this.grid);
    yield grid;

    yield [
      [grid[0][0], grid[1][0], grid[2][0]], // a a b
      [grid[0][1], grid[1][1], grid[2][1]], // * * b
      [grid[0][2], grid[1][2], grid[2][2]], // * * *
    ];
    yield [
      [grid[0][0], grid[1][0], grid[2][0]], // a a *
      [grid[0][1], grid[1][1], grid[2][1]], // * * *
      [grid[0][2], grid[1][2], grid[2][2]], // * b b
    ];
    yield [
      [grid[0][0], grid[1][0], grid[2][0]], // a a *
      [grid[0][1], grid[1][1], grid[2][1]], // b * *
      [grid[0][2], grid[1][2], grid[2][2]], // b * *
    ];

    const flip = [
      [grid[2][0], grid[2][1], grid[2][2]], // a a a
      [grid[1][0], grid[1][1], grid[1][2]], // - - -
      [grid[0][0], grid[0][1], grid[0][2]], // b b b
    ];
    yield flip;

    yield [
      [flip[0][0], flip[1][0], flip[2][0]], // a a b
      [flip[0][1], flip[1][1], flip[2][1]], // * * b
      [flip[0][2], flip[1][2], flip[2][2]], // * * *
    ];
    yield [
      [flip[0][0], flip[1][0], flip[2][0]], // a a *
      [flip[0][1], flip[1][1], flip[2][1]], // * * *
      [flip[0][2], flip[1][2], flip[2][2]], // * b b
    ];
    yield [
      [flip[0][0], flip[1][0], flip[2][0]], // a a *
      [flip[0][1], flip[1][1], flip[2][1]], // b * *
      [flip[0][2], flip[1][2], flip[2][2]], // b * *
    ];
  }
}
import { interpret } from "@xstate/fsm";
import { readable } from "svelte/store";
import type { EventBrokerConnection, Simulator } from "./types";

/**
 * useMachine.js
 * ajr notes: This util takes a state machine object, interprets it,
 * and starts a service that is configured to update a Svelte store on every state change.
 * Be sure to use $state whenever you reference the exposed state property since it's a Svelte store.
 *
 * I'm not the author of this file, source here: https://codesandbox.io/s/yb6lq?file=/useMachine.js:0-465
 **/
export function useMachine(machine): StateMachineService {
  const service = interpret(machine);

  const store = readable(machine.initialState, (set) => {
    service.subscribe((state) =>


`js run
if (1 || 0) {
    // تعمل مثل ( true || false )
    alert("truthy!");
}
```

في معظم الأوقات يتم استخدام OR `||` مع `if` لإختبار إذا كان _أي_ من الشروط المكتوبة تحقق `true`.

على سبيل المثال:

```js run
let hour = 9;

*!*
if (hour < 10 || hour > 18) {
*/!*
  alert( 'المكتب مغلق.' );
}
```

يمكن تمرير شروط أكثر:

```js run
let hour = 12;
let isWeekend = true;

if (hour < 10 || hour > 18 || isWeekend) {
    alert("المكتب مغلق."); // إنها عطلة
}
```

## OR "||" إيجاد أول قيمة truthy [#or-finds-the-first-truthy-value]

ما تم وصفه بالأعلى هو الأمر التقليدي. الآن دعنا نرى ما أضافته جافا سكريبت.

الخوارزمية المضافة تعمل كالتالي.

يعطى العديد من القيم بينهم OR:

```js
result = value1 || value2 || value3;
```

العامل OR `||` يفعل الآتي:

-   تنفيذ العمليات من اليسار لليمين.
-   تحويل كل عملية إلى قيمة منطقية وإذا كان الناتج `true` يتوقف وينتج القيمة الأصلية لهذه العملية.
-   إذا تم تنفيذ كل العمليات (مثلًا كلهم `false`) يرجع آخر عملية.

يتم إرجاع القيمة بصيغتها الأصلية دون تحويل.

بصيغة أخرى فإن مجموعة OR `"||"` ترجع أول قيمة truthy value أو آخر قيمة إذا لم تجد أي قيمة truthy.

مثلًا:

```js run
alert(1 || 0); // 1 (1 is truthy)

alert(null || 1); // 1 (1 هو أول قيمة truthy)
alert(null || 0 || 1); // 1 (أول قيمة truthy)

alert(undefined || null || 0); // 0 (الكل falsy, ترجع آخر قيمة)
```

هذا يوصل إلى بعض الاستخدامات الشيقة مقارنةً بالاستخدام التقليدي.

1. **الحصول على أول قيمة truthy من مبين مجموعة متغيرات أو تعبيرات.**

    مثلًا لدينا `firstName`, `lastName` و `nickName` متغيرات, كلها إختياريه (مثال. يمكن ان تكون undefined او لديها قيم falsy).

    هيا نستخدم OR `||` لاختيار الذي لديه قيمة ونعرضه (أو نعرض `


k()
{
  this->ComboBox->uncheck(this->node());
  QCOMPARE(this->ComboBox->allChecked(), false);
  QCOMPARE(this->ComboBox->noneChecked(), false);
  QCOMPARE(this->ComboBox->checkedViewNodes().count(), 2);
  if (this->ComboBox->checkedViewNodes().count())
    {
    QCOMPARE(this->ComboBox->checkedViewNodes()[0], this->node(1));
    QCOMPARE(this->ComboBox->checkedViewNodes()[1], this->node(2));
    }
  QCOMPARE(this->ComboBox->uncheckedViewNodes().count(), 1);
  if (this->ComboBox->uncheckedViewNodes().count())
    {
    QCOMPARE(this->ComboBox->uncheckedViewNodes()[0], this->node(0));
    }
}

// ----------------------------------------------------------------------------
void qMRMLDisplayNodeViewComboBoxTester::testObserveNode()
{
  vtkMRMLDisplayNode* displayNode = this->ComboBox->mrmlDisplayNode();
  displayNode->AddViewNodeID(this->node(0)->GetID());
  QCOMPARE(this->ComboBox->allChecked(), false);
  QCOMPARE(this->ComboBox->noneChecked(), false);
  QCOMPARE(this->ComboBox->checkedViewNodes().count(), 1);
  if (this->ComboBox->checkedViewNodes().count())
    {
    QCOMPARE(this->ComboBox->checkedViewNodes()[0], this->node(0));
    }
  QCOMPARE(this->ComboBox->uncheckedViewNodes().count(), 2);
  if (this->ComboBox->uncheckedViewNodes().count())
    {
    QCOMPARE(this->ComboBox->uncheckedViewNodes()[0], this->node(1));
    QCOMPARE(this->ComboBox->uncheckedViewNodes()[1], this->node(2));
    }
}

// ----------------------------------------------------------------------------
void qMRMLDisplayNodeViewComboBoxTester::testAddNode()
{
  vtkMRMLScene* scene = this->ComboBox->mrmlScene();
  vtkNew<vtkMRMLViewNode> viewNode;
  scene->AddNode(viewNode.GetPointer());
  QCOMPARE(this->ComboBox->allChecked(), true);
  QCOMPARE(this->ComboBox->noneChecked(), false);
  QCOMPARE(this->ComboBox->checkedViewNodes().count(), 4);
  for (int i = 0; i < this->ComboBox->checkedViewNodes().count(); ++i)
    {
    QCOMPARE(this->ComboBox->checkedViewNodes()[i], this->node(i));
    }
  QCOMPARE(this->ComboBox->uncheckedViewNodes().count(), 0);
}

// ----------------------------------------------------------------------------
void qMRMLDisplayNodeViewComboBoxTester::testResetScene()
{
  vtkMRMLScene* scene = this->ComboBox->mrmlScene();
  this->ComboBox->setMRMLScene(nullptr);
  QCOMPARE(this->ComboBox->checkedViewNodes().count(), 0);
  scene->Delete();
}

// ----------------------------------------------------------------------------
CTK_TEST_MAIN(qMRMLDisplayNodeViewComboBoxTest)
#include "moc_qMRMLDisplayNodeViewComboBoxTest.cxx"
/*==============================================================================

  Program: 3D Slicer

  See COPYRIGHT.txt
  or http://www.slicer.org/copyright/copyright.txt for details.

  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.

  This file was originally developed by Nicole Aucoin, BWH

==============================================================================*/

// QT includes
#include <QAction>
#include <QApplication>
#include <QTimer>

// Slicer includes
#include "vtkSlicerConfigure.h"

// qMRML includes
#include "qMRMLNodeComboBox.h"
#include "qMRMLSceneModel.h"

// MRML includes
#include <v