  VE::Q1,  VE::Q2,  VE::Q3,  VE::Q4,  VE::Q5,  VE::Q6,  VE::Q7,
    VE::Q8,  VE::Q9,  VE::Q10, VE::Q11, VE::Q12, VE::Q13, VE::Q14, VE::Q15,
    VE::Q16, VE::Q17, VE::Q18, VE::Q19, VE::Q20, VE::Q21, VE::Q22, VE::Q23,
    VE::Q24, VE::Q25, VE::Q26, VE::Q27, VE::Q28, VE::Q29, VE::Q30, VE::Q31};

static const MCPhysReg VM512Regs[8] = {VE::VMP0, VE::VMP1, VE::VMP2, VE::VMP3,
                                       VE::VMP4, VE::VMP5, VE::VMP6, VE::VMP7};

static const MCPhysReg MISCRegs[31] = {
    VE::USRCC,      VE::PSW,        VE::SAR,        VE::NoRegister,
    VE::NoRegister, VE::NoRegister, VE::NoRegister, VE::PMMR,
    VE::PMCR0,      VE::PMCR1,      VE::PMCR2,      VE::PMCR3,
    VE::NoRegister, VE::NoRegister, VE::NoRegister, VE::NoRegister,
    VE::PMC0,       VE::PMC1,       VE::PMC2,       VE::PMC3,
    VE::PMC4,       VE::PMC5,       VE::PMC6,       VE::PMC7,
    VE::PMC8,       VE::PMC9,       VE::PMC10,      VE::PMC11,
    VE::PMC12,      VE::PMC13,      VE::PMC14};

namespace {

/// VEOperand - Instances of this class represent a parsed VE machine
/// instruction.
class VEOperand : public MCParsedAsmOperand {
private:
  enum KindTy {
    k_Token,
    k_Register,
    k_Immediate,
    // SX-Aurora ASX form is disp(index, base).
    k_MemoryRegRegImm,  // base=reg, index=reg, disp=imm
    k_MemoryRegImmImm,  // base=reg, index=imm, disp=imm
    k_MemoryZeroRegImm, // base=0, index=reg, disp=imm
    k_MemoryZeroImmImm, // base=0, index=imm, disp=imm
    // SX-Aurora AS form is disp(base).
    k_MemoryRegImm,  // base=reg, disp=imm
    k_MemoryZeroImm, // base=0, disp=imm
    // Other special cases for Aurora VE
    k_CCOp,   // condition code
    k_RDOp,   // rounding mode
    k_MImmOp, // Special immediate value of sequential bit stream of 0 or 1.
  } Kind;

  SMLoc StartLoc, EndLoc;

  struct Token {
    const char *Data;
    unsigned Length;
  };

  struct RegOp {
    unsigned RegNum;
  };

  struct ImmOp {
    const MCExpr *Val;
  };

  struct MemOp {
    unsigned Base;
    unsigned IndexReg;
    const MCExpr *Index;
    const MCExpr *Offset;
  };

  struct CCOp {
    unsigned CCVal;
  };

  struct RDOp {
    unsigned RDVal;
  };

  struct MImmOp {
    const MCExpr *Val;
    bool M0Flag;
  };

  union {
    struct Token Tok;
    struct RegOp Reg;
    struct ImmOp Imm;
    struct MemOp Mem;
    struct CCOp CC;
    struct RDOp RD;
    struct MImmOp MImm;
  };

public:
  VEOperand(KindTy K) : Kind(K) {}

  bool isToken() const override { return Kind == k_Token; }
  bool isReg() const override { return Kind == k_Register; }
  bool isImm() const override { return Kind == k_Immediate; }
  bool isMem() const override {
    return isMEMrri() || isMEMrii() || isMEMzri() || isMEMzii() || isMEMri() ||
           isMEMzi();
  }
  bo


: scanner.Position{
						Filename: "signal_comment.dbc",
						Line:     1,
						Column:   1,
					},
					ObjectType: ObjectTypeSignal,
					MessageID:  1234,
					SignalName: "SignalName",
					Comment:    "signal comment",
				},
			},
		},

		{
			name: "int_attribute_definition.dbc",
			text: `BA_DEF_ "AttributeName" INT 5 10;`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "int_attribute_definition.dbc",
						Line:     1,
						Column:   1,
					},
					Name:       "AttributeName",
					Type:       AttributeValueTypeInt,
					MinimumInt: 5,
					MaximumInt: 10,
				},
			},
		},

		{
			name: "int_attribute_definition_no_min_or_max.dbc",
			text: `BA_DEF_ "AttributeName" INT;`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "int_attribute_definition_no_min_or_max.dbc",
						Line:     1,
						Column:   1,
					},
					Name: "AttributeName",
					Type: AttributeValueTypeInt,
				},
			},
		},

		{
			name: "float_attribute_definition.dbc",
			text: `BA_DEF_ "AttributeName" FLOAT 0.5 1.5;`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "float_attribute_definition.dbc",
						Line:     1,
						Column:   1,
					},
					Name:         "AttributeName",
					Type:         AttributeValueTypeFloat,
					MinimumFloat: 0.5,
					MaximumFloat: 1.5,
				},
			},
		},

		{
			name: "float_attribute_definition_no_min_or_max.dbc",
			text: `BA_DEF_ "AttributeName" FLOAT;`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "float_attribute_definition_no_min_or_max.dbc",
						Line:     1,
						Column:   1,
					},
					Name: "AttributeName",
					Type: AttributeValueTypeFloat,
				},
			},
		},

		{
			name: "string_attribute.dbc",
			text: `BA_DEF_ "AttributeName" STRING;`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "string_attribute.dbc",
						Line:     1,
						Column:   1,
					},
					Name: "AttributeName",
					Type: AttributeValueTypeString,
				},
			},
		},

		{
			name: "enum_attribute.dbc",
			text: `BA_DEF_ "AttributeName" ENUM "value1","value2";`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "enum_attribute.dbc",
						Line:     1,
						Column:   1,
					},
					Name:       "AttributeName",
					Type:       AttributeValueTypeEnum,
					EnumValues: []string{"value1", "value2"},
				},
			},
		},

		{
			name: "enum_attribute_for_messages.dbc",
			text: `BA_DEF_ BO_  "VFrameFormat" ENUM  "StandardCAN","ExtendedCAN","reserved","J1939PG";`,
			defs: []Def{
				&AttributeDef{
					Pos: scanner.Position{
						Filename: "enum_attribute_for_messages.dbc",
						Line:     1,
						Column:   1,
					},
					Name:       "VFrameFormat",
					ObjectType: ObjectTypeMessage,
					Type:       AttributeValueTypeEnum,
					EnumValues: []string{"StandardCAN", "ExtendedCAN", "r


import os
import pandas as pd
import re

FINAL_COMMAND = "@stop"

# Switch to the current .py path
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)
print(f"📁 腳本執行路徑：{script_dir}")

# Find Excel file
excel_file = next((f for f in os.listdir('.') if f.endswith('.xlsx')), None)
if not excel_file:
    print("❌ 找不到 Excel 檔案 (.xlsx)")
    exit()
print(f"📄 已找到 Excel 檔案：{excel_file}")

# Load Excel
xls = pd.ExcelFile(excel_file)
sheet_names = xls.sheet_names

# Load character mapping table, increase robustness
character_map = {}
character_portrait_info = {} # New map: char_id -> has_portrait (bool)
if 'Character' in sheet_names:
    try:
        character_df = xls.parse('Character')
        # Ensure columns exist, remove rows containing NaN, and convert to string to prevent issues
        if '中文顯示' in character_df.columns and 'id' in character_df.columns:
            character_df = character_df.dropna(subset=['中文顯示', 'id'])
            character_df['中文顯示'] = character_df['中文顯示'].astype(str).str.strip()
            character_df['id'] = character_df['id'].astype(str).str.strip()

            # Handle '是否有立繪' column for portrait display logic
            has_portrait_col = '是否有立繪'
            if has_portrait_col in character_df.columns:
                # Convert to string, fill NaN with 'T' (default to has portrait), and normalize
                character_df[has_portrait_col] = character_df[has_portrait_col].fillna('T').astype(str).str.strip().str.upper()
            else:
                # If column doesn't exist, assume all characters have portraits for backward compatibility
                character_df[has_portrait_col] = 'T'

            character_map = dict(zip(character_df['中文顯示'], character_df['id']))
            character_portrait_info = dict(zip(character_df['id'], character_df[has_portrait_col] != 'F'))

            if not character_map:
                 print("⚠ 'Character' 分頁已載入，但未成功建立任何角色對應（可能為空或格式問題）。")
        else:
            print("⚠ 'Character' sheet is missing '中文顯示' or 'id' columns.")
    except Exception as e:
        print(f"⚠ Cannot parse 'Character' sheet or create character mapping: {e}")
else:
    print("⚠ 找不到 'Character' 分頁，將無法對應角色 ID。")

# Prepare output folder
output_folder = os.path.splitext(excel_file)[0]
os.makedirs(output_folder, exist_ok=True)

all_generated_lines = {} # Store initially processed command lines for each sheet

for sheet in sheet_names:
    if sheet in ['Character', 'Stage']:
        continue

    print(f"\n🔧 處理分頁：{sheet}")
    try:
        # Use fillna('') to convert all NaN values to empty strings, avoiding str(NaN) becoming "nan" later
        df = xls.parse(sheet).fillna('')
    except Exception as e:
        print(f"⚠ 無法解析 {sheet}：{e}")
        continue

    # Check for necessary columns, '對話內容' (Dialogue Content) is core
    if '對話內容' not in df.columns:
        print(f"⚠ 分頁 {sheet} 缺少核心的 '對話內容' 欄位，跳過此分頁。")
        continue
    # '角色' (Character) and '選項' (Option) columns are optional; if they don't exist, .get('', '') will handle them

    lines = []
    prev_char_id = None
    currently_in_choice_block = False # True if processing a sequence of choices
    processed_any_choice_in_sheet = False # True if any choice was made in this sheet

    for index, row in df.iterrows():
        # .get(column, '') returns '' if the column doesn't exist or its value is NaN (which has already been converted to '' by fillna(''))
        # str() ensures it's a string, .strip() removes leading/trailing spaces
        speaker_raw = row.get('角色', '') # fillna('') has handled NaN
        speaker = str(speaker_raw).strip()

        text = str(row.get('對話內容', '')).strip()

        option_goto = ''
        original_option_cell_value = '' # Used to determine if the '選項' (Option) column was originally empty or just spaces
        if '選項' in df.columns: # Check if the '選項' (Option) column exists
            original_option_cell_value = str(row.get('選項', '')) # Already a string due to fillna
            option_goto = original_option_cell_value.strip()

        # 1. Process options: '對話內容'(text) as option text, '選項'(option_goto) as jump target
        if text and option_goto:
            if not currently_in_choice_block: # First choice in a new block
                if prev_char_id: # If a character was speaking before this choice block
                    if character_portrait_info.get(prev_char_id, True): # Check if character has a portrait


 acaso nicotina, ya ni cita vecino, anima cocina, pedazo gallina, cedazo terso nos retoza de canilla goza, de pánico camina, ónice vaticina, ya ni tocino saca, a terracota luminosa pera, sacra nómina y ánimo de mortecina, ya ni giros elimina, ya ni poeta, ya ni vida"))
    println(isPalindrome("¿Qué os ha parecido el reto?"))
}

private fun isPalindrome(text: String): Boolean {

    val normalizedText = Normalizer.normalize(text.lowercase(), Normalizer.Form.NFD)
        .replace("[^\\p{ASCII}]".toRegex(), "")
        .replace("[^a-z0-9]".toRegex(), "")
        return normalizedText == normalizedText.reversed()
    }

package com.mouredev.weeklychallenge2022

/*
 * Reto #36
 * LOS ANILLOS DE PODER
 * Fecha publicación enunciado: 06/09/22
 * Fecha publicación resolución: 14/09/22
 * Dificultad: MEDIA
 *
 * Enunciado: ¡La Tierra Media está en guerra! En ella lucharán razas leales a Sauron
 * contra otras bondadosas que no quieren que el mal reine sobre sus tierras.
 * Cada raza tiene asociado un "valor" entre 1 y 5:
 * - Razas bondadosas: Pelosos (1), Sureños buenos (2), Enanos (3), Númenóreanos (4), Elfos (5)
 * - Razas malvadas: Sureños malos (2), Orcos (2), Goblins (2), Huargos (3), Trolls (5)
 * Crea un programa que calcule el resultado de la batalla entre los 2 tipos de ejércitos:
 * - El resultado puede ser que gane el bien, el mal, o exista un empate. Dependiendo de la
 *   suma del valor del ejército y el número de integrantes.
 * - Cada ejército puede estar compuesto por un número de integrantes variable de cada raza.
 * - Tienes total libertad para modelar los datos del ejercicio.
 * Ej: 1 Peloso pierde contra 1 Orco, 2 Pelosos empatan contra 1 Orco, 3 Pelosos ganan a 1 Orco.
 *
 * Información adicional:
 * - Usa el canal de nuestro Discord (https://mouredev.com/discord) "🔁reto-semanal"
 *   para preguntas, dudas o prestar ayuda a la comunidad.
 * - Tienes toda la información sobre los retos semanales en
 *   https://retosdeprogramacion.com/semanales2022.
 *
 */

fun main() {

    battleForTheMiddleEarth(
        listOf(Pair(KindArmy.ELF, 1)),
        listOf(Pair(EvilArmy.TROLL, 1)))

    battleForTheMiddleEarth(
        listOf(Pair(KindArmy.ELF, 1), Pair(KindArmy.HARFOOT, 1)),
        listOf(Pair(EvilArmy.TROLL, 1)))

    battleForTheMiddleEarth(
        listOf(Pair(KindArmy.ELF, 1), Pair(KindArmy.HARFOOT, 1)),
        listOf(Pair(EvilArmy.TROLL, 1), Pair(EvilArmy.ORC, 1)))

    battleForTheMiddleEarth(
        listOf(Pair(KindArmy.ELF, 56), Pair(KindArmy.HARFOOT, 80), Pair(KindArmy.DWARF, 5)),
        listOf(Pair(EvilArmy.TROLL, 17), Pair(EvilArmy.ORC, 51), Pair(EvilArmy.WARG, 10), Pair(EvilArmy.SOUTHERNER, 2)))
}

enum class K


, [fp, #-440]
	str	lr, [fp, #-872]
	str	r6, [fp, #-876]
	b	.L185
.L227:
	add	r0, r7, r2
	add	lr, r3, #19712
	sxtab	r0, r0, ip
	sub	r5, fp, #44
	mov	ip, lr
	str	r2, [lr, #16]
	add	r0, r5, r0, lsl #3
.L213:
	ldr	r0, [r0, #-804]
	mov	r5, ip
	add	r2, r2, #1
	add	r3, r3, #68
	cmp	r2, #32
	str	r0, [ip, #24]
	mov	r0, ip
	ldr	r6, [fp, #-864]
	str	r10, [r5, #36]
	str	r9, [r5, #40]
	str	r6, [r5, #32]
	ldr	lr, [fp, #-868]
	str	lr, [ip, #44]
	mov	lr, ip
	ldr	r5, [r4, #60]
	str	r5, [r0, #48]
	mov	r0, ip
	ldr	r6, [r4, #64]
	mov	r5, ip
	str	r6, [lr, #52]
	str	r8, [ip, #56]
	ldr	r6, [fp, #-872]
	str	r6, [r0, #60]
	ldr	r6, [fp, #-876]
	strb	r1, [r5, #12]
	str	r6, [r5, #64]
	strb	r1, [ip, #13]
	strb	r1, [ip, #14]
	beq	.L184
	ldrb	r0, [r4, #11]	@ zero_extendqisi2
	ldrb	ip, [r4, #12]	@ zero_extendqisi2
.L185:
	sxtb	r0, r0
	cmp	r0, r2
	bhi	.L227
	sxtab	r0, r7, ip
	add	lr, r3, #19712
	sub	r5, fp, #44
	mov	ip, lr
	add	r0, r5, r0, lsl #3
	str	r1, [lr, #16]
	b	.L213
.L184:
	ldr	r3, [fp, #-56]
	cmp	r3, #20
	movge	r3, #20
	strb	r3, [r4, #13]
	ldr	lr, [fp, #-48]
	cmp	lr, #0
	beq	.L190
	ldr	r3, [fp, #-880]
	sub	r0, fp, #856
	mov	r6, #0
	mov	r5, #1
	ldr	r2, [r3, #1808]
	add	lr, r2, lr
	mov	ip, r2, asl #2
	mov	r3, r2, asl #4
	rsb	r1, ip, r3
	add	r1, r1, #22016
	add	r1, r1, #24
	add	r1, r4, r1
.L189:
	rsb	r3, ip, r3
	add	r2, r2, #1
	ldr	ip, [r0, #556]
	add	r3, r4, r3
	add	r3, r3, #22016
	cmp	r2, lr
	add	r0, r0, #12
	ad


clustercontrol.utility.settings.job.xml.SchemaInfo schmaversion) {
		/*スキーマのバージョンチェック*/
		int res = queueConv.checkSchemaVersion(schmaversion.getSchemaType(),
				schmaversion.getSchemaVersion(),
				schmaversion.getSchemaRevision());
		com.clustercontrol.utility.settings.job.xml.SchemaInfo sci = queueConv.getSchemaVersion();
		return BaseAction.checkSchemaVersionResult(this.getLogger(), res, sci.getSchemaType(), sci.getSchemaVersion(), sci.getSchemaRevision());
	}

	/**
	 * 情報をマネージャからエクスポートします。
	 *
	 * @param 出力するXMLファイル
	 * @return 終了コード
	 */
	@ExportMethod
	public int exportJobQueue(String fileName) {
		log.debug("Start Export JobQueue : " + fileName);

		int ret = SettingConstants.SUCCESS;

		//マネージャから同時実行制御キューのビューを取得する。
		JobQueueSettingViewInfoResponse viewInfo;
		try {
			//マネージャからキューの一覧(ビュー)を取得
			viewInfo = JobRestClientWrapper.getWrapper(UtilityManagerUtil.getCurrentManagerName()).getJobQueueListSearch(new GetJobQueueListSearchRequest());
		} catch (Exception e1) {
			log.error(Messages.getString("SettingTools.ExportFailed") + " : " + HinemosMessage.replace(e1.getMessage()));
			ret = SettingConstants.ERROR_INPROCESS;
			log.debug("End Export JobQueue : " + fileName +"(Error)");
			return ret;
		}

		com.clustercontrol.utility.settings.job.xml.JobQueueList queueXML
		= new com.clustercontrol.utility.settings.job.xml.JobQueueList();

		//共通情報のセット
		queueXML.setCommon(CommonConv.versionJobDto2Xml(Config.getVersion()));

		//スキーマ情報のセット
		queueXML.setSchemaInfo(queueConv.getSchemaVersion());

		if(viewInfo != null){
			//ジョブ情報のセット(ジョブツリーからXML用のリストに変換)
			queueXML.setJobQueueInfo(queueConv.view2queueXML(viewInfo));
		}

		try (FileOutputStream output = new FileOutputStream(fileName)) {
			//マーシャリング
			queueXML.marshal(new OutputStreamWriter(output , "UTF-8"));
		} catch (Exception e) {
			log.warn(Messages.getString("SettingTools.ExportFailed"), e);
			ret = SettingConstants.ERROR_INPROCESS;
		}

		// 処理の終了
		if (ret == SettingConstants.SUCCESS) {
			log.info(Messages.getString("SettingTools.ExportCompleted"));
		}else{
			log.error(Messages.getString("SettingTools.EndWithErrorCode") );
		}
		log.debug("End Export JobQueue");
		return ret;
	}

	@ClearMethod
	public int clearJobQueue() {
		log.debug("Start Clear JobQueue");

		int ret = SettingConstants.SUCCESS;

		//マネージャから同時実行制御キューのビューを取得する。
		JobQueueSettingViewInfoResponse viewInfo;
		JobRestClientWrapper wrapper = JobRestClientWrapper.getWrapper(UtilityManagerUtil.getCurrentManagerName());
		try {
			//マネージャからキューの一覧(ビュー)を取得
			viewInfo = wrapper.getJobQueueListSearch(new GetJobQueueListSearchRequest());
		} catch (Exception e) {
			log.error(Messages.getString("SettingTools.ExportFailed") + " : " + HinemosMessage.replace(e.getMessage()));


 port),
				ClusterLocalURI:  fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=%s", username, password, clusterLocalHost, port, dbName, dbName),

				GlobalVpnHost: globalVPNHost,
				GlobalVpnAddr: fmt.Sprintf("%s:%s", globalVPNHost, port),
				GlobalVpnURI:  fmt.Sprintf("mongodb://%s:%s@%s:%s/%s?authSource=%s", username, password, globalVPNHost, port, dbName, dbName),
			}

			m, err := out.ToMap()
			if err != nil {
				return err
			}

			secret.StringData = m
		}

		return nil
	}); err != nil {
		return check.Failed(err)
	}

	return check.Completed()
}

func (r *Reconciler) createStatefulSet(req *rApi.Request[*mongodbMsvcv1.StandaloneService]) stepResult.Result {
	ctx, obj := req.Context(), req.Object
	check := rApi.NewRunningCheck(createStatefulSet, req)

	pvcName := obj.Name

	sts := &appsv1.StatefulSet{ObjectMeta: metav1.ObjectMeta{Name: obj.Name, Namespace: obj.Namespace}}
	if _, err := controllerutil.CreateOrUpdate(ctx, r.Client, sts, func() error {
		sts.SetOwnerReferences([]metav1.OwnerReference{fn.AsOwner(obj, true)})

		selectorLabels := fn.MapMerge(
			fn.MapFilterWithPrefix(obj.GetLabels(), "kloudlite.io/"),
			map[string]string{kloudliteMsvcComponent: "statefulset"},
		)

		for k, v := range selectorLabels {
			fn.MapSet(&sts.Labels, k, v)
		}

		sts.Spec.Replicas = fn.New(int32(1))

		spec := appsv1.StatefulSetSpec{
			Replicas: fn.New(int32(1)),
			Selector: &metav1.LabelSelector{
				MatchLabels: selectorLabels,
			},
			ServiceName: obj.Name,
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: selectorLabels,
				},
				Spec: corev1.PodSpec{
					NodeSelector: obj.Spec.NodeSelector,
					Tolerations:  obj.Spec.Tolerations,
					Volumes: []corev1.Volume{
						{
							Name: pvcName,
							VolumeSource: corev1.VolumeSource{
								PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
									ClaimName: obj.Name,
									ReadOnly:  false,
								},
							},
						},
					},
					Containers: []corev1.Container{
						{
							Name:  "mongodb",
							Image: "mongo:latest",
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      pvcName,
									MountPath: "/data/db",
								},
							},
							Env: []corev1.EnvVar{
								{
									Name: "MONGO_INITDB_ROOT_USERNAME",
									ValueFrom: &corev1.EnvVarSource{
										SecretKeyRef: &corev1.SecretKeySelector{
											LocalObjectReference: corev1.LocalObjectReference{
												Name: obj.Output.CredentialsRef.Name,
											},
											Key: "ROOT_USERNAME",
										},
									},
								},
								{
									Name: "MONGO_INITDB_ROOT_PASSWORD",
									ValueFrom: &corev1.EnvVarSource{
										SecretKeyRef: &corev1.SecretKeySelector{
											LocalObjectReference: corev1.LocalObjectReference{
												Name: obj.Output.CredentialsRef.Name,
											},
											Key: "ROOT_PASSWORD",
										},
									},


hape[0], band))

            # reconstruction loss
            MSE_loss = torch.mean(torch.acos(torch.sum(x * output, dim=1)/
                        (torch.norm(output, dim=1, p=2)*torch.norm(x, dim=1, p=2))))
            # sparsity and minimum volume regularization
            MSE_loss += criterionSparse(abu) + criterionVolumn(net.decoder[0].weight)

            optimizer.zero_grad()
            MSE_loss.backward()
            nn.utils.clip_grad_norm_(net.parameters(), max_norm=10, norm_type=1)
            optimizer.step()
            net.decoder.apply(apply_nonegative)

        if epoch % 1 == 0:
            print('Epoch: {:d} | Train Unmix Loss: {:.5f} | RE Loss: {:.5f} | Sparsity Loss: {:.5f} | Minvol: {:.5f}'
                .format(epoch, MSE_loss, loss_func(output, x), criterionSparse(abu), criterionVolumn(net.decoder[0].weight)))
            net.eval()
            for k, testdata in enumerate(test_loaders):
                x, y = testdata
                x = x.cuda()
                y = y.cuda()

                abu_est, output = net(x, y)

            abu_est = torch.reshape(abu_est.squeeze(-1).permute(2,1,0), (num_classes,row,col)).permute(0,2,1).cpu().data.numpy()
            edm_result = torch.reshape(net.decoder[0].weight, (band,num_classes)).cpu().data.numpy()
            print('RMSE: {:.5f} | SAD: {:.5f}'.format(compute_rmse(abu_est[position,:,:],label), compute_sad(M_true, edm_result[:,position])))
            print('**********************************')

        scheduler.step()
    time_end = time.time()
    # model evaluation
    net.eval()
    print(net.spectral_se)
    for i, testdata in enumerate(test_loaders):
        x, y = testdata
        x = x.cuda()
        y = y.cuda()

        abu, output = net(x, y)

    # compute metric
    abu_est = torch.reshape(abu.squeeze(-1).permute(2,1,0), (num_classes,row,col)).permute(0,2,1).cpu().data.numpy()
    edm_result = torch.reshape(net.decoder[0].weight, (band,num_classes)).cpu().data.numpy()
    abu_est = abu_est[position,:,:]
    edm_result = edm_result[:,position]

    RMSE = compute_rmse(label, abu_est)
    SAD = compute_sad(M_true, edm_result)
    print('**********************************')
    print('RMSE: {:.5f} | SAD: {:.5f}'.format(RMSE, SAD))
    print('**********************************')
    print('total computational cost:', time_end-time_start)
    print('**********************************')

    # abundance map
    for i in range(abu_est.shape[0]):
        plt.subplot(2, num_classes, i+1)
        plt.imshow(abu_est[i,:,:])
        plt.subplot(2, num_classes, i+1+num_classes)
        plt.imshow(label[i,:,:])
    plt.show()

    # print hyperparameter setting and save result
    print_args(vars(args))
    save_path = str(args.dataset) + '_result.mat'
    sio.savemat(save_path, {'abu_est':abu_est.T, 'M_est':edm_result})


wPanel.selectAllButtonMnemonic").charAt(0)); //$NON-NLS-1$
		pbSelectAll.addActionListener(this);
		gc.gridy = 3;
		gc.gridx = 1;
		gb.setConstraints(pbSelectAll, gc);
		centerpanel.add(pbSelectAll);

		// Add information button
		pbViewInfo = new UIButton(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.linkingInfoButton")); //$NON-NLS-1$
		pbViewInfo.setMnemonic(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.linkingInfoButtonMnemonic").charAt(0)); //$NON-NLS-1$
		pbViewInfo.addActionListener(this);
		gc.gridy = 3;
		gc.gridx = 2;
		gc.weightx=1;
		gc.weighty=1;
		gb.setConstraints(pbViewInfo, gc);
		centerpanel.add(pbViewInfo);

		// DeletedViews button
		int count = 0;
		try {
			count = ProjectCompendium.APP.getModel().getNodeService().getDeletedViewCount(ProjectCompendium.APP.getModel().getSession(), node.getId());
		}catch(Exception ex){
            log.warn("Exception...", ex);
        }

		pbDeletedViews = new UIButton(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.viewDeletedButton")+" ("+count+")"); //$NON-NLS-1$ //$NON-NLS-2$
		pbDeletedViews.setMnemonic(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.viewDeletedButtonMnemonic").charAt(0)); //$NON-NLS-1$ //$NON-NLS-2$
		pbDeletedViews.addActionListener(this);
		gc.gridy = 5;
		gc.gridx = 0;
		gc.gridwidth=3;
		gb.setConstraints(pbDeletedViews, gc);
		centerpanel.add(pbDeletedViews);

		// other initializations
		updateListView(node);

		add(centerpanel, BorderLayout.CENTER);
		add(createButtonPanel(), BorderLayout.SOUTH);
	}

	/**
	 * Create and return the button panel.
	 */
	private UIButtonPanel createButtonPanel() {

		UIButtonPanel oButtonPanel = new UIButtonPanel();

		pbCancel = new UIButton(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.closeButton")); //$NON-NLS-1$
		pbCancel.setMnemonic(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.closeButtonMnemonic").charAt(0));
		pbCancel.addActionListener(this);
		oButtonPanel.addButton(pbCancel);

		pbHelp = new UIButton(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.helpButton")); //$NON-NLS-1$
		pbHelp.setMnemonic(LanguageProperties.getString(LanguageProperties.PANELS_BUNDLE, "UINodeViewPanel.helpButtonMnemonic").charAt(0));
		ProjectCompendium.APP.mainHB.enableHelpOnButton(pbHelp, "node.views-view", ProjectCompendium.APP.mainHS); //$NON-NLS-1$
		oButtonPanel.addHelpButton(pbHelp);

		return oButtonPanel;
	}

	/**
	 * Set the default button for the parent dialog to be this panel's default button.
	 */
	public void setDefaultButton() {
		//oParentDialog.getRootPane().setDefaultButton(pbCancel);
	}

	/**
	 * Updates the list view with the view vector.
	 * This method used in displaying the containing views for the given node.
	 * @param node com


8.632-.202a2.21 2.21 0 011.546-2.347 2.29 2.29 0 01.697-.108zM5.476 9.02c-.588 0-1.105.368-1.287.915a1.32 1.32 0 00.869 1.668c.136.043.277.065.419.065.588 0 1.105-.368 1.287-.915a1.29 1.29 0 00-.081-1.01 1.338 1.338 0 00-.788-.658 1.377 1.377 0 00-.42-.065zm13.045 0c-.142 0-.282.021-.419.065a1.32 1.32 0 00-.869 1.668c.182.547.7.915 1.287.915a1.4 1.4 0 00.42-.065c.344-.11.623-.343.787-.659.165-.315.193-.673.082-1.009a1.348 1.348 0 00-1.288-.915zM12 10.474c-1.095 0-1.986.871-1.986 1.942 0 1.07.89 1.941 1.986 1.941 1.094 0 1.985-.87 1.985-1.94 0-1.072-.89-1.943-1.985-1.943zm-2.706 4.831.73.519-.39.526c.709.757.801 1.925.16 2.787a2.28 2.28 0 01-1.827.91c-.478 0-.937-.147-1.325-.422a2.177 2.177 0 01-.499-3.082 2.28 2.28 0 012.76-.71zm5.41 0 .392.528a2.285 2.285 0 012.76.71 2.178 2.178 0 01-.499 3.082 2.275 2.275 0 01-1.325.421 2.28 2.28 0 01-1.827-.91 2.172 2.172 0 01.16-2.785l-.39-.527zm-6.734 1.21a1.37 1.37 0 00-1.097.547c-.44.59-.304 1.42.3 1.849a1.37 1.37 0 001.891-.293c.44-.59.305-1.42-.3-1.85a1.364 1.364 0 00-.794-.252zm8.059 0c-.287 0-.561.088-.795.254a1.307 1.307 0 00-.299 1.849 1.371 1.371 0 001.891.293 1.307 1.307 0 00.3-1.85 1.37 1.37 0 00-1.097-.545Z"/></svg>';
  static const String smashdotgg =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="currentColor" d="M18.01 4.32c-.622.044-1.096.236-1.41.574a1.438 1.438 0 00-.332.546c-.138.366-.134.288-.142 2.57-.008 2.096-.002 2.328.066 2.628.142.612.524 1.03 1.124 1.228.342.114.58.14 1.192.128.586-.01.686-.028.962-.17a1.35 1.35 0 00.496-.494l.074-.14-.004.6c-.006.686-.01.7-.176.784l-.088.046H16.5v2h1.986c1.976 0 2.386-.012 2.714-.072.98-.178 1.508-.71 1.62-1.628.012-.11.02-1.616.02-4.394V4.3h-2.76v.93l-.048-.114c-.17-.412-.48-.664-.932-.756-.226-.046-.736-.066-1.09-.04zm1.844


ARN)
}

func (r *ROSARoleConfigReconciler) reconcileOIDC(scope *scope.RosaRoleConfigScope) error {
	oidcID := ""
	switch scope.RosaRoleConfig.Spec.OidcProviderType {
	case expinfrav1.Managed:
		// Create oidcConfig if not exist
		if scope.RosaRoleConfig.Status.OIDCID == "" {
			oidcID, createErr := oidcconfig.CreateOIDCConfig(r.Runtime, true, "", "")
			if createErr != nil {
				return fmt.Errorf("failed to Create OIDC config: %w", createErr)
			}
			scope.RosaRoleConfig.Status.OIDCID = oidcID
		}
		oidcID = scope.RosaRoleConfig.Status.OIDCID
	case expinfrav1.Unmanaged:
		oidcID = scope.RosaRoleConfig.Spec.OperatorRoleConfig.OIDCID
	}

	// Check if oidc Config exist
	oidcConfig, err := r.Runtime.OCMClient.GetOidcConfig(oidcID)
	if err != nil || oidcConfig == nil {
		return fmt.Errorf("failed to get OIDC config: %w", err)
	}

	scope.RosaRoleConfig.Status.OIDCID = oidcConfig.ID()

	// check oidc providers
	providers, err := r.Runtime.AWSClient.ListOidcProviders("", oidcConfig)
	if err != nil {
		return err
	}

	// set oidc Provider Arn
	for _, provider := range providers {
		if strings.Contains(provider.Arn, oidcID) {
			scope.RosaRoleConfig.Status.OIDCProviderARN = provider.Arn
			return nil
		}
	}

	// create oidc provider if not exist.
	if scope.RosaRoleConfig.Status.OIDCProviderARN == "" {
		if err := oidcprovider.CreateOIDCProvider(r.Runtime, oidcID, "", true); err != nil {
			return err
		}
		providerArn, err := r.Runtime.AWSClient.GetOpenIDConnectProviderByOidcEndpointUrl(oidcConfig.IssuerUrl())
		if err != nil {
			return err
		}
		scope.RosaRoleConfig.Status.OIDCProviderARN = providerArn
	}

	return nil
}

func (r *ROSARoleConfigReconciler) reconcileAccountRoles(scope *scope.RosaRoleConfigScope) error {
	accountRoles, err := r.Runtime.AWSClient.ListAccountRoles(scope.RosaRoleConfig.Spec.AccountRoleConfig.Version)
	if err != nil {
		// ListAccountRoles return error if roles does not exist. return for any other error
		if !strings.Contains(err.Error(), "no account roles found") {
			return err
		}
	}

	accountRolesRef := expinfrav1.AccountRolesRef{}
	for _, role := range accountRoles {
		if role.RoleName == fmt.Sprintf("%s%s", scope.RosaRoleConfig.Spec.AccountRoleConfig.Prefix, expinfrav1.HCPROSAInstallerRole) {
			accountRolesRef.InstallerRoleARN = role.RoleARN
		} else if role.RoleName == fmt.Sprintf("%s%s", scope.RosaRoleConfig.Spec.AccountRoleConfig.Prefix, expinfrav1.HCPROSASupportRole) {
			accountRolesRef.SupportRoleARN = role.RoleARN
		} else if role.RoleName == fmt.Sprintf("%s%s", scope.RosaRoleConfig.Spec.AccountRoleConfig.Prefix, expinfrav1.HCPROSAWorkerRole) {
			accountRolesRef.WorkerRoleARN = role.RoleARN
		}
	}

	// Set account role ref if ready
	if r.accountRolesReady(accountRolesRef) {
		scope.RosaRoleConfig.Status.AccountRolesRef = accountRolesRef
		return nil
	}

	policies, err := r.Runtime.OCMClient.GetPolicies("AccountRole")
	if err != nil {
		return err
	}

	return accountroles.CreateHCPRoles(r.Runtime, scope.Rosa


制器，必须是实现[IControllerView]接口的UI组件
     */
    fun removeControllerWidget(controllerView: IControllerView?)

    /**
     * 根据组件tag标识寻找组件实例
     * @param target 根据组件tag标识寻找组件实例,target为组件的唯一标识
     * @return 组件实例化的对象
     */
    fun findControlWidgetByTag(target: String?): IControllerView?

    /**
     * 移除所有控制器
     */
    fun removeAllControllerWidget()

    //======================================下列方法为不常用方法========================================
    /**
     * 设置视频标题
     * @param videoTitle 视频标题
     */
    fun setTitle(videoTitle: String?)

    /**
     * 返回是否播放\试看完成
     * @return true:播放完成 false:未播放完成
     */
    val isCompletion: Boolean

    /**
     * 返回seekBar控制器是否正在被显示状态中
     * @return seekBar控制器是否正在被显示状态中
     */
    val isControllerShowing: Boolean

    /**
     * 返回控制器是否处于竖屏状态
     * @return true:处于竖屏状态 false:非竖屏状态
     */
    val isOrientationPortrait: Boolean

    /**
     * 返回控制器是否处于横屏状态
     * @return true:处于横屏状态 false:非横屏状态
     */
    val isOrientationLandscape: Boolean

    /**
     * 返回控制器当前正处于什么场景，各UI组件初始化后会收到回调：onPlayerScene
     * @return 播放器\控制器场景 0：常规状态(包括竖屏、横屏)，1：activity小窗口，2：全局悬浮窗窗口，3：列表，4：Android8.0的画中画 其它：自定义场景
     */
    /**
     * 更新播放器场景
     * @param playerScene 更新播放器场景，自定义场景可调用此方法设置，设置后会同步通知到所有实现IControllerView接口的UI组件中的onPlayerScene方法
     * 播放器\控制器场景 0：常规状态(包括竖屏、横屏)，1：activity小窗口，2：全局悬浮窗窗口，3：列表，4：Android8.0的画中画 其它：自定义场景
     */
    var playerScene: Int

    /**
     * 返回试看模式下的试看时长
     * @return 返回试看模式下的试看时长，单位：毫秒
     */
    /**
     * 设置试看|收费模式下的虚拟总时长
     * @return 设置试看|收费模式下的虚拟总时长，单位：毫秒
     */
    var preViewTotalDuration: Long

    /**
     * 设置控制器为列表模式
     * @param listPlayerScene 设置控制器为列表模式 true：列表模式 false：非列表模式
     */
    fun setListPlayerMode(listPlayerScene: Boolean)

    /**
     * 进入画中画模式
     */
    fun enterPipWindow()

    /**
     * 退出画中画模式
     */
    fun quitPipWindow()


flex-direction: row;
  align-items: center;
}

.header__nav a:hover,
.header__nav a.active {
  background: #c72a63;
}

.header__nav a svg {
  margin-left: 10px;
}

.header__nav a.main_action {
  background-color: #551a8b;
}

.languageSwitcher {
  flex: 0 0 auto;
}

.languageSwitcher a {
  height: 24px;
  padding: 3px 8px;
}

.languageSwitcher a:hover {
  border-bottom: 5px solid;
}

@media (max-width: 1000px) {
  .header .container {
    flex-direction: column;
  }
  .header__nav {
    flex-grow: 0;
  }
  .header .container {
    display: flex;
    align-items: center;
    height: 120px;
  }
}

@media (max-width: 800px) {
  .header .container {
    display: block;
    height: auto;
  }
  .header__nav {
    display: block;
    padding-bottom: 10px;
  }
  .header__nav a {
    display: block;
    padding: 3px 8px;
  }
  .languageSwitcher a {
    display: block;
  }
}
.root {
	-fx-accent: #1a6ee4;
	-fx-focus-color: -fx-accent;
	-fx-base: #111;
	-fx-primary-color: derive(-fx-base, 12%);
	-fx-secondary-color: derive(-fx-base, 20%);
	-fx-hover-color: derive(-fx-base, 30%);
	-fx-dark-color: derive(-fx-base, 6%);
	-fx-diagram-color: -fx-hover-color;
	-fx-control-inner-background: -fx-primary-color;
	-fx-control-inner-background-alt: -fx-control-inner-background;
	-fx-faint-focus-color: transparent;
	-fx-font-size: 13.0pt;
	/*-fx-selection-bar-non-focused: derive(-fx-accent,30%);*/
	-fx-selection-bar-non-focused: derive(-fx-base, 90.0%);
	-fx-background: -fx-primary-color;
}

.menu-bar {
	-fx-background-color: transparent;
	-fx-padding: 0.0 0.0 10.0 0.0;
}

.dock-area-indicator {
	-fx-fill: -fx-selection-bar;
	-fx-opacity: 0.5;
	-fx-stroke: rgba(50.0, 50.0, 100.0, 0.4);
	-fx-stroke-width: 6.0;
	-fx-stroke-type: inside;
	-fx-stroke-dash-array: 8.0 4.0;
	-fx-stroke-line-cap: butt;
}

.dock-top {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-right {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-bottom {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-left {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-center {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-top-root {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-right-root {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-bottom-root {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);
}

.dock-left-root {
	-fx-graphic: url(../styles/flat-dark/icons/pin.png);


model.primalColumnSolution(), sol2, numberColumns * sizeof(double));
  memcpy(model.statusArray(), status2, numberColumns);
  delete[] sol2;
  delete[] status2;
  columnLower = model.columnLower();
  columnUpper = model.columnUpper();
  solution = model.primalColumnSolution();
  for (jNon = 0; jNon < numberNonLinearColumns; jNon++) {
    iColumn = listNonLinearColumn[jNon];
    columnLower[iColumn] = CoinMax(solution[iColumn],
      trueLower[jNon]);
    columnUpper[iColumn] = CoinMin(solution[iColumn],
      trueUpper[jNon]);
  }
  model.primal(1);
  for (jNon = 0; jNon < numberNonLinearColumns; jNon++) {
    iColumn = listNonLinearColumn[jNon];
    columnLower[iColumn] = trueLower[jNon];
    columnUpper[iColumn] = trueUpper[jNon];
  }
  delete[] saveSolution;
  delete[] safeSolution;
  delete[] saveRowSolution;
  for (iPass = 0; iPass < 3; iPass++)
    delete[] last[iPass];
  delete[] trust;
  delete[] trueUpper;
  delete[] trueLower;
  delete[] changeRegion;
  delete[] startArtificial;
  delete[] rowArtificial;
  delete[] elementArtificial;
  delete[] objectiveArtificial;
  delete[] listNonLinearColumn;
  delete[] whichRow;
  delete[] markNonlinear;
  return CoinCopyOfArray(solution, coinModel.numberColumns());
}
/* Solve linearized quadratic objective branch and bound.
   Return cutoff and OA cut
*/
double
OsiSolverLink::linearizedBAB(CglStored *cut)
{
  double bestObjectiveValue = COIN_DBL_MAX;
  if (quadraticModel_) {
    ClpSimplex *qp = new ClpSimplex(*quadraticModel_);
    // bounds
    int numberColumns = qp->numberColumns();
    double *lower = qp->columnLower();
    double *upper = qp->columnUpper();
    const double *lower2 = getColLower();
    const double *upper2 = getColUpper();
    for (int i = 0; i < numberColumns; i++) {
      lower[i] = CoinMax(lower[i], lower2[i]);
      upper[i] = CoinMin(upper[i], upper2[i]);
    }
    qp->nonlinearSLP(20, 1.0e-5);
    qp->primal();
    OsiSolverLinearizedQuadratic solver2(qp);
    const double *solution = NULL;
    // Reduce printout
    solver2.setHintParam(OsiDoReducePrint, true, OsiHintTry);
    CbcModel model2(solver2);
    // Now do requested saves and modifications
    CbcModel *cbcModel = &model2;
    OsiSolverInterface *osiModel = model2.solver();
    OsiClpSolverInterface *osiclpModel = dynamic_cast< OsiClpSolverInterface * >(osiModel);
    ClpSimplex *clpModel = osiclpModel->getModelPtr();

    // Set changed values

    CglProbing probing;
    probing.setMaxProbe(10);
    probing.setMaxLook(10);
    probing.setMaxElements(200);
    probing.setMaxProbeRoot(50);
    probing.setMaxLookRoot(10);
    probing.setRowCuts(3);
    probing.setUsingObjective(true);
    cbcModel->addCutGenerator(&probing, -1, "Probing", true, false, false, -100, -1, -1);
    cbcModel->cutGenerator(0)->setTiming(true);

    CglGomory gomory;
    gomory.setLimitAtRoot(512);
    cbcModel->addCutGenerator(&gomory, -98, "Gomory", true, false, false, -100, -1, -1);
    cbcMode


(http)
    application.internal.fixed_loop[1]()

    application.internal.event_loop[1]({
        class='tcp',
        type='connect',
        host='pudim.com.br',
        connection=1
    })
    application.internal.event_loop[1]({
        class='tcp',
        type='data',
        value='some error',
        connection=1
    })

    assert(response.ok == false)
    assert(response.status == nil)
    assert(response.body == nil)
    assert(response.error == 'some error')
end

function test_http_dns_error()
    http_reset().http.dns_state = 2

    local response = {}
    local http = {
        speed='',
        method='POST',
        body_content='',
        url='http://pudim.com',
        set = function(key, value)
            response[key] = value
        end,
        promise = function() end,
        resolve = function() end
    }

    http_handler(http)
    application.internal.fixed_loop[1]()

    application.internal.event_loop[1]({
        class='tcp',
        type='connect',
        host='pudim.com',
        error='cannot resolve pudim.c


rrier(o):
 *   performs the pre-teardown barrier for the external
 *   (resp. internal) refcount
 *
 */
#define _os_object_xrefcnt_inc_orig(o) \
		_os_atomic_refcnt_add_orig2o(o, os_obj_xref_cnt, 1)

#define _os_object_xrefcnt_dec(o) \
		_os_atomic_refcnt_sub2o(o, os_obj_xref_cnt, 1)

#define _os_object_xrefcnt_dispose_barrier(o) \
		_os_atomic_refcnt_dispose_barrier2o(o, os_obj_xref_cnt)

#define _os_object_refcnt_add_orig(o, n) \
		_os_atomic_refcnt_add_orig2o(o, os_obj_ref_cnt, n)

#define _os_object_refcnt_sub(o, n) \
		_os_atomic_refcnt_sub2o(o, os_obj_ref_cnt, n)

#define _os_object_refcnt_dispose_barrier(o) \
		_os_atomic_refcnt_dispose_barrier2o(o, os_obj_ref_cnt)

void _os_object_atfork_child(void);
void _os_object_atfork_parent(void);
void _os_object_atfork_prepare(void);
void _os_object_init(void);
unsigned long _os_object_retain_count(_os_object_t obj);
bool _os_object_retain_weak(_os_object_t obj);
bool _os_object_allows_weak_reference(_os_object_t obj);
void _os_object_dispose(_os_object_t obj);
void _os_object_xref_dispose(_os_object_t obj);

#endif // __DISPATCH_OBJECT_INTERNAL__


 { }
    T *operator->() { return ptr; }
    T *operator&() { return ptr; }
    operator T&() { return *ptr; }
    template<typename U> bool operator ==(U other) { return *ptr == other; }
    template<typename U> bool operator !=(U other) { return *ptr != other; }
  private:
    T *ptr;
};

#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag)
  #define Py_OptimizeFlag 0
#endif
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#if PY_MAJOR_VERSION < 3
  #define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
  #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
          PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
  #define __Pyx_DefaultClassType PyClass_Type
#else
  #define __Pyx_BUILTIN_MODULE_NAME "builtins"
#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2
  #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
          PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#else
  #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\
          PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#endif
  #define __Pyx_DefaultClassType PyType_Type
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
  #define Py_TPFLAGS_CHECKTYPES 0
#endif
#ifndef Py_TPFLAGS_HAVE_INDEX
  #define Py_TPFLAGS_HAVE_INDEX 0
#endif
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
  #define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_FINALIZE
  #define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#ifndef METH_STACKLESS
  #define METH_STACKLESS 0
#endif
#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL)
  #ifndef METH_FASTCALL
     #define METH_FASTCALL 0x80
  #endif
  typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs);
  typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args,
                                                          Py_ssize_t nargs, PyObject *kwnames);
#else
  #define __Pyx_PyCFunctionFast _PyCFunctionFast
  #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords
#endif
#if CYTHON_FAST_PYCCALL
#define __Pyx_PyFastCFunction_Check(func)\
    ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC


ic_functions()
        {
            // Вообще говоря, надо эти операции добавлять только если пользовательские не определены
            if (BaseFullName != "PABCSystem.NewSet`1") // SSM 19/11/24 - для типа встроенных множеств где эти операции переопределены
            {
                conform_basic_function(StringConstants.assign_name, 0);
                conform_basic_function(StringConstants.eq_name, 1);
                conform_basic_function(StringConstants.noteq_name, 2);
            }
            temp_names = null;
        }

        public virtual List<function_node> all_methods
        {
            get
            {
                return null;
            }
        }

        public virtual List<type_node> all_field_types
        {
            get
            {
                return null;
            }
        }

        public override generic_instance_type_node base_generic_instance
        {
            get
            {
                return this;
            }
        }

        public override bool depended_from_indefinite
        {
            get
            {
                if (_instance_params == null)
                {
                    return false;
                }
                foreach (type_node tn in _instance_params)
                {
                    if (tn.depended_from_indefinite)
                    {
                        return true;
                    }
                }
                return false;
            }
        }

    }

    //Класс, характеризующий одну псевдоинстанцию generic-типа
    public class compiled_generic_instance_type_node : generic_instance_type_node, SemanticTree.ICompiledGenericTypeInstance
    {
        public compiled_type_node compiled_original_generic
        {
            get
            {
                return _original_generic as compiled_type_node;
            }
        }

        public override string BaseFullName
        {
            get
            {
                return compiled_original_generic.BaseFullName;
            }
        }

        public compiled_generic_instance_type_node(compiled_type_node generic_definition,
            List<type_node> param_types,
            type_node base_type, string name,
            SemanticTree.type_access_level type_access_level,
            common_namespace_node comprehensive_namespace,
            location loc)
            :
            base(generic_definition, param_types, base_type, name, type_access_level, comprehensive_namespace,
            loc)
        {
        }

        private List<function_node> _all_methods = null;

        public override List<function_node> all_methods
        {
            get
            {
                if (_all_methods != null) return _all_methods;
                _all_methods = new List<function_node>();
                System.Reflection.MemberInfo[] orig_members = compiled_original_generic.compiled_type.GetMembers();
                foreach (System.Reflection.MemberInfo mi in orig_members)
                {
                    if (mi.MemberType == System.Reflection.MemberTypes.Method)
                    {
                        compiled_function_node cmeth = compiled_function_node.get_compiled_method((System.Reflection.MethodInfo)mi);
                        _all_methods.Add(ConvertMember(cmeth) as function_node);
                    }
                }
                return _all_methods;
            }
        }

        private List<type_node> _all_field_types = null;
        public override List<type_node> all_field_types
        {
            get
            {
                if (_all_field_types != null) return _all_field_types;
                System.Reflection.FieldInfo[] fields = compiled_original_generic.compiled_type.GetFields();
                _all_field_types = new List<type_node>();
                foreach (System.Reflection.FieldInfo


Mantel des Zandalaribesessenen",
  [19850] = "Tribut an Uther",
  [19851] = "Tribut an Grom",
  [19858] = "Ehrenmünze der Zandalari",
  [19862] = "Aegis des Blutgottes",
  [19868] = "_",
  [19879] = "_",
  [19916] = "Monster - Mace, Standard Serpent Green",
  [19917] = "Monster - Wand, Horde A01 Green",
  [19924] = "Monster - Dagger, Fang Hook Curve Dark",
  [19926] = "_",
  [19932] = "_",
  [19945] = "Forors Augenklappe",
  [19946] = "Tigules Harpune",
  [19948] = "Heldenabzeichen der Zandalari",
  [19949] = "Heldenmedaillon der Zandalari",
  [19950] = "Heldenamulett der Zandalari",
  [19966] = "_",
  [19970] = "Arkanitangelrute",
  [19980] = "Monster - Dagger, Ornate Spikey Base Red",
  [19981] = "Monster - Sword2H, Claymore B01/Broadsword A03 Black Sharpened",
  [19983] = "Monster - Wand, Horde Demon Skull Red",
  [19985] = "_",
  [19986] = "Pirate\'s Eye Patch",
  [19987] = "Monster - Dagger, Vulture Black",
  [19988] = "Monster - Mace2H, Horde C01 Steel (Green)",
  [19989] = "Tome of Devouring Shadows",
  [20003] = "Devilsaur Claws",
  [20004] = "Mächtiges Trollblutelixier",
  [20005] = "Devilsaur Claws",
  [20007] = "Magierblutelixier",
  [20010] = "Höllschrei, Held der Horde",
  [20011] = "Rezept: Magierblutelixier",
  [20014] = "Rezept: Mächtiges Trollblutelixier",
  [20020] = "Bundle of Goods",
  [20024] = "Putrid Bile Duct",
  [20026] = "Rotting Flesh",
  [20033] = "Robe des besessenen Zandalari",
  [20034] = "Robe des der Zandalari-Illusionisten",
  [20068] = "Umhang der Todeswache",
  [20076] = "Zandalarisiegel des Mojo",
  [20077] = "Zandalarisiegel der Macht",
  [20078] = "Zandalarisiegel der inneren Ruhe",
  [20084] = "Hunting Net",
  [20086] = "Zerbrochenes Düsterstahlwurfmesser",
  [20090] = "Gefütterter Gurt des Highlanders",
  [20093] = "Gefütterte Schienbeinschützer des Highlanders",
  [20118] = "Highlander\'s Mail Girdle",
  [20119] = "Highlander\'s Mail Girdle",
  [20120] = "Highlander\'s Mail Girdle",
  [20121] = "Highlander\'s Mail Greaves",
  [20122] = "Highlander\'s Mail Greaves",
  [20123] = "Highlander\'s Mail Greaves",
  [20126] = "Panzergurt des Highlanders",
  [20129] = "Panzerschienbeinschützer des Highlanders",
  [20133] = "_",
  [20135] = "_",
  [20136] = "_",
  [20137] = "_",
  [20138] = "_",
  [20139] = "_",
  [20140] = "_",
  [20141] = "_",
  [20142] = "_",
  [20143] = "_",
  [20144] = "_",
  [2014


PerGasCap = (
      if (gasPriceCaps.maxBaseFeePerGasCap != null) {
        gasPriceCaps.maxBaseFeePerGasCap!! + maxPriorityFeePerGasCap
      } else {
        gasPriceCaps.maxFeePerGasCap
      }
      )
      .coerceAtMost(amplifiedMaxFeePerGasCap)
      .run { if (this <= 0uL) amplifiedMaxFeePerGasCap else this }

    return GasPriceCaps(
      maxPriorityFeePerGasCap = maxPriorityFeePerGasCap,
      maxFeePerGasCap = maxFeePerGasCap,
      maxFeePerBlobGasCap = 0uL,
    )
  }

  override fun getGasPriceCaps(targetL2BlockNumber: Long): SafeFuture<GasPriceCaps?> {
    return gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber)
      .thenApply { it?.run(this::coerceGasPriceCaps) }
      .thenPeek {
        this.lastGasPriceCap.set(it)
      }
  }

  override fun getGasPriceCapsWithCoefficient(targetL2BlockNumber: Long): SafeFuture<GasPriceCaps?> {
    return gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber)
      .thenApply { it?.run(this::coerceGasPriceCaps) }
      .thenPeek {
        this.lastGasPriceCap.set(it)
      }
  }
}
package net.consensys.linea.ethereum.gaspricing.staticcap

import linea.domain.FeeHistory
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever

class VariableFeesCalculatorTest {

  private val config = VariableFeesCalculator.Config(
    margin = 1.1,
    bytesPerDataSubmission = 200_000u,
    blobSubmissionExpectedExecutionGas = 120_000u,
    expectedBlobGas = 131_000u,
  )

  @Test
  fun test_calculateFees() {
    val mockFeeHistory = mock<FeeHistory>()
    whenever(mockFeeHistory.blocksRange()).thenReturn(1uL..100uL)
    val mockBaseFeeCalculator = mock<AverageWeightedFeesCalculator>()
    val averageWeightedBaseFees = 1.0
    whenever(mockBaseFeeCalculator.calculateFees(eq(mockFeeHistory))).thenReturn(averageWeightedBaseFees)
    val mockPriorityFeeCalculator = mock<AverageWeightedFeesCalculator>()
    val averageWeightedPriorityFees = 2.0
    whenever(mockPriorityFeeCalculator.calculateFees(eq(mockFeeHistory))).thenReturn(averageWeightedPriorityFees)
    val mockBlobBaseFeeCalculator = mock<AverageWeightedFeesCalculator>()
    val averageWeightedBlobBaseFees = 5.0
    whenever(mockBlobBaseFeeCalculator.calculateFees(eq(mockFeeHistory))).thenReturn(averageWeightedBlobBaseFees)

    // ((1+2)*120000 + 5*131000)*1.1/200000 = 5.5825
    val expectedVariableFees = (((1.0 + 2.0) * 120000.0 + 5.0 * 131000.0) * 1.1) / 200000.0

    val feesCalculator = VariableFeesCalculator(
      config = config,
      averageWeightedBaseFeesCalculator = mockBaseFeeCalculator,
      averageWeightedPriorityFeesCalculator = mockPriorityFeeCalculator,
      averageWeightedBlobBaseFeesCalculator = mockBlobBaseFeeCalculator,
    )
    assertThat(feesCalculator.calculateFees(mockFeeHistory))
      .isEqualTo(expectedVariableFees)
  }
}
package net.consensys.linea.ethereum.gaspricing.staticcap

import com.github.michaelbull.result.Result
import com.github.michaelbull.result.onFailur


         HabitMetaData(emptySet(), DeadlineFrequency.DAILY, 1, 0, LocalDate.now().toString())
        }

        return habitMeta
    }

    fun setAlarms(databaseHelper: DatabaseHelper, context: Context) {
        if (!deadlineNotification) {
            return
        }

        val pendingTasks = databaseHelper.getDDLsByType(DeadlineType.TASK)
            .filter {
                if (it.isCompleted || it.isArchived) {
                    return@filter false
                }

                val endTime = parseDateTime(it.endTime)
                endTime != null && endTime.isAfter(LocalDateTime.now())
            }

        pendingTasks.forEach { ddlItem ->
            DeadlineAlarmScheduler.scheduleExactAlarm(context, ddlItem)
        }
    }

    fun decideHideFromRecent(context: Context, activity: Activity) {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val myTaskId = activity.taskId
        activityManager.appTasks
            .firstOrNull { it.taskInfo?.id == myTaskId }
            ?.setExcludeFromRecents(hideFromRecent)
    }

    fun Long.toDateTimeString(): String {
        val zonedDateTime = Instant.ofEpochMilli(this).atZone(ZoneId.systemDefault())
        return zonedDateTime.toLocalDateTime().toString()
    }

    fun generateWikiForSpecificDevice(): String {
        val manufacturer = Build.MANUFACTURER.lowercase(Locale.getDefault())
        val brand = Build.BRAND.lowercase(Locale.getDefault())

        val baseWikiUrl = "https://github.com/AritxOnly/Deadliner/wiki/%E9%80%9A%E7%9F%A5%E6%8E%A8%E9%80%81%E5%8A%9F%E8%83%BD%E7%94%A8%E6%88%B7%E6%96%87%E6%A1%A3"

        Log.d("WikiGenerate", manufacturer)

        return baseWikiUrl
    }

    fun generateHabitNote(context: Context, frequency: Int?, total: Int?, type: DeadlineFrequency): String {
        val typeString = when (type) {
            DeadlineFrequency.DAILY -> context.getString(R.string.frequency_daily)
            DeadlineFrequency.WEEKLY -> context.getString(R.string.frequency_weekly)
            DeadlineFrequency.MONTHLY -> context.getString(R.string.frequency_monthly)
            else -> context.getString(R.string.frequency_daily)
        }

        val frequencyValue = frequency ?: 1

        val totalString = if (total == null) {
            context.getString(R.string.habit_total_unlimited)
        } else {
            context.getString(R.string.habit_total_count, total)
        }

        return context.getString(R.string.habit_checkin, typeString, frequencyValue, totalString)
    }

    fun canHabitBeDone(item: DDLItem, metaData: HabitMetaData): Boolean {
        val endTime = parseDateTime(item.endTime)
        if (endTime == null) {
            return true
        }

        val remainingTime = Duration.between(LocalDateTime.now(), endTime).toDays()
        val remainingTasks = metaData.total - item.habitTotalCount
        return when (metaData.frequencyType) {
            DeadlineFrequency.TOTAL ->
                true

            DeadlineFrequency.DAILY ->
                (remainingTime * metaData.frequency >= remainingTasks)

            DeadlineFrequency.WEEKLY ->
                ((remainingTime / 7) * metaData.frequency >= remainingTasks)

            DeadlineFrequency.MONTHLY ->
                ((remainingTime / 30) * metaData.frequency >= remainingTasks)
        }
    }

    fun showRetroactiveDatePicker(fragmentManager: FragmentManager, onDatePicked: (Long) -> Unit) {
        // 限制不选未来日期
        val constraints = CalendarConstraints.Builder()
            .setValidator(DateValidatorPointBackward.now())
            .build()

        val picker = MaterialDatePicker.Builder.


	[1623304263] = 'prop_v_5_bclock',
	[-290464389] = 'prop_v_bmike_01',
	[-206866686] = 'prop_v_cam_01',
	[1427153555] = 'prop_v_door_44',
	[-1137425659] = 'prop_v_hook_s',
	[1298935678] = 'prop_v_m_phone_01',
	[1142221529] = 'prop_v_m_phone_o1s',
	[1654893215] = 'prop_v_parachute',
	[1652730148] = 'prop_valet_01',
	[-2086179979] = 'prop_valet_02',
	[1902790395] = 'prop_valet_03',
	[1710403596] = 'prop_valet_04',
	[36810380] = 'prop_vault_door_scene',
	[-1485006268] = 'prop_vault_shutter',
	[1209027853] = 'prop_vb_34_tencrt_lighting',
	[330240957] = 'prop_vcr_01',
	[-2098052468] = 'prop_veg_corn_01',
	[-1007446468] = 'prop_veg_crop_01',
	[649223100] = 'prop_veg_crop_02',
	[-634939447] = 'prop_veg_crop_03_cab',
	[-2084538847] = 'prop_veg_crop_03_pump',
	[-1163697832] = 'prop_veg_crop_04_leaf',
	[-383623015] = 'prop_veg_crop_04',
	[-83295126] = 'prop_veg_crop_05',
	[955777091] = 'prop_veg_crop_06',
	[2007502834] = 'prop_veg_crop_orange',
	[-1194920181] = 'prop_veg_crop_tr_01',
	[-2040982992] = 'prop_veg_crop_tr_02',
	[-62459927] = 'prop_veg_grass_01_a',
	[-1634847635] = 'prop_veg_grass_01_b',
	[-1933078304] = 'prop_veg_grass_01_c',
	[52002182] = 'prop_veg_grass_01_d',
	[-1180346286] = 'prop_veg_grass_02_a',
	[-534597020] = 'prop_vehicle_hook',
	[463039275] = 'prop_ven_market_stool',
	[-1184096195] = 'prop_ven_market_table1',
	[615030415] = 'prop_ven_shop_1_counter',
	[690372739] = 'prop_vend_coffe_01',
	[684389648] = 'prop_vend_condom_01',
	[73774428] = 'prop_vend_fags_01',
	[-1317235795] = 'prop_vend_fridge01',
	[-1034034125] = 'prop_vend_snak_01_tu',
	[-654402915] = 'prop_vend_snak_01',
	[992069095] = 'prop_vend_soda_01',
	[1114264700] = 'prop_vend_soda_02',
	[1099892058] = 'prop_vend_water_01',
	[-770680652] = 'prop_venice_board_01',
	[-459014693] = 'prop_venice_board_02',
	[-1317169265] = 'prop_venice_board_03',
	[797649894] = 'prop_venice_counter_01',
	[504531189] = 'prop_venice_counter_02',
	[-772083517] = 'prop_venice


" ==> i ] ~o:[ "o" ==> o ] ~t:[ "t" ==> t ];
    end_circuit ();
    to_verilog (find_circuit "example") |> Rope.to_string |> print_string
val gen : unit -> unit = <fun>
# gen ()
module example
(
  input i,
  output o,
  inout t
);

  inner _4
  (
    .i(i),
    .o(o),
    .t(t)
  );
endmodule
- : unit = ()
```

Circuits must have unique names.

```ocaml
# gen ()
Exception: Hardcaml__Structural.Circuit_already_exists("example").
```

## API functions

A small set of functions are natively supported by `Structural` - `of_bit_string`, `mux`,
`concat_msb` and `select`.

In addition, assignment is performed with `<--`.

```ocaml
# let gen () =
    start_circuit "example2";
    let i = mk_input "i" 3 in
    let o = mk_output "o" 2 in
    o <--
        concat_msb
            [ of_bit_string "1"
            ; mux
                (select i ~high:0 ~low:0)
                [ select i ~high:1 ~low:1
                ; select i ~high:2 ~low:2 ]
            ];
    end_circuit ();
    to_verilog (find_circuit "example2") |> Rope.to_string |> print_string
val gen : unit -> unit = <fun>
# gen ()
module example2
(
  input [2:0] i,
  output [1:0] o
);

  wire _3;
  wire _4;
  wire _5;
  wire _6;
  wire _7;
  wire [1:0] _8;
  assign _3 = i[2:2];
  assign _4 = i[1:1];
  assign _5 = i[0:0];
  assign _6 =
    _5 == 0 ? _4 :
    _3;
  assign _7 = 1'b1;
  assign _8 = { _7, _6 };
  assign o = _8;
endmodule
- : unit = ()
```
### Using `Lib`

The complete `Comb` API be provided by instantiating the `Structural.Lib` functor (note
this must be done within a 'started' circuit). This uses hardcaml to create
implementations for each operation and allows them to be instantiated within `Structural`
circuits.

```ocaml
# let circuit =
    create_circuit "example3" (fun () ->
      let open Lib () in
      let a = mk_input "a" 3 in
      let b = mk_input "b" 3 in
      let addsub = mk_input "addsub" 1 in
      let c = mk_output "c" 3 in
      c <-- mux2 addsub (a +: b) (a -: b));;
val circuit : circuit = <abstr>
# to_verilog circuit |> Rope.to_string |> print_string
module example3
(
  input [2:0] a,
  input [2:0] b,
  input addsub,
  output [2:0] c
);

  wire _1;
  wire _2;
  wire [2:0] _7;
  wire [2:0] _9;
  wire [2:0] _11;
  assign _1 = 1'b1;
  assign _2 = 1'b0;
  assign _11 =
    addsub == 0 ? _7 :
    _9;
  assign c = _11;
  hardcaml_lib_sub_3 _8
  (
    .i0(a),
    .i1(b),
    .o(_7)
  );
  hardcaml_lib_add_3 _10
  (
    .i0(a),
    .i1(b),
    .o(_9)
  );
endmodule
- : unit = ()
```

We have used a new function here called `create_


y) diag.Diagnostics {
	config := meta.(*Config)

	networkingClient, err := config.NetworkingV2Client(ctx, GetRegion(d, config))
	if err != nil {
		return diag.Errorf("Error creating OpenStack network client: %s", err)
	}

	bgpvpnID, id, err := parsePairedIDs(d.Id(), "openstack_bgpvpn_port_associate_v2")
	if err != nil {
		return diag.FromErr(err)
	}

	res, err := bgpvpns.GetPortAssociation(ctx, networkingClient, bgpvpnID, id).Extract()
	if err != nil {
		return diag.FromErr(CheckDeleted(d, err, "Error getting openstack_bgpvpn_port_associate_v2"))
	}

	log.Printf("[DEBUG] Retrieved openstack_bgpvpn_port_associate_v2 %s: %#v", id, res)

	d.Set("bgpvpn_id", bgpvpnID)
	d.Set("port_id", res.PortID)
	d.Set("advertise_fixed_ips", res.AdvertiseFixedIPs)

	if res.ProjectID != "" {
		// the project_id is returned only on POST/PUT responses
		d.Set("project_id", res.ProjectID)
	}

	d.Set("routes", flattenBGPVPNPortAssociateRoutesV2(res.Routes))

	d.Set("region", GetRegion(d, config))

	return nil
}

func resourceBGPVPNPortAssociateV2Update(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
	config := meta.(*Config)

	networkingClient, err := config.NetworkingV2Client(ctx, GetRegion(d, config))
	if err != nil {
		return diag.Errorf("Error creating OpenStack network client: %s", err)
	}

	bgpvpnID, id, err := parsePairedIDs(d.Id(), "openstack_bgpvpn_port_associate_v2")
	if err != nil {
		return diag.FromErr(err)
	}

	opts := bgpvpns.UpdatePortAssociationOpts{}

	if d.HasChange("advertise_fixed_ips") {
		v := d.Get("advertise_fixed_ips").(bool)
		opts.AdvertiseFixedIPs = &v
	}

	if d.HasChange("routes") {
		routes := expandBGPVPNPortAssociateRoutesUpdateV2(d)
		opts.Routes = &routes
	}

	log.Printf("[DEBUG] openstack_bgpvpn_port_associate_v2 %s update options: %#v", id, opts)

	res, err := bgpvpns.UpdatePortAssociation(ctx, networkingClient, bgpvpnID, id, opts).Extract()
	if err != nil {
		return diag.Errorf("Error updating openstack_bgpvpn_port_associate_v2 %s: %s", id, err)
	}

	// the project_id is returned only on POST/PUT responses
	d.Set("project_id", res.ProjectID)

	return resourceBGPVPNPortAssociateV2Read(ctx, d, meta)
}

func resourceBGPVPNPortAssociateV2Delete(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
	config := meta.(*Config)

	networkingClient, err := config.NetworkingV2Client(ctx, GetRegion(d, config))
	if err != nil {
		return diag.Errorf("Error creating OpenStack network client: %s", err)
	}

	bgpvpnID, id, err := parsePairedIDs(d.Id(), "openstack_bgpvpn_port_associate_v2")
	if err != nil {
		return diag.FromErr(err)
	}

	portID := d.Get("port_id").(string)

	err = bgpvpns.DeletePortAssociation(ctx, networkingClient, bgpvpnID, id).ExtractErr()
	if err != nil && CheckDeleted(d, err


PYRAMID,
        score: 0,
        coin: 0,
        isPause: false);

    if (dialogResult.exit) {
      homeViewModel.setFirstTime(GameCategoryType.NUMBER_PYRAMID);
      timerSubscription.resume();
      _pause = false;
      notifyListeners();
    }
  }

  void dispose() {
    super.dispose();
    this.timerSubscription.cancel();
  }
}
import 'package:mathgame/src/data/models/math_pairs.dart';
import 'package:mathgame/src/utility/math_util.dart';

class MathPairsRepository {
  static List<int> listHasCode = [];

  static List<MathPairs> getMathPairsDataList(int level) {
    if (level == 1) {
      listHasCode.clear();
    }

    int i = 0;
    int totalPairs = level <= 2 ? 12 : 18;
    print("level $level   total pairs $totalPairs");

    List<Pair> list = [];

    while (list.length < totalPairs) {
      MathUtil.getMathPair(level, (totalPairs ~/ 2) - (list.length ~/ 2))
          .forEach((Expression expression) {
        Pair mathPair1 = Pair(
            i,
            "${expression.firstOperand} ${expression.operator1} ${expression.secondOperand}",
            false,
            true);
        Pair mathPair2 = Pair(i, "${expression.answer}", false, true);
        if (!list.contains(mathPair2) &&
            !listHasCode.contains(mathPair1.hashCode)) {
          list.add(mathPair1);
          list.add(mathPair2);
          listHasCode.add(mathPair1.hashCode);
          i++;
        }
      });
    }

    list.shuffle();
    return [MathPairs(list, totalPairs)];
  }
}

void main() {
  for (int i = 1; i < 6; i++) {
    MathPairsRepository.getMathPairsDataList(i);
  }
}
import 'package:test/test.dart';
import 'package:zone/model/msg_node.dart';

// 辅助类，用于构建测试数据
class TestMsgBuilder {
  final MsgNode rootNode;

  TestMsgBuilder(this.rootNode);

  /// 构建一个消息链，从 `startNode`（如果提供）或 `rootNode` 开始，
  /// 依次添加指定 ID 的节点。
  /// 如果 `keepLatest` 为 true，则在添加新节点时，父节点的 `latest` 不会更新。
  /// 返回链中最后添加的节点。
  MsgNode buildChain(List<int> ids, {MsgNode? startNode, bool keepLatest = false}) {
    var current = startNode ?? rootNode;
    for (final id in ids) {
      current = current.add(MsgNode(id), keepLatest: keepLatest);
    }
    return current; // 返回最后添加的节点
  }

  /// 构建一个线性的对话，交替添加用户消息和机器人消息。
  /// `turns` 指定对话的回合数。
  /// `startId` 指定消息 ID 的起始值。
  List<MsgNode> buildLinearConversation(int turns, {int startId = 1}) {
    final nodes = <MsgNode>[];
    var currentParent = rootNode;
    var currentId = startId;

    for (var i = 0; i < turns; i++) {
      // 添加用户消息
      final userMsg = currentParent.add(MsgNode(currentId++));
      nodes.add(userMsg);
      if (i < turns) {
        // 为用户消息添加对应的机器人回复
        final botMsg = userMsg.add(MsgNode(currentId++));
        nodes.add(botMsg);
        currentParent = botMsg;
      } else {
        currentParent = userMsg;
      }
    }
    return nodes;
  }
}

void main() {
  late MsgNode root;
  late TestMsgBuilder builder;

  // 在每个测试运行前设置初始状�


teral BinaryExpression BinOp CallExpression Callee CallLiteral CallTag ParenthesizedContent , PseudoClassName ArgList IdSelector # IdName ] AttributeSelector [ AttributeName MatchOp ChildSelector ChildOp DescendantSelector SiblingSelector SiblingOp } { Block Declaration PropertyName Important ; ImportStatement AtKeyword import KeywordQuery FeatureQuery FeatureName BinaryQuery LogicOp UnaryQuery UnaryQueryOp ParenthesizedQuery SelectorQuery selector MediaStatement media CharsetStatement charset NamespaceStatement namespace NamespaceName KeyframesStatement keyframes KeyframeName KeyframeList from to SupportsStatement supports AtRule Styles",maxTerm:108,nodeProps:[["openedBy",17,"(",48,"{"],["closedBy",18,")",49,"}"]],propSources:[X],skippedNodes:[0,3],repeatNodeCount:8,tokenData:"Lq~R!^OX$}X^%u^p$}pq%uqr)Xrs.Rst/utu6duv$}vw7^wx7oxy9^yz9oz{9t{|:_|}?Q}!O?c!O!P@Q!P!Q@i!Q![Cu![!]Dp!]!^El!^!_$}!_!`E}!`!aF`!a!b$}!b!cG[!c!}$}!}#OHt#O#P$}#P#QIV#Q#R6d#R#T$}#T#UIh#U#c$}#c#dJy#d#o$}#o#pK`#p#q6d#q#rKq#r#sLS#s#y$}#y#z%u#z$f$}$f$g%u$g#BY$}#BY#BZ%u#BZ$IS$}$IS$I_%u$I_$I|$}$I|$JO%u$JO$JT$}$JT$JU%u$JU$KV$}$KV$KW%u$KW&FU$}&FU&FV%u&FV;'S$};'S;=`Lk<%lO$}W%QSOy%^z;'S%^;'S;=`%o<%lO%^W%cSoWOy%^z;'S%^;'S;=`%o<%lO%^W%rP;=`<%l%^~%zh#U~OX%^X^'f^p%^pq'fqy%^z#y%^#y#z'f#z$f%^$f$g'f$g#BY%^#BY#BZ'f#BZ$IS%^$IS$I_'f$I_$I|%^$I|$JO'f$JO$JT%^$JT$JU'f$JU$KV%^$KV$KW'f$KW&FU%^&FU&FV'f&FV;'S%^;'S;=`%o<%lO%^~'mh#U~oWOX%^X^'f^p%^pq'fqy%^z#y%^#y#z'f#z$f%^$f$g'f$g#BY%^#BY#BZ'f#BZ$IS%^$IS$I_'f$I_$I|%^$I|$JO'f$JO$JT%^$JT$JU'f$JU$KV%^$KV$KW'f$KW&FU%^&


     /// <summary>
        /// [NOT YET IMPLEMENTED] Get the Default VPC for a region.
        /// </summary>
        public static Output<GetDefaultVpcResult> Invoke(InvokeOutputOptions options)
            => global::Pulumi.Deployment.Instance.Invoke<GetDefaultVpcResult>("awsx:ec2:getDefaultVpc", InvokeArgs.Empty, options.WithDefaults());
    }

    public sealed class GetDefaultVpcArgs : global::Pulumi.InvokeArgs
    {
        public GetDefaultVpcArgs()
        {
        }
        public static new GetDefaultVpcArgs Empty => new GetDefaultVpcArgs();
    }

    [OutputType]
    public sealed class GetDefaultVpcResult
    {
        public readonly ImmutableArray<string> PrivateSubnetIds;
        public readonly ImmutableArray<string> PublicSubnetIds;
        /// <summary>
        /// The VPC ID for the default VPC
        /// </summary>
        public readonly string VpcId;

        [OutputConstructor]
        private GetDefaultVpcResult(
            ImmutableArray<string> privateSubnetIds,

            ImmutableArray<string> publicSubnetIds,

            string vpcId)
        {
            PrivateSubnetIds = privateSubnetIds;
            PublicSubnetIds = publicSubnetIds;
            VpcId = vpcId;
        }
    }
}


te("node_modules"),
            Validity::Invalid {
                errors: vec!["node_modules is a blacklisted name".into()],
                warnings: vec![]
            }
        );

        assert_eq!(
            validate("favicon.ico"),
            Validity::Invalid {
                errors: vec!["favicon.ico is a blacklisted name".into()],
                warnings: vec![]
            }
        );
    }

    #[test]
    fn node_io_core() {
        assert_eq!(
            validate("http"),
            Validity::ValidForOldPackages {
                warnings: vec!["http is a core module name".into()]
            }
        );
    }

    #[test]
    fn long_package_names() {
        let one_too_long = "ifyouwanttogetthesumoftwonumberswherethosetwonumbersarechosenbyfindingthelargestoftwooutofthreenumbersandsquaringthemwhichismultiplyingthembyitselfthenyoushouldinputthreenumbersintothisfunctionanditwilldothatforyou-";
        let short_enough = "ifyouwanttogetthesumoftwonumberswherethosetwonumbersarechosenbyfindingthelargestoftwooutofthreenumbersandsquaringthemwhichismultiplyingthembyitselfthenyoushouldinputthreenumbersintothisfunctionanditwilldothatforyou";

        assert_eq!(
            validate(one_too_long),
            Validity::ValidForOldPackages {
                warnings: vec!["name can no longer contain more than 214 characters".into()]
            }
        );

        assert_eq!(validate(short_enough), Validity::Valid);
    }

    #[test]
    fn legacy_mixed_case() {
        assert_eq!(
            validate("CAPITAL-LETTERS"),
            Validity::ValidForOldPackages {
                warnings: vec!["name can no longer contain capital letters".into()]
            }
        );
    }
}
<gh_stars>0
use colored::Colorize;

struct Point<T> {
    x: T,
    y: T,
}

impl Point<f32> {
    fn distance_from_origin(&self) -> f32 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

pub fn generics() {
    println!("\n{}", "Generics".green().bold());

    let number_list = vec![34, 50, 25, 100, 65];
    let result = largest(&number_list);
    println!("The largest number is {}", result);

    let char_list = vec!['y', 'm', 'a', 'q'];
    let result = largest(&char_list);
    println!("The largest char is {}", result);

    let _integer = Point { x: 5, y: 10 };
    let float = Point { x: 1.0, y: 4.0 };

    println!("The distance is {}", float.distance_from_origin());
}
use crate::data_types::event_protocol_messages::signatures::sig;

// Searches through each participant to see if the channel pk matches that of the participant.
// Uses the signature as ID for the participants
pub fn find_did_pk_from_channel_pk(
    participants: &Vec<Box<dyn sig::Sig>>,
    channel_pk: &str
) -> Option<String>
{
    for part in participants {
        if channel_pk == part.get_channel_pubkey() {
            return Some(part.get_did_pubkey());
        }
    }

    return None;
}<filename>src/main.rs
use bevy::prelude::*;
use pathfinding::prelude::*;
use std::ops::Not;

const SIZE: i32 = 10;

fn main() {
    let mut app = App::build();
    app.insert_resource(ClearColor(Color::GRAY))
        .insert_resource(WindowDescriptor {
            title: "Pathfinding".to_string(),
            width: 800.,
            height: 600.,
            vsync: false,
            resizable: false,
            ..Default::default


um."}},
[13612] = {"Em defesa de Mor'shan", nil, {"Kadrak, na Paliçada Mor'shan, quer que você mate 5 Escaramuçadores do Vale Gris e 5 Atiradores do Vale Gris."}},
[13613] = {"Resgate dos feridos", nil, {"Use o Bálsamo Medicinal em 5 Defensores Feridos de Mor'shan."}},
[13614] = {"Algalon", nil, {"Leve os Signos dos Vigilantes ao console do Archivum em Ulduar."}},
[13615] = {"Aljavas vazias", nil, {"Truun, na Paliçada Mor'shan, quer que você junte 10 Flechas Utilizáveis na região do Lago Céu Caído."}},
[13616] = {"Limiar do Inverno", nil, {"O Marechal Jacob Alerius, nos Campos do Torneio Argênteo, quer que você lhe traga o Gume Austrino."}},
[13617] = {"Para o oeste, para a praia", nil, {"Fale com o Talen no Acampamento das Profundezas Negras, que fica no Vale Gris."}},
[13618] = {"Encontre Gorat!", nil, {"Kadrak, na Paliçada Mor'shan, quer que você procure por Gorat na região do Lago Céu Caído."}},
[13619] = {"Relatório final", nil, {"Gorat quer que você leve a Ampola de Sangue para Kadrak na Paliçada Mor'shan."}},
[13620] = {"Para Dinah, agora mesmo!", nil, {"Kadrak quer que você leve a Ampola de Sangue de Gorat para Dinah na Paliçada Mor'shan."}},
[13621] = {"A vingança de Gorat", nil, {"Use o Sangue Enfeitiçado de Gorat no corpo de Gorat e, em seguida, derrote o Capitão Elendilad."}},
[13622] = {"História antiga", nil, {"Leve os Fragmentos Estilhaçados de Val'anyr ao Console do Archivum em Ulduar."}},
[13623] = {"Entrega para Orendil", nil, {"Entregue o Saco com Cabelo-de-bathran para Orendil Folharga no Entreposto de Maestra, que fica no Vale Gris."}},
[13624] = {"Um pelotão para chamar de seu", nil, {"Comande um pelotão de Sentinelas do Entreposto de Maestra para destruir 3 Destroçadores do Vale Gris e matar 10 Invasores da Horda."}},
[13625] = {"Dominando as rédeas", nil, {"Golpeie um Alvo Corpo a Corpo com Estocada 5 vezes, use Quebra-escudo em 2 Alvos à Distância vulneráveis, use Investida em 2 Alvos de Investida e depois fale novamente com a Batedora Shalíndria nos Campos do Torneio Argênteo.\n\nCaso perca a lança, é possível obter outra em qualquer Cavalete de Lanças próximo aos estábulos ou no Pavilhão do Pacto de Prata."}},
[13626] = {"Em respeito aos mortos", nil, {"Consiga o Martelo Sagrado de Firo e o Devocionário do Purificador."}},
[13627] = {"Me arruma madeira serrada", nil, {"Leve 12 Tábuas Não Aplainadas para Juntatudo Estourapino nos Campos do Torneio Argênteo."}},
[13628] = {"Vai madeira aí?", nil, {"Truun quer que você cavalgue o Brucutu até o Campo de Trabalho Brado Guerreiro.\n\nFale com Kadrak para pegar as Rédeas de Kadrak, que lhe permitirão montar o Brucutu."}},
[13630] = {"Tudo tem motivo", nil, {"Desative as Pedras-da-lua Azul, Verde e V


ancestor);
};
export function __binarySearch(arr: any[], value: any, min?: number, max?: number): number {
    min = min || 0;
    max = max || arr.length;

    if (min + 1 >= max) { return max; }

    // @ts-ignore
    let mid = parseInt((max - min) / 2) + min;

    if (arr[mid] == value) {
        mid--;
        while (min < mid) {
            if (arr[mid] != value) { break; }
            mid--;
        }
        return mid + 1;
    }

    if (arr[mid] > value) { max = mid; }
    if (arr[mid] < value) { min = mid; }

    return __binarySearch(arr, value, min, max);
}
export default function _addToIndex(buckets: any, obj: any): void {
    for (let prop in buckets) {
        let sarr = buckets[prop][obj[prop]];
        if (!sarr || !sarr.length) {
            sarr = sarr || (buckets[prop][obj[prop]] = []);
            let keys = buckets[prop].__bucket_keys;
            let index = __binarySearch(keys, obj[prop]);
            keys.splice(index, 0, obj[prop]);
        }
        sarr.push(obj);
    }
}
import { generateArray } from '../../../utils/array';

export const f1 = (noOfEggs: number, noOfFloors: number): number => {
  const f = (eggNo: number, floorNo: number) => {
    if (floorNo === 0 || floorNo === 1 || eggNo === 1) return floorNo;
    let minTrials = Number.POSITIVE_INFINITY;
    for (let prevFloorNo = 1; prevFloorNo <= floorNo; ++prevFloorNo) {
      const maxTrials = Math.max(
        f1(eggNo - 1, prevFloorNo - 1),
        f1(eggNo, floorNo - prevFloorNo),
      );
      minTrials = Math.min(minTrials, maxTrials);
    }
    return minTrials + 1;
  };

  return f(noOfEggs, noOfFloors);
};

export const f2 = (noOfEggs: number, noOfFloors: number) => {
  const results = generateArray<number>(noOfEggs + 1, noOfFloors + 1);

  for (let eggNo = 1; eggNo <= noOfEggs; ++eggNo) {
    for (let floorNo = 0; floorNo <= noOfFloors; ++floorNo) {
      if (floorNo === 0 || floorNo === 1 || eggNo === 1)
        results[eggNo][floorNo] = floorNo;
      else {
        let minTrials = Number.POSITIVE_INFINITY;
        for (let prevFloorNo = 1; prevFloorNo <= floorNo; ++prevFloorNo) {
          const maxTrials = Math.max(
            results[eggNo - 1][prevFloorNo - 1],
            results[eggNo][floorNo - prevFloorNo],
          );
          if (maxTrials < minTrials) minTrials = maxTrials;
        }
        results[eggNo][floorNo] = minTrials + 1;
      }
    }
  }

  return results[noOfEggs][noOfFloors];
};

export const f3 = (noOfEggs: number, noOfFloors: number): number => {
  const results = generateArray<number>(noOfEggs + 1, noOfFloors + 1);

  const f = (eggNo: number, floorNo: number) => {
    let result = results[eggNo][floorNo];
    if (typeof result === 'number') return result;

    if (floorNo === 0 || floorNo === 1 || eggNo === 1) result = floorNo;
    else {
      let minTrials = Number.POSITIVE_INFINITY;
      for (let prevFloorNo = 1; prevFloorNo <= floorNo; ++prevFloorNo) {
        const maxTrials = Math.max(
          f1(eggNo - 1, prevFloorNo - 1),
          f1(eggNo, floorNo - prevFl


        offset /= Offset::new(-5, 12);
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(10, 12);
        offset /= 5_u32;
        assert_eq!(offset, Offset::new(2, 12));
    }

    #[test]
    fn rem_offset() {
        let mut offset = Offset::new(8, 12);

        assert_eq!(offset % 5_i32, Offset::new(3, 12));
        assert_eq!(offset % -5_i32, Offset::new(1, 12));
        assert_eq!(offset % Offset::new(5, 12), Offset::new(3, 12));
        assert_eq!(offset % Offset::new(-5, 12), Offset::new(1, 12));
        assert_eq!(offset % 5_u32, Offset::new(3, 12));

        offset %= 5_i32;
        assert_eq!(offset, Offset::new(3, 12));

        offset = Offset::new(8, 12);
        offset %= -5_i32;
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(8, 12);
        offset %= Offset::new(5, 12);
        assert_eq!(offset, Offset::new(3, 12));

        offset = Offset::new(8, 12);
        offset %= Offset::new(-5, 12);
        assert_eq!(offset, Offset::new(1, 12));

        offset = Offset::new(8, 12);
        offset %= 5_u32;
        assert_eq!(offset, Offset::new(3, 12));
    }
}
// run-pass
#![feature(generic_const_exprs)]
#![allow(incomplete_features)]

struct Generic<const K: u64>;

struct ConstU64<const K: u64>;

impl<const K: u64> Generic<K>
where
    ConstU64<{ K - 1 }>: ,
{
    fn foo(self) -> u64 {
        K
    }
}

impl<const K: u64> Generic<K>
where
    ConstU64<{ K - 1 }>: ,
    ConstU64<{ K + 1 }>: ,
    ConstU64<{ K + 1 - 1 }>: ,
{
    fn bar(self) -> u64 {
        let x: Generic<{ K + 1 }> = Generic;
        x.foo()
    }
}

fn main() {
    assert_eq!((Generic::<10>).bar(), 11);
}

// Test that the ``ConstU64<{ K + 1 - 1}>`` bound on ``bar``'s impl block satisfies the
// ``ConstU64<{K - 1}>`` bound on ``foo``'s impl block
use std::time::Duration;
use crossbeam_channel::{bounded, tick, Receiver, select};

fn ctrl_channel() -> Result<Receiver<()>, ctrlc::Error> {
    let (sender, receiver) = bounded(100);
    ctrlc::set_handler(move || {
        let _ = sender.send(());
    })?;

    Ok(receiver)
}

fn main() -> Result<(), exitfailure::ExitFailure> {
    let ctrl_c_events = ctrl_channel()?;
    let ticks = tick(Duration::from_secs(1));

    loop {
        select! {
            recv(ticks) -> _ => {
                println!("working!");
            }
            recv(ctrl_c_events) -> _ => {
                println!();
                println!("Goodbye!");
                break;
            }
        }
    }

    Ok(())
}
<filename>examples/basics/7_modules/7_modules.rs
use nannou::prelude::*;

mod ball;
use crate::ball::Ball;

fn main() {
    nannou::app(model).update(update).simple_window(view).run();
}

struct Model {
    ball: Ball,
}

fn model(_app: &App) -> Model {
    // Create a new ball with a color
    let ball = Ball::new(GREEN);
    // Construct and return the model with our


 to new .ini
				if (migrate && ReadIniIfExists("FrontendOptions", option.m_CFO->save, option.m_CFO->value))
					cfg.remove("FrontendOptions", option.m_CFO->save);
				else
					ReadIniIfExists(option.m_CFO->saveCat, option.m_CFO->save, option.m_CFO->value);

				if (option.m_Action == MENUACTION_CFO_SELECT) {
					option.m_CFOSelect->lastSavedValue = option.m_CFOSelect->displayedValue = *option.m_CFO->value;
				}
			}
		}
	}
#endif

	return true;
}

void SaveINISettings()
{
#ifdef IMPROVED_VIDEOMODE
	StoreIni("VideoMode", "Width", FrontEndMenuManager.m_nPrefsWidth);
	StoreIni("VideoMode", "Height", FrontEndMenuManager.m_nPrefsHeight);
	StoreIni("VideoMode", "Depth", FrontEndMenuManager.m_nPrefsDepth);
	StoreIni("VideoMode", "Subsystem", FrontEndMenuManager.m_nPrefsSubsystem);
	// Windowed mode is loaded below in CUSTOM_FRONTEND_OPTIONS section
#else
	StoreIni("Graphics", "VideoMode", FrontEndMenuManager.m_nDisplayVideoMode);
#endif
	StoreIni("Controller", "HeadBob1stPerson", TheCamera.m_bHeadBob);
	StoreIni("Controller", "VerticalMouseSens", TheCamera.m_fMouseAccelVertical);
	StoreIni("Controller", "HorizantalMouseSens", TheCamera.m_fMouseAccelHorzntl);
	StoreIni("Controller", "InvertMouseVertically", MousePointerStateHelper.bInvertVertically);
	StoreIni("Controller", "DisableMouseSteering", CVehicle::m_bDisableMouseSteering);
	StoreIni("Controller", "Vibration", FrontEndMenuManager.m_PrefsUseVibration);
	StoreIni("Audio", "SfxVolume", FrontEndMenuManager.m_PrefsSfxVolume);
	StoreIni("Audio", "MusicVolume", FrontEndMenuManager.m_PrefsMusicVolume);
	StoreIni("Audio", "Radio", FrontEndMenuManager.m_PrefsRadioStation);
	StoreIni("Audio", "SpeakerType", FrontEndMenuManager.m_PrefsSpeakers);
	StoreIni("Audio", "Provider", FrontEndMenuManager.m_nPrefsAudio3DProviderIndex);
	StoreIni("Audio", "DynamicAcoustics", FrontEndMenuManager.m_PrefsDMA);
	StoreIni("Display", "Brightness", FrontEndMenuManager.m_PrefsBrightness);
	StoreIni("Display", "DrawDistance", FrontEndMenuManager.m_PrefsLOD);
	StoreIni("Display", "Subtitles", FrontEndMenuManager.m_PrefsShowSubtitles);
	StoreIni("Graphics", "AspectRatio", FrontEndMenuManager.m_PrefsUseWideScreen);
	StoreIni("Graphics", "VSync", FrontEndMenuManager.m_PrefsVsyncDisp);
	StoreIni("Graphics", "FrameLimiter", FrontEndMenuManager.m_PrefsFrameLimiter);
	StoreIni("Graphics", "Trails", CMBlur::BlurOn);
	StoreIni("General", "SkinFile", FrontEndMenuManager.m_PrefsSkinFile, 256);
	StoreIni("Controller", "Method", FrontEndMenuManager.m_ControlMethod);
	StoreIni("General", "Language", FrontEndMenuManager.m_PrefsLanguage);

#ifdef EXTENDED_COLOURFILTER
	StoreIni("CustomPipesValues", "PostFXIntensity", CPostFX::Intensity);
#endif
#ifdef EXTENDED_PIPELINES
	StoreIni("CustomPipesValues", "NeoVehicleShininess", CustomPipes::VehicleSh


 udp/9001(listen)`),
			},
			comment: "dedups processes that have multiple connections on the same port",
		},
		{
			ports: []PortRange{
				PortRange{From: 9001, To: 9001, Protocol: "tcp", ListenAddr: "127.0.0.2"},
			},
			reader: testGetProcs(
				process{
					name: "foo",
					pid:  9001,
					socket: tcpSocket{
						State:         Listen,
						LocalAddress:  tcpAddr("127.0.0.1:9001", c),
						RemoteAddress: tcpAddr("192.168.178.1:45001", c),
					},
				},
			),
			probes: []*pb.Probe{
				&pb.Probe{
					Checker: portCheckerID,
					Status:  pb.Probe_Running,
				},
			},
			comment: "only validates the specified listen address",
		},
		{
			ports: []PortRange{
				PortRange{From: 9001, To: 9001, Protocol: "tcp", ListenAddr: "127.0.0.2"},
			},
			reader: testGetProcs(
				process{
					name:   "foo",
					pid:    100,
					socket: tcpSocket{State: Listen, LocalAddress: tcpAddr("0.0.0.0:9001", c)},
				},
			),
			probes: []*pb.Probe{
				prober.newRaised(`conflicting program "foo"(pid=100) is occupying port tcp/9001(listen)`),
			},
			comment: "detects process bound to any address",
		},
		{
			ports: []PortRange{
				PortRange{From: 9001, To: 9001, Protocol: "tcp"},
			},
			reader: testGetProcs(
				process{
					name: "foo",
					pid:  9001,
					socket: tcpSocket{
						State:         TimeWait,
						LocalAddress:  tcpAddr("127.0.0.1:9001", c),
						RemoteAddress: tcpAddr("192.168.178.1:45001", c),
					},
				},
			),
			probes: []*pb.Probe{
				&pb.Probe{
					Checker: portCheckerID,
					Status:  pb.Probe_Running,
				},
			},
			comment: "ignores open ports in TimeWait",
		},
	}

	// exercise & verify
	for _, testCase := range testCases {
		checker := &portChecker{
			ranges:   testCase.ports,
			getPorts: testCase.reader,
		}
		var probes health.Probes
		checker.Check(context.TODO(), &probes)
		sort.Slice(probes, func(i, j int) bool {
			return probes[i].Detail < probes[j].Detail
		})
		c.Assert(probes, test.DeepCompare, testCase.probes, Commentf(testCase.comment))
	}
}

func testGetProcs(procs ...process) portCollectorFunc {
	return func() ([]process, error) {
		return procs, nil
	}
}

func testFailingGetProcs(err error) portCollectorFunc {
	return func() ([]process, error) {
		return nil, err
	}
}
/*
Copyright 2016-2020 Gravitational, Inc.

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

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

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

package main

import (
	"os"
	"os/signal"
	"syscall"

	"github.com/gravitational/satellite/agent"
	"github.com/gravitational/satellite/cmd"
	k8smembership "github.com/gravitational/satellite/lib/membership/kubern


аем свои устройства, чтобы запитать их электричеством от одной розетки. Коммутатор не умеет маршрутизировать сеть как роутер. Он не выдаст вашему устройству ip-адрес и без помощи роутера не сможет выпустить вас в интернет. У стандартного маршрутизатора обычно 4-5 портов для подключения устройств. Соответственно, если ваши устройства подключаются проводами и их больше чем портов на роутере, то вам необходим свитч. Можно к одному порту роутера подключить свитч на 24 порта и спокойно организовать локальную сеть на 24 устройства. А если у вас завалялся еще один роутер, то можно в его web-интерфейсе включить режим коммутатора и тоже использовать как свитч.
* Хаб: Хаб выполняет те же функции, что и коммутатор. Но его технология распределения сильно деревянная и уже устарела. Хаб раздает приходящие от роутера пакеты всем подключенным устройствам без разбора, а устройства уже сами должны разбираться их это пакет или нет. А коммутатор имеет MAC таблицу и поэтому распределяет приходящие пакеты на одно конкретное устройство, которое и запрашивало этот пакет. Следовательно передача данных коммутатором быстрее и эффективнее. В настоящее время уже редко где встретишь использование хаба, но всё таки они попадаются, нужно быть к этому готовым и обязательно рекомендовать пользователю замену хаба на свитч.

**Основные команды для анализа сети**

*   Команда Ping: Чтобы понять активен ли ip-адрес или само устройство, можно его “пропинговать”. Для этого в командной строке пишем команду ping “ip-адрес”. Ping намного полезней использовать с ключами:

    * \-t -”пинговать” непрерывно (для остановки нажимаем комбинацию Ctrl+С);
    * \-а -отображать имя “пингуемого” узла (сайта/устройства/сервера).

    При непрерывном пинге можно увидеть адекватно ли ведет себя пингуемый узел и примерное качество работы интернет канала. Внимание! Иногда на роутерах отключена отправка ICMP пакетов (кто-то отключает специально, а где-то не включена по умолчанию), в таком случае на "пинги" такой узел отвечать не будет, хотя сам будет активен и нормально функцион


namespace RszTool.Generators;

using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

[Generator(LanguageNames.CSharp)]
public class ContentEditorGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        // var classes = context.SyntaxProvider
        //     .CreateSyntaxProvider<HashedFieldConstGeneratorCtx>(
        //         predicate: static (s, _) => s is ClassDeclarationSyntax classDecl && classDecl.Identifier.Text == "ConfigKeys",
        //         transform: static (ctx, _) => new HashedFieldConstGeneratorCtx() {
        //             ClassDecl = (ClassDeclarationSyntax)ctx.Node,
        //             Fields = ctx.Node.ChildNodes().OfType<FieldDeclarationSyntax>().Where(field => field.GetFieldType()?.GetElementTypeName() == "HashedString").ToList(),
        //         }
        //     )
        //     .Where(ctx => ctx is not null);

        // context.RegisterSourceOutput(classes, static (ctx, source) => {
        //     var clsName = source.ClassDecl.Identifier.Text;
        //     var sb = new StringBuilder();
        //     AppendClassDefinition(sb, source.ClassDecl, out int indent);
        //     var indentStr = new string('\t', indent);
        //     foreach (var field in source.Fields) {
        //         var name = field.GetFieldName();
        //         if (name == null) continue;
        //         sb.Append(indentStr).AppendLine($"public const uint {name}_Hash = {MurMur3HashUtils.GetHash(name)};");
        //     }
        //     CloseIndents(sb, indent);
        //     ctx.AddSource($"{clsName}.g", sb.ToString());
        //


et; private set; } = (int)TokenExpiration.Absolute;

    public int AccessTokenType { get; private set; } = 0; // AccessTokenType.Jwt;

    public bool EnableLocalLogin { get; private set; } = true;

    public List<ClientIdPRestriction> IdentityProviderRestrictions { get; private set; } = new();

    public bool IncludeJwtId { get; private set; }

    public List<ClientClaim> Claims { get; private set; } = new();

    public bool AlwaysSendClientClaims { get; private set; }

    public string ClientClaimsPrefix { get; private set; } = "client_";

    public string PairWiseSubjectSalt { get; private set; } = string.Empty;

    public List<ClientCorsOrigin> AllowedCorsOrigins { get; private set; } = new();

    public List<ClientProperty> Properties { get; private set; } = new();

    public DateTime? LastAccessed { get; private set; }

    public int? UserSsoLifetime { get; private set; }

    public string UserCodeType { get; private set; } = string.Empty;

    public int DeviceCodeLifetime { get; private set; } = 300;

    public bool NonEditable { get; private set; }

    private Client()
    {
    }

    public Client(ClientTypes clientType, string clientId, string clientName)
    {
        SetClientType(clientType);
        ClientId = clientId;
        ClientName = clientName;
    }

    public void SetClientType(ClientTypes clientType)
    {
        ClientType = clientType;
        switch (clientType)
        {
            case ClientTypes.Web:
            case ClientTypes.Spa:
            case ClientTypes.Native:
                AllowedGrantTypes = GrantTypeConsts.Code.Select(x => new ClientGrantType(x)).ToList();
                RequirePkce = true;
                RequireClientSecret = false;
                break;
            case ClientTypes.Machine:
                AllowedGrantTypes = GrantTypeConsts.ClientCredentials.Select(x => new ClientGrantType(x)).ToList();
                RequireClientSecret = true;
                break;
            case ClientTypes.Device:
                AllowedGrantTypes = GrantTypeConsts.DeviceFlow.Select(x => new ClientGrantType(x)).ToList();
                RequireClientSecret = false;
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    public void SetRedirectUris(List<string> redirectUris)
    {
        RedirectUris = redirectUris.Select(x => new ClientRedirectUri(x)).ToList();
    }

    public void SetPostLogoutRedirectUris(List<string> postLogoutRedirectUris)
    {
        PostLogoutRedirectUris = postLogoutRedirectUris.Select(x => new ClientPostLogoutRedirectUri(x)).ToList();
    }

    public void SetAllowedScopes(List<string> allowedScopes)
    {
        AllowedScopes = allowedScopes.Select(x => new ClientScope(x)).ToList();
    }
}


, click cnt:   0
[     81][    21] ID(hex):   0, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   0
[    281][   200] ID(hex):   0, evt:   ONCLICK, keep-alive cnt:   0, click cnt:   1
Testing test_sequence_onpress_debounce ..................................... pass
[  65547][ 65547] ID(hex):   0, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   0
[  65568][    21] ID(hex):   0, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   0
[  65768][   200] ID(hex):   0, evt:   ONCLICK, keep-alive cnt:   0, click cnt:   1
Testing test_sequence_time_overflow_onpress_debounce ....................... pass
[  65527][ 65527] ID(hex):   0, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   0
[  65548][    21] ID(hex):   0, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   0
[  65748][   200] ID(hex):   0, evt:   ONCLICK, keep-alive cnt:   0, click cnt:   1
Testing test_sequence_time_overflow_onpress ................................ pass
[  65507][ 65507] ID(hex):   0, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   0
[  65528][    21] ID(hex):   0, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   0
[  65728][   200] ID(hex):   0, evt:   ONCLICK, keep-alive cnt:   0, click cnt:   1
Testing test_sequence_time_overflow_onrelease_muti ......................... pass
[  65267][ 65267] ID(hex):   0, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   0
[  65767][   500] ID(hex):   0, evt: KEEPALIVE, keep-alive cnt:   1, click cnt:   0
[  65789][    22] ID(hex):   0, evt: ONRELEASE, keep-alive cnt:   1, click cnt:   0
Testing test_sequence_time_overflow_keepalive .............................. pass
[     20][    20] ID(hex):   1, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   0
[    164][   144] ID(hex):   1, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   0
[    364][   200] ID(hex):   1, evt:   ONCLICK, keep-alive cnt:   0, click cnt:   1
Testing test_sequence_onrelease_debounce ................................... pass
[     20][    20] ID(hex):   1, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   0
[    102][    82] ID(hex):   1, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   0
[    123][    21] ID(hex):   1, evt:   ONPRESS, keep-alive cnt:   0, click cnt:   1
[    204][    81] ID(hex):   1, evt: ONRELEASE, keep-alive cnt:   0, click cnt:   1
[    404][   200] ID(hex):   1, evt:   ONCLICK, keep-alive cnt:   0, click cnt:   2
Testing test_sequence_onrelease_debounce_over ..............................


T_AND_BACK, GL_LINE);

        (
            shader,
            screen_shader,
            cubevao,
            planevao,
            quadvao,
            cube_texture,
            floor_texture,
            framebuffer,
            texture_colorbuffer,
        )
    };

    // render loop
    event_loop.run(move |event, _, control_flow| match event {
        Event::WindowEvent { ref event, window_id } if window_id == window.id() => match event {
            WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
            WindowEvent::KeyboardInput { input, .. } => match input {
                KeyboardInput {
                    state: ElementState::Pressed,
                    virtual_keycode: Some(VirtualKeyCode::Escape),
                    ..
                } => *control_flow = ControlFlow::Exit,
                _ => {
                    let current_frame = get_time(&start_time);

                    // input
                    process_input(&input, current_frame - last_frame, &mut camera);
                    last_frame = current_frame;
                }
            },
            WindowEvent::Resized(physical_size) => {
                // make sure the viewport matches the new window dimensions; note that width and
                // height will be significantly larger than specified on retina displays.
                gl::viewport(0, 0, physical_size.width as i32, physical_size.height as i32);
            }
            _ => {
                // events
                process_events(&event, &mut first_mouse, &mut last_x, &mut last_y, &mut camera);
            }
        },
        Event::MainEventsCleared => {
            // redraw here for not active games like a RPG or RTS
            // per-frame time logic

            // bind to framebuffer and draw scene as we normally would to color texture
            gl::bind_framebuffer(GL_FRAMEBUFFER, framebuffer);
            gl::enable(GL_DEPTH_TEST); // enable depth testing (is disabled for rendering screen-space quad)

            // make sure we clear the framebuffer's content
            gl::clear_color(0.1, 0.1, 0.1, 1.0);
            gl::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            shader.use_program();
            let mut model: Matrix4<f32>;
            let view = camera.get_view_matrix();
            let projection: Matrix4<f32> =
                perspective(Deg(camera.zoom), SCR_WIDTH as f32 / SCR_HEIGHT as f32, 0.1, 100.0);
            shader.set_mat4("view", &view);
            shader.set_mat4("projection", &projection);
            // cubes
            gl::bind_vertex_array(cubevao);
            gl::active_texture(GL_TEXTURE0);
            gl::bind_texture(GL_TEXTURE_2D, cube_texture);
            model = Matrix4::from_translation(vec3(-1.0, 0.0, -1.0));
            shader.set_mat4("model", &model);
            gl::draw_arrays(GL_TRIANGLES, 0, 36);
            model = Matrix4::from_translation(vec3(2.0, 0.0, 0.0));
            shader.set_mat4("model", &model);
            gl::draw_arrays(GL_TRIANGLES, 0, 36);
            // floor
            gl::bind_vertex_array(planevao);
            gl::bind_texture(GL_TEXTURE_2D, floor_texture);
            shader.set_mat4("model", &Matrix4::identity());
            gl::draw_arrays(GL_TRIANGLES, 0, 6);
            gl::bind_vertex_array(0);

            // now bind