�本文呢呢表纯本文呢"
                  "表纯本文呢表纯本文呢表纯本文呢呢表纯本文呢表纯本文呢表纯本文呢表纯本"
                  "文呢呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢呢表纯本文呢表纯本文呢"
                  "表纯本文呢表纯本文呢呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢呢表纯"
                  "本文呢表纯本文呢表纯本文呢表纯本文呢呢表纯本文呢表纯本文呢表纯本文呢",
              isShowOperateWidget: false,
            ));
  }
}
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../common/UiUtils.dart';
import '../common/fdb_overlay.dart';
import 'inspector_bottom_edit_page.dart';

const Color _kHighlightedRenderObjectFillColor =
    Color.fromARGB(50, 128, 128, 255);
const String _kFileName = 'UiUtils.dart';
const Color _kTooltipBackgroundColor = Color.fromARGB(230, 60, 60, 60);
const Color _kTooltipBackgroundColor1 = Color.fromARGB(100, 60, 60, 60);
const double _kTooltipPadding = 5.0;
const TextStyle _messageStyle = TextStyle(
  color: Color(0xFFFFFFFF),
  fontSize: 15.0,
  height: 1.2,
);

abstract class InspectorElementChangeListener {
  void inspectorElementChangeListener(Element element, bool isUp);
}

const String kOverlayBackgroundType = 'background_type';
const String kOverlayInfoType = "info_type";

class InspectorElementChange extends InspectorElementChangeListener {
  BuildContext context;
  Element _element;
  ValueNotifier<Rect> _locationNotifier;
  ValueNotifier<Element> _infoNotifier;

  _InfoPanelWidget _infoPanelWidget;
  FdbOverlayBuilder _fdbOverlayBuilder;

  InspectorElementChange(this.context) {
    _locationNotifier = ValueNotifier(null);
  }

  String preFile;
  String preLine;
  double _showY;
  double _showX;

  @override
  void inspectorElementChangeListener(Element element, bool isUp) {
    showOverlayMaskShade(element);
    showOverlayInfo(element);
  }

  void showOverlayMaskShade(Element element) {
    if (element == null || getRectByElement(element) == null) {
      return;
    }
    Size size = element.size;
    Rect rect = getRectByElement(element);

    Widget background = IgnorePointer(
      ignoring: true,
      child: Container(
        width: size.width,
        height: size.height,
        color: _kHighlightedRenderObjectFillColor,
      ),
    );

    FdbOverlayBuilder builder =
        FdbOverlayBuilder().dx(rect.left).dy(rect.top).widget(background);
    FdbOverlay.getInstance().putBuilder(builder, kOverlayBackgroundType).show(
          context,
        );
  }

  void showOverlayInfo(Element element) {
    if (element == null || getRectByElement(element) == null) {
      return;
    }

    Size size = element.size;
    Rect rect = getRectByElement(element);

    double dx = rect.left;
    double dy = rect.top + size.height + 3;

    Rect locationRect = Rect.fromLTRB(_showX ?? dx, _showY ?? dy + 4, 0, 0);

    if (_fdbOverlayBuilder == null) {
      _infoNotifier = new ValueNotifier(_element);
      _locationNotifier.value = locationRect;
      _infoPanelWidget = _InfoPanelWidget(
        valueNotifier: _infoNotifier,
        submitCallback: inspectorElementChangeListener,
      );
      _fdbOverlayBuilder = FdbOverlayBuilder()
          .cust


92] = {"Rix Quijatrampa","Armas de combates de arena excepcionales"},
[34093] = {"Blazzek el Dentellada","Armas de combates de arena excepcionales"},
[34094] = {"Grex Bullecerebros","Armas de combates de arena excepcionales"},
[34095] = {"Rix Quijatrampa","Armas de combates de arena excepcionales"},
[34096] = {"Acechador defensor feral de Auriaya",nil},
[34097] = {"Materia oscura desatada",nil},
[34098] = {"Acechador de esencia acuosa de Auriaya",nil},
[34099] = {"Agujero de gusano",nil},
[34100] = {"Algalon Void Zone Visual Stalker",nil},
[34101] = {"Hostigador de Vallefresno",nil},
[34102] = {"Confesora Argenta Cabelloclaro",nil},
[34103] = {"Keynira Ala de Lechuza",nil},
[34104] = {"The Black Knight (No helmet)",nil},
[34107] = {"Argent Charger (No abilities)",nil},
[34116] = {"Pez enigmático",nil},
[34117] = {"Hostigador de Vallefresno",nil},
[34118] = {"Defensor de Mor'shan",nil},
[34119] = {"Brann Barbabronce",nil},
[34120] = {"Máquina de volar de Brann",nil},
[34121] = {"Flames (Spread)",nil},
[34122] = {"Comandante Colminiestro",nil},
[34123] = {"Astranaar's Burning! Fire Bunny",nil},
[34124] = {"Anciano enfurecido",nil},
[34125] = {"Caballo de campaña de guerra de establo",nil},
[34126] = {"Hostigador de Vallefresno",nil},
[34127] = {"Comandante Guardahuesos",nil},
[34128] = {"Vagón de peste Guardahuesos",nil},
[34129] = {"Bomba de Naturaleza",nil},
[34132] = {"Lanzador de Astranaar",nil},
[34133] = {"Campeón de Hodir",nil},
[34134] = {"Aparecido invernal",nil},
[34135] = {"Estruendor invernal",nil},
[34136] = {"Guardia del Hachazo",nil},
[34137] = {"Jormungar invernal",nil},
[34138] = {"Ashenvale Oak Bunny",nil},
[34143] = {"Ordenador",nil},
[34144] = {"Mercenario de expedición",nil},
[34145] = {"Ingeniero de expedición",nil},
[34146] = {"Montículo de nieve (4)",nil},
[34147] = {"Robot antiincendio",nil},
[34149] = {"Bomba de Escarcha",nil},
[34150] = {"Montículo de nieve (6)",nil},
[34151] = {"Montículo de nieve (8)",nil},
[34154] = {"Caballo de guerra esquelético azul",nil},
[34155] = {"Kodo blanco",nil},
[34156] = {"Ravasaurio Pellejo Venenoso",nil},
[34157] = {"Toxic Tolerance Kill Credit Bunny",nil},
[34158] = {"Ravasaurio Pellejo Venenoso joven",nil},
[34159] = {"Ulduar Gauntlet Generator (small radius)",nil},
[34160] = {"Jinete del viento de vigilancia",nil},
[34161] = {"Mecanopam 54-A",nil},
[34163] = {"Helión de Grito Infernal",nil},
[34164] = {"Tanque de batalla me


str r1, [r0]
	pop {r4, r5, r6, pc}
	.balign 4, 0
	thumb_func_end ov93_0225E008

	thumb_func_start ov93_0225E03C
ov93_0225E03C: ; 0x0225E03C
	push {r4, r5, r6, r7, lr}
	sub sp, #0xc
	mov r1, #0x51
	str r0, [sp]
	str r0, [sp, #8]
	add r0, #0xd8
	lsl r1, r1, #2
	str r0, [sp, #8]
	add r0, r0, r1
	mov r7, #0
	str r0, [sp, #4]
_0225E052:
	ldr r4, [sp, #8]
	ldr r5, [sp, #4]
	mov r6, #0
_0225E058:
	add r0, r4, #0
	add r0, #0xc8
	ldr r0, [r0]
	cmp r0, #1
	bne _0225E07A
	mov r1, #1
	add r0, r5, #0
	lsl r1, r1, #0xc
	bl sub_0201815C
	cmp r0, #1
	bne _0225E07A
	ldr r0, [sp]
	add r1, r7, #0
	add r2, r6, #0
	bl ov93_0225E008
_0225E07A:
	add r6, r6, #1
	add r4, #0x90
	add r5, #0x90
	cmp r6, #4
	blt _0225E058
	mov r0, #9
	ldr r1, [sp, #8]
	lsl r0, r0, #6
	add r0, r1, r0
	str r0, [sp, #8]
	mov r0, #9
	ldr r1, [sp, #4]
	lsl r0, r0, #6
	add r0, r1, r0
	add r7, r7, #1
	str r0, [sp, #4]
	cmp r7, #8
	blt _0225E052
	add sp, #0xc
	pop {r4, r5, r6, r7, pc}
	.balign 4, 0
	thumb_func_end ov93_0225E03C

	thumb_func_start ov93_0225E0A4
ov93_0225E0A4: ; 0x0225E0A4
	push {r3, r4, r5, r6, r7, lr}
	sub sp, #8
	str r0, [sp]
	add r0, #0xd8
	str r0, [sp]
	ldr r7, [sp]
	mov r0, #0
	str r0, [sp, #4]
	add r7, #0xcc
_0225E0B6:
	ldr r4, [sp]
	mov r6, #0
	add r5, r7, #0
_0225E0BC:
	add r0, r4, #0
	add r0, #0xc8
	ldr r0, [r0]
	cmp r0, #1
	bne _0225E0CC
	add r0, r5, #0
	bl sub_020181EC
_0225E0CC:
	add r6, r6, #1
	add r4, #0x90
	add r5, #0x90
	cmp r6, #4
	blt _0225E0BC
	mov r0, #9
	ldr r1, [sp]
	lsl r0, r0, #6
	add r0, r1, r0
	str r0, [s


).apply { orCreateTag.putLong("Energy", capacity) })
        }
    }

    override fun appendHoverText(stack: ItemStack, world: Level?, tooltip: MutableList<Component>, extra: TooltipFlag) {
        val amount = stack.orCreateTag.getLong("Energy")
        tooltip.add(LangKeys.ENERGY_ENERGY_STORED.format(EnergyUnit.UnitType.HBM.getPreferredUnit(amount).format(amount, false), EnergyUnit.UnitType.HBM.getPreferredUnit(capacity).format(capacity, false)).gray()) // TODO configurable units
        tooltip.add(LangKeys.ENERGY_CHARGE_RATE.format(EnergyUnit.UnitType.HBM.getPreferredUnit(chargeRate).format(chargeRate, false)).gray())
        tooltip.add(LangKeys.ENERGY_DISCHARGE_RATE.format(EnergyUnit.UnitType.HBM.getPreferredUnit(dischargeRate).format(dischargeRate, false)).gray())
    }

    /*
    FIXME client-side duplication glitch
    For some reason, a duplication glitch occurs exceptionally often with this approach. Other mods' implementations also
    have that problem, but here, almost every tenth shift-click creates a dead copy on the client, even in machines from
    other mods. Behind this could be a tag modification even though the item does not exist anymore, and the client tries
    to save it anyway.
    */
    override fun initCapabilities(stack: ItemStack, nbt: CompoundTag?): ICapabilityProvider = object : ICapabilityProvider {
        @Suppress("UsePropertyAccessSyntax")
        private val energyCapability = LazyOptional.of { // doing it this way has the added benefit of the damage tag actually working ('cause it's delayed)
            object : LudicrousEnergyStorage(capacity, chargeRate, dischargeRate, stack.getOrCreateTag().getLong("Energy")) {
                override fun receiveEnergy(maxReceive: Int, simulate: Boolean): Int {
                    if (stack.isEmpty || stack.item !is BatteryItem) return 0
                    val energyTransferred = super.receiveEnergy(maxReceive, simulate)
                    if (!simulate) {
                        stack.damageValue = ((getActualMaxEnergyStored() - getActualEnergyStored()).toDouble() / energyPerDamage.toDouble()).toInt()
                        stack.getOrCreateTag().putLong("Energy", getActualEnergyStored())
                    }
                    return energyTransferred
                }

                override fun extractEnergy(maxExtract: Int, simulate: Boolean): Int {
                    if (stack.isEmpty || stack.item !is BatteryItem) return 0
                    val energyTransferred = super.extractEnergy(maxExtract, simulate)
                    if (!simulate) {
                        stack.damageValue = ((getActualMaxEnergyStored() - getActualEnergyStored()).toDouble() / energyPerDamage.toDouble()).toInt()
                        stack.getOrCreateTag().putLong("Energy", getActualEnergyStored())
                    }
                    return energyTransferred
                }
            }
        }

        override fun <T : Any?> getCapability(cap: Capability<T>, side: Direction?): LazyOptional<T> =
            if (cap == CapabilityEnergy.ENERGY) energyCapability.cast() else LazyOptional.empty()
    }
}
package at.martinthedragon.nucleartech.recipe

import at.martinthedragon.nucleartech.ntm
import at.martinthedragon.nucleartech.recipe.anvil.AnvilConstructingRecipe
im


onversationType"] = type.index;
    Map result = await PushChannel.invokeMethod(
        ChatMethodKeys.removeConversationSilentMode, req);
    try {
      EMError.hasErrorFromResult(result);
    } catch (e) {
      rethrow;
    }
  }

  /// ~english
  /// Gets the offline push settings of a conversation.
  ///
  /// Param [conversationId] The conversation ID.
  ///
  /// Param [type] The conversation type.
  ///
  /// **Return** The offline push settings of the conversation.
  ///
  /// **Throws** A description of the exception. See [EMError].
  /// ~end
  ///
  /// ~chinese
  /// 获取指定会话的离线推送设置。
  ///
  /// Param [conversationId] 会话 ID。
  ///
  /// Param [type] 会话类型。
  ///
  /// **Return** 会话的离线推送设置。
  ///
  /// **Throws** 如果有异常会在此抛出，包括错误码和错误信息，详见 [EMError]。
  /// ~end
  @override
  Future<ChatSilentModeResult> fetchConversationSilentMode({
    required String conversationId,
    required EMConversationType type,
  }) async {
    Map req = {};
    req["conversationId"] = conversationId;
    req["conversationType"] = type.index;
    Map result = await PushChannel.invokeMethod(
        ChatMethodKeys.fetchConversationSilentMode, req);
    try {
      EMError.hasErrorFromResult(result);
      Map map = result[ChatMethodKeys.fetchConversationSilentMode];
      return ChatSilentModeResult.fromJson(map);
    } catch (e) {
      rethrow;
    }
  }

  /// ~english
  /// Sets the offline push settings at the app level for the current login user.
  ///
  /// Param [param] The offline push parameters.
  ///
  /// **Throws** A description of the exception. See [EMError].
  /// ~end
  ///
  /// ~chinese
  /// 设置当前登录用户的 app 级别的推送设置。
  ///
  /// Param [param] 离线推送参数。
  ///
  /// **Throws** 如果有异常会在此抛出，包括错误码和错误信息，详见 [EMError]。
  /// ~end
  @override
  Future<void> setSilentModeForAll({
    required ChatSilentModeParam param,
  }) async {
    Map req = {};
    req["param"] = param.toJson();
    Map result = await PushChannel.invokeMethod(
      ChatMethodKeys.setSilentModeForAll,
      req,
    );
    try {
      EMError.hasErrorFromResult(result);
    } catch (e) {
      rethrow;
    }
  }

  /// ~english
  /// Gets the offline push settings at the app level for the current login user.
  ///
  /// **Return** The offline push settings settings.
  ///
  /// **Throws** A description of the exception. See [EMError].
  /// ~end
  ///
  /// ~chinese
  /// 获取当前登录用户的 app 级别的推送通知设置。
  ///
  /// **Return** 推送通知设置。
  ///
  /// **Throws** 如果有异常会在此抛出，包括错误码和错误信息，详见 [EMError]。
  /// ~end
  @override
  Future<ChatSilentModeResult> fetchSilentModeForAll() async {
    Map result =
        await PushChannel.invokeMethod(ChatMethodKeys.fetchSil


put(PlayerSettings PlayerData)
        {
            byte[] bufferX = BitConverter.GetBytes((UInt16)PlayerData.RIController.Computed_X);
            byte[] bufferY = BitConverter.GetBytes((UInt16)PlayerData.RIController.Computed_Y);

            if (PlayerData.ID == 1)
            {
                WriteByte(_Data_Base_Address + _P1_X_Offset, bufferX[0]);
                WriteByte(_Data_Base_Address + _P1_Y_Offset, bufferY[0]);

                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.OnScreenTriggerDown) != 0)
                    Apply_OR_ByteMask(_Data_Base_Address + _P1_Buttons_Offset, 0x02);
                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.OnScreenTriggerUp) != 0)
                    Apply_AND_ByteMask(_Data_Base_Address + _P1_Buttons_Offset, 0xFD);

                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.ActionDown) != 0)
                    Apply_OR_ByteMask(_Data_Base_Address + _P1_Buttons_Offset, 0x01);
                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.ActionUp) != 0)
                    Apply_AND_ByteMask(_Data_Base_Address + _P1_Buttons_Offset, 0xFE);
            }
            else if (PlayerData.ID == 2)
            {
                WriteByte(_Data_Base_Address + _P2_X_Offset, bufferX[0]);
                WriteByte(_Data_Base_Address + _P2_Y_Offset, bufferY[0]);

                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.OnScreenTriggerDown) != 0)
                    Apply_OR_ByteMask(_Data_Base_Address + _P2_Buttons_Offset, 0x02);
                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.OnScreenTriggerUp) != 0)
                    Apply_AND_ByteMask(_Data_Base_Address + _P2_Buttons_Offset, 0xFD);

                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.ActionDown) != 0)
                    Apply_OR_ByteMask(_Data_Base_Address + _P2_Buttons_Offset, 0x01);
                if ((PlayerData.RIController.Computed_Buttons & RawInputcontrollerButtonEvent.ActionUp) != 0)
                    Apply_AND_ByteMask(_Data_Base_Address + _P2_Buttons_Offset, 0xFE);
            }
        }

        #endregion

        #region Outputs

        /// <summary>
        /// Create the Output list that we will be looking for and forward to MameHooker
        /// </summary>
        protected override void CreateOutputList()
        {
            //Gun motor : stays activated when trigger is pulled
            //Gun recoil : not used ??
            _Outputs = new List<GameOutput>();
            _Outputs.Add(new GameOutput(OutputDesciption.P1_LmpStart, OutputId.P1_LmpStart));
            _Outputs.Add(new GameOutput(OutputDesciption.P2_LmpStart, OutputId.P2_LmpStart));
            _Outputs.Add(new GameOutput(OutputDesciption.Lmp2D3D, OutputId.Lmp2D3D));
            _Outputs.Add(new GameOutput(OutputDesciption.P1_AirFront, OutputId.P1_AirFront));
            _Outputs.Add(new GameOutput(OutputDesciption.P2_AirFront, OutputId.P2_AirFront));
            _Outputs.Add(new GameOutput(OutputDesciption.P1_AirRear, OutputId.P1_AirRear));
            _Outputs.Add(new GameOutput(OutputDesciption.P2_AirRear, OutputId.P2_AirRear));
            _Outputs.Add(new GameOutput(OutputDesciption.P1_GunRecoil, OutputId.P1_GunRec


//     prelude::*,
///     primitives::{Arc, PrimitiveStyle, PrimitiveStyleBuilder},
/// };
/// # use embedded_graphics::mock_display::MockDisplay;
/// # let mut display = MockDisplay::default();
///
/// // Arc with 1 pixel wide white stroke with top-left point at (10, 20) with a diameter of 30
/// Arc::new(Point::new(10, 20), 30, 0.0.deg(), 90.0.deg())
///     .into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1))
///     .draw(&mut display)?;
///
/// // Arc with styled stroke with top-left point at (15, 25) with a diameter of 20
/// let style = PrimitiveStyleBuilder::new()
///     .stroke_color(Rgb565::RED)
///     .stroke_width(3)
///     .build();
///
/// Arc::new(Point::new(15, 25), 20, 180.0.deg(), -90.0.deg())
///     .into_styled(style)
///     .draw(&mut display)?;
/// # Ok::<(), core::convert::Infallible>(())
/// ```
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
pub struct Arc {
    /// Top-left point of the bounding-box of the circle supporting the arc
    pub top_left: Point,

    /// Diameter of the circle supporting the arc
    pub diameter: u32,

    /// Angle at which the arc starts
    pub angle_start: Angle,

    /// Angle defining the arc sweep starting at angle_start
    pub angle_sweep: Angle,
}

impl Arc {
    /// Create a new arc delimited with a top-left point with a specific diameter and start and sweep angles
    pub const fn new(
        top_left: Point,
        diameter: u32,
        angle_start: Angle,
        angle_sweep: Angle,
    ) -> Self {
        Arc {
            top_left,
            diameter,
            angle_start,
            angle_sweep,
        }
    }

    /// Create a new arc centered around a given point with a specific diameter and start and sweep angles
    pub fn with_center(
        center: Point,
        diameter: u32,
        angle_start: Angle,
        angle_sweep: Angle,
    ) -> Self {
        Self::from_circle(
            Circle::with_center(center, diameter),
            angle_start,
            angle_sweep,
        )
    }

    /// Creates an arc based on a circle.
    ///
    /// The resulting arc will match the `top_left` and `diameter` of the base circle.
    pub fn from_circle(circle: Circle, angle_start: Angle, angle_sweep: Angle) -> Self {
        Self {
            top_left: circle.top_left,
            diameter: circle.diameter,
            angle_start,
            angle_sweep,
        }
    }

    /// Returns a circle with the same `top_left` and `diameter` as this arc.
    pub fn to_circle(&self) -> Circle {
        Circle::new(self.top_left, self.diameter)
    }

    /// Return the center point of the arc.
    pub fn center(&self) -> Point {
        self.bounding_box().center()
    }
}

impl Primitive for Arc {}

impl PointsIter for Arc {
    type Iter = Points;

    fn points(&self) -> Self::Iter {
        Points::new(self)
    }
}


を提供します。

Cloudflareでは人員を拡大させており、日本最初の東京オフィスでは人材を募集しています。

あなたがもし、企業や一般ユーザーのため、より良いインターネットを作り上げる、この意欲的なミッションの一員になりたければ、
是非私たちの東京オフィスの人材募集ページにこちらからアクセスしてください。

採用ページでは、営業、マーケティング、テクニカル・サポート、その他さまざまな業種の募集を行っています。

今後、Cloudflareのチームが日本でどのように展開していくのか、本当に楽しみです。

私たちの日本における役割

私は日本の顧客にネットワークや様々なツールを提供して彼らのビジネスの拡大に役立ちたいと思っています。

日本にはいまだに自分たちの施設内、またはクラウド環境に自分ら自身でセキュリティ保護やその他ソリューションを築いているユーザーが多く存在します。

もし、複雑な問題に直面している、マルチクラウドの環境のセキュリティ機能を探している、コストを削減したい、などお悩みでしたら、私にご連絡ください：(maoba@cloudflare.com)

私たちが良い解決法をご提供します。あなたを助けるために私たちはここにいるのです。

3 分で読了

本日、CloudflareのクライアントレスWeb分離のベータ版を発表いたします。これはブラウザの分離の新しいオンランプで、Zero Trust Network Access（ZTNA）とゼロデイ、フィッシング、データ損失防止をネイティブに統合し、あらゆるデバイスであらゆるWebサイト、社内アプリ、SaaSアプリケーションを閲覧するユーザーに対してリモートブラウジングの利点を提供します。エンドポイントデバイスにソフトウェアをインストールしたり、証明書を設定したりする必


leSystem = fileSystem;
            _valueFilePath = valueFilePath;

            if (!_fileSystem.FileExists(_valueFilePath))
            {
                _fileSystem.CreateDirectory(_valueFilePath.GetParent());
                WriteValueFile(initialValue);
            }
        }

        /// <summary>
        ///     Reads the value from the marker file. Returns 0 is the marker does not exist.
        /// </summary>
        public int ReadValueFile()
        {
            int valueRead = 0;
            if (_fileSystem.FileExists(_valueFilePath))
            {
                valueRead = BitConverter.ToInt32(_fileSystem.ReadAllBytes(_valueFilePath), 0);
            }

            return valueRead;
        }

        /// <summary>
        ///     Writes the given value number to the marker file.
        /// </summary>
        /// <param name="newValue">Value to write into the marker file.</param>
        public void WriteValueFile(int newValue)
        {
            Contract.Requires(newValue >= 0); // Allow writes of value 0 for tests

            _fileSystem.WriteAllBytes(_valueFilePath, BitConverter.GetBytes(newValue));
        }
    }
}


      children: <Widget>[
              const BottomSheetHeader(
                label: 'Oh no!',
              ),
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  "We're so sorry, something broke. A bug report was anonymously sent, but you can email us too!",
                  style: GentleText.introBody,
                ),
              ),
              const SizedBox(height: 24),
              Transform.rotate(
                angle: angle * pi / 180,
                child: Container(
                  width: double.infinity,
                  margin: const EdgeInsets.symmetric(horizontal: 8.0),
                  decoration: BoxDecoration(
                      border: Border.all(
                        color: Palette.graySecondary,
                        width: 1,
                      ),
                      borderRadius: BorderRadius.circular(8.0),
                      color: Palette.white,
                      boxShadow: const [
                        GentleShadow.basic,
                      ]),
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        '${provider.exception.runtimeType}',
                        style: GentleText.errorReportSubTitle,
                      ),
                      const SizedBox(height: 4),
                      Text(exception.toVisibleString(),
                          style: GentleText.errorReportLabel),
                    ],
                  ),
                ),
              ),
              const SizedBox(
                height: 104,
              ),
            ],
          ),
        ),
        Positioned(
          bottom: 24 + MediaQuery.of(context).padding.bottom,
          right: 24,
          child: FloatingDoneButton(
            label: 'Contact Gentle',
            icon: const AssetImage('assets/images/icons/24x24/shield.png'),
            onPressed: () {
              provider.launchEmail();
            },
            bgColor: Palette.offBlack,
          ),
        ),
      ],
    );
  }
}
import 'package:gentle/constants.dart';
import 'package:gentle/theme.dart';
import 'package:flutter/material.dart';
import 'package:simple_animations/simple_animations.dart';

class DotParticle extends StatelessWidget {
  final Offset offset;
  final Duration delay;

  const DotParticle({
    Key key,
    this.offset = Offset.zero,
    this.delay = Duration.zero,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final tween = MultiTrackTween([
      Track<double>('opacity')
          .add(const Duration(milliseconds: 2000), Tween(begin: 0.0, end: 1.0),
              curve: Curves.easeInOutCirc)
          .add(const Duration(milliseconds: 3000), ConstantTween(1.0))
          .add(const Duration(milliseconds: 2000), Tween(begin: 1.0, end: 0.0),
              curve: Curves.easeInOutCirc)
          .add(const Duration(milliseconds: 3000), ConstantTween(0.0))
    ]);

    return ControlledAnimation(
      delay: delay,
      duration: Constants.particleDuration,
      tween: tween,
      playback: Playback.LOOP,
      builder: (_, Map<String, dynamic> animation) {
        return Positioned(
          left: offset.dx,
          top: offset.dy,
          child: Opacity(
            opacity: animation['opacity'] as double,
            child: CustomPaint(
              painter: _DotParticlePainter(),
              child: const SizedBox(
                width: _DotParticlePainter.dotRadius * 2,


 ...ast.LambdaNode)
```

Returns: [CombineNode](/kapacitor/v1/reference/nodes/combine_node/)

### Count

Count the number of points.

```js
barrier|count(field string)
```

Returns: [InfluxQLNode](/kapacitor/v1/reference/nodes/influx_q_l_node/)

### CumulativeSum

Compute a cumulative sum of each point that is received.
A point is emitted for every point collected.

```js
barrier|cumulativeSum(field string)
```

Returns: [InfluxQLNode](/kapacitor/v1/reference/nodes/influx_q_l_node/)

### Deadman

Helper function for creating an alert on low throughput, a.k.a. deadman's switch.

- Threshold: trigger alert if throughput drops below threshold in points/interval.
- Interval: how often to check the throughput.
- Expressions: optional list of expressions to also evaluate. Useful for time of day alerting.

Example:

```js
    var data = stream
        |from()...
    // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
    data
        |deadman(100.0, 10s)
    //Do normal processing of data
    data...
```

The above is equivalent to this example:

```js
    var data = stream
        |from()...
    // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
    data
        |stats(10s)
            .align()
        |derivative('emitted')
            .unit(10s)
            .nonNegative()
        |alert()
            .id('node \'stream0\' in task \'{{ .TaskName }}\'')
            .message('{{ .ID }} is {{ if eq .Level "OK" }}alive{{ else }}dead{{ end }}: {{ index .Fields "emitted" | printf "%0.3f" }} points/10s.')
            .crit(lambda: "emitted" <= 100.0)
    //Do normal processing of data
    data...
```

The `id` and `message` alert properties can be configured globally via the 'deadman' configuration section.

Since the [AlertNode](/kapacitor/v1/reference/nodes/alert_node/) is the last piece it can be further modified as usual.
Example:

```js
    var data = stream
        |from()...
    // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
    data
        |deadman(100.0, 10s)
            .slack()
            .channel('#dead_tasks')
    //Do normal processing of data
    data...
```

You can specify additional lambda expressions to further constrain when the deadman's switch is triggered.
Example:

```js
    var data = stream
        |from()...
    // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
    // Only trigger the alert if the time of day is between 8am-5pm.
    data
        |deadman(100.0, 10s, lambda: hour("time") >= 8 AND hour("time") <= 17)
    //Do normal processing of data
    data...
```

```js
barrier|deadman(threshold float64, interval time.Duration, expr ...ast.LambdaNode)
```

Returns: [AlertNode](/kapacitor/v1/reference/nodes/alert_node/)

### Default

Create a node that can set defaults for missing tags or fields.

```js
barrier|default()
```

Returns: [DefaultNode](/kapacitor/v1/reference/nodes/default_node/)

### Delete

Create a node that can delete tags or fields.

```js
barrier|delete()
```

Returns: [DeleteNode](/kapacitor/v1/reference/nodes/delete


Xml(
                    // this.RmsChannels, // sessioninfo.Channels,
                    channel,
                    strBarcode,
                    out strReaderXml,
                    out strOutputPath,
                    out baTimestamp,
                    out strError);

            }
            finally
            {
                this.App.ReaderLocks.UnlockForRead(strBarcode);
#if DEBUG_LOCK_READER
                this.App.WriteErrorLog("LossOneReaderInfo 结束为读者加读锁 '" + strBarcode + "'");
#endif

            }

            if (nRet == -1)
                return -1;
            if (nRet > 1)
            {
                strError = "条码号 " + strBarcode + "在读者库群中检索命中 " + nRet.ToString() + " 条，请尽快更正此错误。";
                return -1;
            }

            if (nRet == 0)
            {
                // 记录既然不存在，就没有必要挂失
                strError = "读者记录不存在";
                return 1;
            }

            string strAction = "";
            string strRecPath = "";

            string strNewXml = "";  // 修改后的记录

            // 记录存在

            Debug.Assert(nRet == 1, "");
            // 命中，修改后覆盖原记录

            strAction = "change";
            strRecPath = strOutputPath;

            XmlDocument readerdom = new XmlDocument();
            try
            {
                readerdom.LoadXml(String.IsNullOrEmpty(strReaderXml) == false ? strReaderXml : "<root />");
            }
            catch (Exception ex)
            {
                strError = "读者XML记录装入DOM发生错误: " + ex.Message;
                return -1;
            }

            string strOldOuterValue = DomUtil.GetElementOuterXml(readerdom.DocumentElement,
                "state");
            DomUtil.SetElementText(readerdom.DocumentElement,
                "state", "挂失 (" + strLossDate + ")");
            string strNewOuterValue = DomUtil.GetElementOuterXml(readerdom.DocumentElement,
                "state");

            if (strOldOuterValue == strNewOuterValue) // 没有发生修改，没有必要写入
            {
                strError = "记录没有发生修改";
                return 1;
            }

            // 修改读者记录
            {
                string strExistingXml = "";
                string strSavedXml = "";
                string strSavedRecPath = "";
                byte[] baNewTimestamp = null;
                DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue kernel_errorcode = DigitalPlatform.rms.Client.rmsws_localhost.ErrorCodeValue.NoError;

                strNewXml = readerdom.OuterXml;

                LibraryServerResult result = this.App.SetReaderInfo(
                        sessioninfo,
                        strAction,
                        strRecPath,
                        strNewXml,
                        strReaderXml,
                        baTimestamp,
                        out strExistingXml,
                        out strSavedXml,
                        out strSavedRecPath,
                        out baNewTimestamp,
                        out kernel_errorcode);
                if (result.Value == -1)
                {
                    strError = result.ErrorInfo;
                    return -1;
                }
            }

            strError = "正常写入";
            return 0;   // 正常写入了
        }

#if NOOOOOOOOOOOOOOOOOOOOOOOOOO
        static string GetAccStatusString(string strAccStatus)
        {
            if (strAccStatus == "0")
                return "已撤户";
            if (strAccStatus == "1")
                return "有效卡";
            if (strAccStatus == "2")
                return "挂失卡";
            if (strAccStatus == "3")
                return "冻结卡";
            if (strAccStatus == "4")
                return "预撤户";
            return strAccS


),
                makeLightningPart(820_000.msat)
            ),
            status = LightningOutgoingPayment.Status.Succeeded(
                preimage = randomBytes32(),
                completedAt = 1675289814498
            ),
            createdAt = currentTimestampMillis()
        )
        val metadata = makeMetadata(
            exchangeRate = 23686.60,
            userNotes = null
        )

        val expected = "date,id,type,amount_msat,amount_fiat,fee_credit_msat,mining_fee_sat,mining_fee_fiat,service_fee_msat,service_fee_fiat,payment_hash,tx_id,destination,description\n" +
                "2023-02-01T22:16:54.498Z,d8ca850a-4406-4ebe-a4a8-be73553f589b,legacy_swap_out,-12820000,3.0366 USD,0,2820,0.6679 USD,0,0.0000 USD,,,tb1qlywh0dk40k87gqphpfs8kghd96hmnvus7r8hhf,\n"
        csvWriter.add(payment, metadata)
        val actual = csvWriter.dumpAndClear()

        assertEquals(expected, actual)
    }

    @Test
    fun testRow_Outgoing_ChannelClose() {
        val payment = ChannelCloseOutgoingPayment(
            id = UUID.fromString("861b22e3-b584-493a-ab5a-55512d3b3228"),
            recipientAmount = 8_690.sat,
            address = "tb1qz5gxe2450uadavle8wwcc5ngquqfj5xp4dy0ja",
            isSentToDefaultAddress = false,
            miningFee = 1_400.sat,
            channelId = randomBytes32(),
            txId = TxId("343a4bfa6531a2e06757908ff70ba53bec23a922da6335d0cff2bfafa2360805"),
            createdAt = 1675353533694,
            confirmedAt = 1675353533694,
            lockedAt = null,
            closingType = ChannelClosingType.Mutual,
        )
        val metadata = makeMetadata(
            exchangeRate = 23662.59,
            userNotes = null
        )

        val expected = "date,id,type,amount_msat,amount_fiat,fee_credit_msat,mining_fee_sat,mining_fee_fiat,service_fee_msat,service_fee_fiat,payment_hash,tx_id,destination,description\n" +
                "2023-02-02T15:58:53.694Z,861b22e3-b584-493a-ab5a-55512d3b3228,channel_close,-10090000,2.3875 USD,0,1400,0.3312 USD,0,0.0000 USD,,343a4bfa6531a2e06757908ff70ba53bec23a922da6335d0cff2bfafa2360805,tb1qz5gxe2450uadavle8wwcc5ngquqfj5xp4dy0ja,\n"
        csvWriter.add(payment, metadata)
        val actual = csvWriter.dumpAndClear()

        assertEquals(expected, actual)
    }

    /**
     * The only thing the CsvWriter reads from a PaymentRequest is the paymentHash.
     * So everything else can be fake.
     */
    private fun makePaymentRequest() =
        Bolt11Invoice.create(
            chain = Chain.Testnet3,
            amount = 10_000.msat,
            paymentHash = randomBytes32(),
            privateKey = PrivateKey(value = ByteVector32.fromValidHex("8aca84879c0d7517445ecaf399b427d1e79ecc55e9bfe2421e227679993c461e")),
            description = Either.Left("fake invoice"),
            minFinalCltvExpiryDelta = CltvExpiryDelta(128),
            features = TestConstants.Bob.nodeParams.features,
            paymentSecret = randomBytes32(),
            paymentMetadata = null,
            expirySeconds = null,
            extraHops = listOf(),
            timestampSeconds = currentTimestampSeconds()
        )

    private fun makeLightningPart(amount: MilliSatoshi) =
        LightningOutgoingPayment.Part(
            id = UUID.randomUUID(),


.itemCardPrefab;
    local itemContainer = self:_PickItemContainer(idx);
    local itemCard = CS.UnityEngine.GameObject.Instantiate(prefab, itemContainer);

    viewModel:LoadGameData(item.id, item.type);
    viewModel.itemCount = item.count;
    itemCard:Render(idx, viewModel);
    itemCard.isCardClickable = true;
    itemCard.showItemNum = true;
    self:AsignDelegate(itemCard, "onItemClick", self._HandleItemClicked);
    local scaler = itemCard:GetComponent("Torappu.UI.UIScaler");
    if scaler then
      scaler.scale = LoginOnlyConst.ITEM_CARD_SCALE;
    end

    table.insert(self.m_itemList, itemCard);
  end
end

function LoginOnlyDlg:_PickItemContainer(index)
  if (self.m_itemContainerList == nil) then
    local rectTransList = self._panelItemContainers:GetComponentsInChildren(typeof(CS.UnityEngine.RectTransform));
    self.m_itemContainerList = {};

    for i = 1, rectTransList.Length - 1 do
      table.insert(self.m_itemContainerList, rectTransList[i]);
    end
  end

  if (#self.m_itemContainerList == 0) then
    return nil
  end

  local containerIndex = (index - 1) % #self.m_itemContainerList + 1;
  return self.m_itemContainerList[containerIndex];
end

function LoginOnlyDlg:_HandleGetReward()
  if CS.Torappu.UI.UISyncDataUtil.instance:CheckCrossDaysAndResync() then
    return;
  end

  UISender.me:SendRequest(
    LoginOnlyServiceCode.GET_REWARD,
    {
      activityId = self.m_activityId
    },
    {
      hideMask = true,
      onProceed = Event.Create(self, self._HandleGetRewardResponse)
    }
  );
end

function LoginOnlyDlg:_HandleGetRewardResponse(response)
  CS.Torappu.Activity.ActivityUtil.DoShowGainedItems(response.reward);

  self:_RefreshUI();
end

function LoginOnlyDlg:_HandleItemClicked(index)
  if (index <= 0 or index > #self.m_itemList) then
    return;
  end

  local itemCard = self.m_itemList[index];
  CS.Torappu.UI.UIItemDescFloatController.ShowItemDesc(itemCard.gameObject, itemCard.model);
end


verride fun getCenterPixel(): ch.bailu.aat_lib.util.Point {
        return center ?: return ch.bailu.aat_lib.util.Point(0,0)
    }

    override fun isVisible(box: BoundingBoxE6): Boolean {
        return doOverlap(box, BoundingBoxE6(bounding))
    }

    override fun isVisible(point: LatLongInterface): Boolean {
        return bounding.contains(
            toD(point.getLatitudeE6()),
            toD(point.getLongitudeE6())
        )
    }

    override fun toMapPixels(box: BoundingBoxE6): Rect {
        val rect = Rect()
        val tl = toPixel(LatLongE6(box.latNorthE6, box.lonWestE6).toLatLong())
        val br = toPixel(LatLongE6(box.latSouthE6, box.lonEastE6).toLatLong())
        rect.left = tl.x
        rect.right = br.x
        rect.bottom = br.y
        rect.top = tl.y
        return rect
    }

    override fun toPixel(tp: LatLongInterface): ch.bailu.aat_lib.util.Point {
        return toPixel(toLatLong(tp))
    }

    override fun toPixel(p: LatLong): ch.bailu.aat_lib.util.Point {
        val y = MercatorProjection.latitudeToPixelY(p.getLatitude(), zoom, tileSize)
        val x = MercatorProjection.longitudeToPixelX(p.getLongitude(), zoom, tileSize)
        tl?.apply {
            return ch.bailu.aat_lib.util.Point(x - this.x, y - this.y)
        }

        return ch.bailu.aat_lib.util.Point(0, 0)
    }

    override fun fromPixel(x: Int, y: Int): LatLong? {
        return mapView.mapViewProjection.fromPixels(x.toDouble(), y.toDouble())
    }

    override fun getBoundingBox(): BoundingBox {
        return bounding
    }

    override fun getZoomLevel(): Int {
        return zoom.toInt()
    }
}
package ch.bailu.aat_lib.service.cache

import ch.bailu.aat_lib.util.Rect

class Span {
    private var deg: Int
    private var firstPixel: Int
    private var lastPixel: Int

    constructor() {
        deg = -1
        firstPixel = 0
        lastPixel = -1
    }

    constructor(s: Span) {
        deg = s.deg
        firstPixel = s.firstPixel
        lastPixel = s.lastPixel
    }

    fun firstPixelIndex(): Int {
        return firstPixel
    }

    fun lastPixelIndex(): Int {
        return lastPixel
    }

    fun deg(): Int {
        return deg
    }

    fun pixelDim(): Int {
        if (lastPixel >= firstPixel) {
            return lastPixel - firstPixel + 1
        }
        return 0
    }

    fun incrementAndCopyIntoArray(spanArray: ArrayList<Span>, pixelIndex: Int, deg: Int) {
        lastPixel = pixelIndex

        if (deg != this.deg) {
            copyIntoArray(spanArray)

            this.deg = deg
            firstPixel = pixelIndex
        }
    }

    fun copyIntoArray(l: ArrayList<Span>) {
        if (pixelDim() > 0) l.add(Span(this))
    }

    companion object {
        fun toRect(laSpan: Span, loSpan: Span): Rect {
            val r = Rect()
            r.top = laSpan.firstPixel
            r.bottom = laSpan.lastPixel
            r.left = loSpan.firstPixel
            r.right = loSpan.lastPixel
            return r
        }
    }
}
package ch.bailu.aat_lib.service.cache

import ch.bailu.aat_lib.app.AppContext
import ch.bailu.aat_lib.broadcaster.AppBroadcaster
import ch.bailu.aat_lib.logger.AppLog


Letter(letter, fasterDriver)
            } else {
                animateLetter(letter, slowerDriver)
            }
        })

        fasterDriver.start()
        slowerDriver.start()
        return EventSourceToPromise(slowerDriver.onCompleted())
    }

    letterAtIndex(index: number): LetterInformation | void {
        if (index >= 0 && index < this.letters.length) {
            return this.letters[index]
        }
        return undefined
    }
}

export {
    Letters
}import * as compression from 'compression';
import * as express from 'express';
import * as zlib from 'zlib';

export function getCompressMethod(request: express.Request) {
  // prefer gzip
  if (request.acceptsEncodings(['gzip'])) {
    return { func: zlib.gzip, name: 'gzip' };
  } else if (request.acceptsEncodings(['deflate'])) {
    return { func: zlib.deflate, name: 'deflate' };
  } else if (request.acceptsEncodings(['br'])) {
    return { func: zlib.brotliCompress, name: 'br' };
  }
  return undefined;
}

export function setCompressHeader(response, method, zipHtml) {
  response.setHeader('Content-Encoding', method);
  response.setHeader('Content-type', 'text/html; charset=utf-8');
  response.setHeader('Vary', 'Accept-Encoding');
  response.setHeader('Content-Length', zipHtml.length.toString());
}

export function getCompressStaticFilter() {
  const isStatic = new RegExp('.(?:js|css)$');
  return function filter(req, res) {
    if (!isStatic.test(req.url)) {
      // don't compress responses with this request header
      return false;
    }
    // fallback to standard filter function
    return compression.filter(req, res);
  };
}
import { CmdCategory } from '@prisma/client';
import { balloonProvider } from '../../data/providers/balloonProvider';
import {
  baseEmbed,
  lightErrorEmbed,
  sendNotInGuild,
} from '../../shared/embeds';
import { Command } from '../../types/command';

const balloonMax = new Command({
  name: 'balloon-max',
  aliases: ['bl-max'],
  category: CmdCategory.GAMES,
  description:
    "Check or set the upper bound for balloons' volumes in this server.",
  args: [{ name: 'new_max', optional: true }],
  async execute(message, args) {
    const { channel, guild } = message;
    if (!guild) {
      sendNotInGuild(channel);
      return;
    }
    const [_newMax] = args;
    if (!_newMax) {
      const currMax = await balloonProvider.getMax(guild.id);
      channel.send(
        baseEmbed().setDescription(`Current max volume: **${currMax}**`),
      );
      return;
    }
    const newMax = parseInt(_newMax, 10);
    if (Number.isNaN(newMax)) {
      channel.send(lightErrorEmbed(`Please give me a valid number!`));
      return;
    }
    const currMin = await balloonProvider.getMin(guild.id);
    if (newMax < currMin) {
      channel.send(
        lightErrorEmbed(
          `The current min is **${currMin}**.

          Please set a max below that, or lower the min.`,
        ),
      );
      return;
    }
    if (newMax <= 0) {
      channel.send(
        lightErrorEmbed('Volume is a *non-negative scalar*  ლ(´ڡ`ლ)'),
      );
      return;
    }
    await balloonProvider.setMax(newMax, guild.id);
    channel.send(
      baseEmbed().setDescription(
        `The maximum ball


9f1bd2d159857671da73de894d6c9">  322   using PartitionShape = typename Base::PartitionShape;

  323

  324   //

  325   // Static constants

  326   //

  327

  328   static int const kElementSize = Base::kElementSize;

  329   static int const kElementsPerAccess = Base::kElementsPerAccess;

  330   using PartitionCount =  typename Base::PartitionCount;

  331   <span class="keywor


",warn_save:"Saved in browser (you are not logged)",unable_to_save:"Unable to save",not_premium:"Subscribe",copy_net_link:"Share this link to connect",copied:"Copied",image_rendering:"Image rendering",read_only_access:"Win 9x emulation is in READ ONLY mode",fix:"Fix",close:"Close",cancle:"Cancle",manage:"Manage",unable_to_cancle_subscription:"Unable to cancle subscription",subscription_cancelled:"Subscription cancelled",hardware:"Hardware acceleration",net_drives:"Net drives",fat_write:"Writeable FAT",no_cloud_access:"Please enter",no_cloud_access2:"to use cloud storage",key:"your key",sockdrive_native:"Native drives"},pt:{hello:"Olá",hello_guest:"Olá, convidado!",play:"Iniciar",system_cursor:"Cursor do sistema",mobile_controls:"Controles móveis",mirrored_controls:"Controles espelhados",scale_controls:"Escalar controles",enter_name_of_drive:"Digite o nome da unidade",ws_outdated:"Você precisa atualizar o aplicativo DOS Browser",update:"Atualizar",preloading_sockdrive:"Carregando",filter:"Filtrar",add:"Adicionar",logout:"Sair",features:"Recursos",premium:"Assinatura",buy:"Comprar",experimental_features:"Acesso a todos os recursos experimentais",cloud_saves:"Salvamentos em nuvem",writeable_fat32:"FAT32 gravável",net_no_limits:"Alterar a região da rede",unlock_options:"Desbloquear todas as opções de configuração",error:"Oops... Algo deu errado...",consult_logs:"Por favor, verifique os logs do navegador",bundle_loading:"Carregando pacote",bundle_config:"Lendo configuração",try_free:"dias grátis",upload_file:"Selecione um arquivo jsdos/zip para iniciar...",emulation_backend:"Emulador",render_backend:"Renderização",render_aspect:"Aspecto",worker:"Thread de trabalho",mouse_sensitivity:"Sensibilidade do mouse...",mouse_lock:"Capturar mouse",volume:"Volume",pause:"Pausar",dosboxconf_template:"Modelo dosbox.conf:",preview:"Pré-visualizar",continue:"Continuar",skip:"Pular",loading:"Carregando",extract_loading:"Extraindo arquivo",extract_long_time:"Pode levar algum tempo, por favor, seja paciente...",theme:"Tema",create_empty:"Criar pacote vazio",uploading_file:"Enviando arquivo",fs_restart:"Você deseja reconstruir o pacote usando este sistema de arquivos?",please_wait:"Por favor, aguarde",making_bundle:"Criando pacote",size:"Tamanho",room:"Sala",server:"Servidor",load_by_url:"Carregar por URL",enter_url:"Digite a URL",load:"Carregar",stored:"Armazenado",delete:"Excluir",editor:"Editor",download:"Download",changes:"Salvamentos",loading_saves:"Carregando salvamentos",success:"Sucesso",success_save:"Salvo na nuvem",warn_save:"Salvo no navegador (você não está conectado)",unable_to_save:"Não foi possível salvar",not_premium:"Assine",copy_net_link:"Compartilhe este link para se conectar",copied:"Copiado",image_rendering:"Renderização de imagem",read_only_access:"A emulação do Win 9x está no modo SOMENTE LEITURA",fix:"Corrigir",close:"Fechar",cancle:"Cancelar",manage:"Gerenciar",unable_to_cancle_subscription:"Não foi po


38,          /* Safer Mode Extensions */
    EST = 39,          /* Enhanced SpeedStep */
    TM2 = 40,          /* Thermal Monitor 2 */
    SSSE3 = 41,        /* Supplemental SSE3 instructions */
    CNXT_ID = 42,      /* L1 Context ID */
    SDBG = 43,         /* Silicon Debug Interface */
    FMA = 44,          /* Fused Multiply-Add */
    CX16 = 45,         /* CMPXCHG16B instruction */
    XTPR = 46,         /* Task priority message disable */
    PDCM = 47,         /* Performance monitoring and debugging capabilities */
    PCID = 49,         /* Process Context IDs */
    DCA = 50,          /* DMA Direct Cache Access */
    SSE4_1 = 51,       /* SSE 4.1 instructions */
    SSE4_2 = 52,       /* SSE 4.2 instructions */
    X2_APIC = 53,      /* x2APIC */
    MOVBE = 54,        /* MOVBE instruction */
    POPCNT = 55,       /* POPCNT instruction */
    TSC_DEADLINE = 56, /* APIC TSC Deadline capability */
    AES = 57,          /* AES instructions */
    XSAVE = 58,        /* XSAVE etc. instructions */
    OS_XSAVE = 59,     /* XSAVE enabled by OS */
    AVX = 60,          /* AVX instructions */
    F16C = 61,         /* Half-precision floating point */
    RDRND = 62,        /* on-chip RNG */
    HYPERVISOR = 63,   /* Hypervisor present */

    /* Extended EDX feature flags (64 - 95) */
    SYSCALL = 75,   /* SYSCALL / SYSRET instructions (EDX, bit 11) */
    NX = 84,        /* No-Execute bit (EDX, bit 20) */
    GB_PAGES = 90,  /* Gibibyte page support (EDX, bit 26) */
    RDTSCP = 91,    /* RDTSCP instruction (EDX, bit 27) */
    LONG_MODE = 93, /* Long mode support (EDX, bit 29) */

    /* Extended ECX feature flags (96 - 127) */
    LAHF = 96, /* LAHF / SAHF instructions (ECX, bit 0) */
}

impl FeatureFlags {
    pub fn supported(self) -> bool {
        check_feature(self)
    }
}

fn cpuid(in_eax: u32) -> (u32, u32, u32, u32) {
    let eax: u32;
    let ebx: u32;
    let ecx: u32;
    let edx: u32;

    unsafe {
        llvm_asm!("cpuid" : "={eax}"(eax), "={ebx}"(ebx), "={ecx}"(ecx), "={edx}"(edx) : "0"(in_eax) :: "volatile");
    }

    (eax, ebx, ecx, edx)
}
<gh_stars>0
// Websocket based on actix example https://github.com/actix/examples/blob/0.7/websocket/src/main.rs

use crate::models::*;
use actix::prelude::*;
use actix_http::ws::Item;
use actix_web_actors::ws;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use uuid::Uuid;

const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
const CLIENT_TIMEOUT: Duration = Duration::from_secs(30);

pub struct EventWebSocket {
    pub heartbeat: Instant,
    pub event_id: Uuid,
    clients: Arc<Mutex<HashMap<Uuid, Vec<Addr<EventWebSocket>>>>>,
}

impl Actor for EventWebSocket {
    type Context = ws::WebsocketContext<Self>;

    fn started(&mut self, context: &mut Self::Context) {
        self.heartbeat(context);
    }
}

impl EventWebSocket {
    pub fn


s = (1..(num_columns * chunk.len()) + 1)
                .map(|i| format!("${}", i.to_string()))
                .collect::<Vec<String>>()
                .chunks(num_columns)
                .map(|x| x.join(", "))
                .join("), (");
            let stmt = tx.prepare(&format!(
                "
INSERT INTO bigmap_keys (
    tx_context_id, bigmap_id, keyhash, key
)
Values ({})",
                v_refs
            ))?;

            let values: Vec<&dyn postgres::types::ToSql> = chunk
                .iter()
                .flat_map(|(tx_context, bigmap_id, keyhash, key)| {
                    [
                        tx_context.id.borrow_to_sql(),
                        bigmap_id.borrow_to_sql(),
                        keyhash.borrow_to_sql(),
                        key.borrow_to_sql(),
                    ]
                })
                .collect();

            tx.query_raw(&stmt, values)?;
        }
        Ok(())
    }

    pub(crate) fn save_tx_contexts(
        tx: &mut Transaction,
        tx_contexts: &[TxContext],
    ) -> Result<()> {
        struct TxContextPG {
            id: i64,
            pub level: i32,
            pub contract: String,
            pub operation_group_number: i32,
            pub operation_number: i32,
            pub content_number: i32,
            pub internal_number: Option<i32>,
        }
        for chunk in tx_contexts.chunks(Self::INSERT_BATCH_SIZE) {
            let num_columns = 7;
            let v_refs = (1..(num_columns * chunk.len()) + 1)
                .map(|i| format!("${}", i.to_string()))
                .collect::<Vec<String>>()
                .chunks(num_columns)
                .map(|x| x.join(", "))
                .join("), (");
            let stmt = tx.prepare(&format!(
                "
INSERT INTO tx_contexts(
    id,
    level,
    contract,
    operation_group_number,
    operation_number,
    content_number,
    internal_number
)
VALUES ( {} )",
                v_refs
            ))?;

            let tx_contexts_pg: Vec<TxContextPG> = chunk
                .iter()
                .map(|tx_context| TxContextPG {
                    id: tx_context
                        .id
                        .ok_or_else(|| anyhow!("Missing ID on TxContext"))
                        .unwrap(),
                    level: tx_context.level as i32,
                    contract: tx_context.contract.clone(),
                    operation_group_number: tx_context.operation_group_number
                        as i32,
                    operation_number: tx_context.operation_number as i32,
                    content_number: tx_context.content_number as i32,
                    internal_number: tx_context
                        .internal_number
                        .map(|n| n as i32),
                })
                .collect();
            let values: Vec<&dyn postgres::types::ToSql> = tx_contexts_pg
                .iter()
                .flat_map(|tx_context| {
                    [
                        tx_context.id.borrow_to_sql(),
                        tx_context.level.borrow_to_sql(),
                        tx_context.contract.borrow_to_sql(),
                        tx_context
                            .operation_group_number
                            .borrow_to_sql(),
                        tx_context
                            .operation_number
                            .borrow_to_sql(),
                        tx_context
                            .content_number
                            .borrow_to_sql(),
                        tx_context
                            .internal_number
                            .borrow_to_sql(),
                    ]
                })


2.len(), 1);

        assert_eq!(proof1, proof2);
    }

    #[test]
    fn get_storage_proof() {
        let mut state = get_temp_state();
        let a: Address = 1000.into();
        let b: Address = 2000.into();
        let c: Address = 3000.into();
        state.new_contract(&a, 5.into(), 0.into(), vec![10u8, 20, 30, 40, 50]);
        state.set_storage(&a, 10.into(), 10.into()).unwrap();
        state.new_contract(&b, 5.into(), 0.into(), vec![10u8, 20, 30, 40, 50]);
        state.commit().unwrap();

        // account not exist
        let proof = state.get_storage_proof(&c, &10.into()).unwrap();
        assert_eq!(proof.len(), 0);

        // account who has empty storage trie
        let proof = state.get_storage_proof(&b, &10.into()).unwrap();
        assert_eq!(proof.len(), 0);

        // account and storage key exists
        let proof1 = state.get_storage_proof(&a, &10.into()).unwrap();
        assert_eq!(proof1.len(), 1);

        // account exists but storage key not exist
        let proof2 = state.get_storage_proof(&a, &20.into()).unwrap();
        assert_eq!(proof2.len(), 1);

        assert_eq!(proof1, proof2);
    }
}
pub fn handle() {

}<filename>boa/src/syntax/parser/statement/iteration/mod.rs
mod do_while_statement;
mod for_statement;
#[cfg(test)]
mod tests;
mod while_statement;

pub(super) use self::{
    do_while_statement::DoWhileStatement, for_statement::ForStatement,
    while_statement::WhileStatement,
};
use crate::{MemoryUsage, MemoryUsageTracker};
use std::marker::PhantomData;

impl<T> MemoryUsage for PhantomData<T> {
    fn size_of_val(&self, _: &mut dyn MemoryUsageTracker) -> usize {
        0
    }
}
<reponame>imor/wasm-tools
use super::*;
use std::convert::TryFrom;

impl Module {
    /// Encode this Wasm module into bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.inner.to_bytes()
    }
}

impl<C> ConfiguredModule<C>
where
    C: Config,
{
    /// Encode this Wasm module into bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.encoded().finish()
    }

    fn encoded(&self) -> wasm_encoder::Module {
        let mut module = wasm_encoder::Module::new();

        self.encode_initializers(&mut module);
        self.encode_funcs(&mut module);
        self.encode_tables(&mut module);
        self.encode_memories(&mut module);
        self.encode_globals(&mut module);
        self.encode_exports(&mut module);
        self.encode_start(&mut module);
        self.encode_elems(&mut module);
        self.encode_data_count(&mut module);
        self.encode_code(&mut module);
        self.encode_data(&mut module);

        module
    }

    fn encode_initializers(&self, module: &mut wasm_encoder::Module) {
        for init in self.initial_sections.iter() {
            match init {
                InitialSection::Type(types) => self.encode_types(module, types),
                InitialSection::Import(imports) => self.encode_imports(module, imports),
                InitialSection::Alias(aliases) => self.encode_aliases(module, aliases),
                InitialSection::Instance(list) => self.encode_instances(module, list),
                InitialSection::Module(


.size} inputs")
            val parentTxId = input.outPoint.txid
            log.debug("retrieving parent_tx {}", parentTxId)
            val parentTx = electrumClient.getTx(input.outPoint.txid) ?: throw RuntimeException("parent tx=$parentTxId not found by electrum")

            // select correct output
            val txOut = parentTx.txOut[tx.txIn.first().outPoint.index.toInt()]

            // swap-in protocol
            val addressIndex = (0..1_000).indexOfFirst { i ->
               keyManager.swapInOnChainWallet.getSwapInProtocol(i).serializedPubkeyScript == txOut.publicKeyScript
            }
            if (addressIndex == -1) {
                log.error("(taproot) cannot find address index")
                state.value = TaprootSwapInSignerState.Failed.AddressIndexNotFound
                return@launch
            }
            val swapInProtocol = keyManager.swapInOnChainWallet.getSwapInProtocol(addressIndex)

            // generate nonce
            val (userPrivateNonce, userNonce) = try {
                Musig2.generateNonce(
                    sessionId = randomBytes32(),
                    privateKey = userPrivateKey,
                    publicKey = userPublicKey,
                    publicKeys = listOf(swapInProtocol.userPublicKey, swapInProtocol.serverPublicKey),
                    message = null,
                    extraInput = null
                )
            } catch (e: Exception) {
                log.error("(taproot) unable to generate nonce: ", e)
                state.value = TaprootSwapInSignerState.Failed.NonceGenerationFailure(e)
                return@launch
            }

            val userSig = swapInProtocol.signSwapInputUser(
                fundingTx = tx,
                index = 0,
                parentTxOuts = listOf(txOut),
                userPrivateKey = userPrivateKey,
                privateNonce = userPrivateNonce,
                userNonce = userNonce,
                serverNonce = IndividualNonce(serverNonce)
            ).toResult().getOrThrow()

            state.value = TaprootSwapInSignerState.Signed(
                txId = tx.txid.toString(),
                userKey = keyManager.swapInOnChainWallet.userPublicKey.toHex(),
                userSig = userSig.toString(),
                userRefundKey = swapInProtocol.userRefundKey.toHex(),
                userNonce = userNonce.toString(),
            )
        }
    }

    class Factory(
        private val walletManager: WalletManager,
        private val electrumClient: ElectrumClient,
    ) : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return SwapInSignerViewModel(walletManager, electrumClient) as T
        }
    }
}/*
 * Copyright 2024 ACINQ SAS
 *
 * 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.
 */

@file:Suppress("DEPRECATION")

package fr.acinq.phoenix.android.utils.extensions

import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import fr.acinq.lightning.db.AutomaticLiquidityPurchasePayment
import fr.acinq.lightning.db.Bolt11IncomingPayment
import fr.acinq.


2.77 11.52C2.83 11.67 2.9 11.81 2.99 11.94C3.08 12.08 3.18 12.2 3.3 12.32C3.41 12.43 3.54 12.54 3.67 12.63C3.8 12.72 3.95 12.79 4.09 12.86C4.24 12.92 4.4 12.96 4.55 13C4.71 13.03 4.87 13.04 5.03 13.04L5.03 14.64Z" fill="currentColor" fill-opacity="1.000000" fill-rule="evenodd"></path></g><path id="path" d="M14.75 18.91L9.3 18.91C9.03 18.91 8.77 18.88 8.51 18.83C8.25 18.78 8 18.7 7.75 18.6C7.51 18.49 7.27 18.37 7.05 18.22C6.83 18.07 6.63 17.9 6.44 17.71C6.25 17.52 6.09 17.32 5.94 17.1C5.79 16.87 5.67 16.64 5.57 16.39C5.47 16.14 5.39 15.89 5.34 15.63C5.28 15.37 5.26 15.1 5.26 14.83L5.26 9.33C5.26 9.06 5.28 8.8 5.34 8.54C5.39 8.28 5.47 8.02 5.57 7.77C5.67 7.53 5.79 7.29 5.94 7.07C6.09 6.85 6.25 6.64 6.44 6.45C6.63 6.26 6.83 6.09 7.05 5.95C7.27 5.8 7.51 5.67 7.75 5.57C8 5.47 8.25 5.39 8.51 5.34C8.77 5.29 9.03 5.26 9.3 5.26L14.75 5.26C15.01 5.26 15.28 5.29 15.54 5.34C15.8 5.39 16.05 5.47 16.29 5.57C16.54 5.67 16.77 5.8 16.99 5.95C17.21 6.09 17.41 6.26 17.6 6.45C17.79 6.64 17.96 6.85 18.1 7.07C18.25 7.29 18.37 7.53 18.48 7.77C18.58 8.02 18.65 8.28 18.71 8.54C18.76 8.8 18.78 9.06 18.78 9.33L18.78 14.83C18.78 15.1 18.76 15.37 18.71 15.63C18.65 15.89 18.58 16.14 18.48 16.39C18.37 16.64 18.25 16.87 18.1 17.1C17.96 17.32 17.79 17.52 17.6 17.71C17.41 17.9 17.21 18.07 16.99 18.22C16.77 18.37 16.54 18.49 16.29 18.6C16.05 18.7 15.8 18.78 15.54 18.83C15.28 18.88 15.01 18.91 14.75 18.91ZM9.3 6.86C9.13 6.86 8.97 6.87 8.82 6.91C8.66 6.94 8.51 6.98 8.36 7.05C8.21 7.11 8.07 7.18 7.93 7.28C7.8 7.37 7.68 7.47 7.56 7.58C7.45 7.7 7.35 7.82 7.26 7.96C7.17 8.09 7.09 8.24 7.03 8.38C6.97 8.54 6.92 8.69 6.89 8.85C6.86 9.01 6.84 9.17 6.84 9.33L6.84 14.83C6.84 15 6.86 15.16 6.89 15.32C6.92 15.48 6.97 15.63 7.03 15.78C7.09 15.93 7.17 16.07 7.26 16.21C7.35 16.34 7.45 16.47 7.56 16.58C7.68 16.7 7.8 16.8 7.93 16.89C8.07 16.98 8.21 17.06 8.36 17.12C8.51 17.18 8.6


stomer);
    //
    expect(result.mobile_no, customer.mobile_no);
  });

  test('store add the correct header to the end point when token is available',
          () async {
        const String token = 'token';
        final RemoteStoreCustomerSUT sut = _makeSUT(token: token);

        await await tryFunction(() => sut.remoteStoreCustomer.store(anyCustomer));

        expect(MockClientStub.requests.first.headers, <String, String>{
          'Content-Type': 'application/json; charset=utf-8',
          'Authorization': 'Bearer $token',
        });
      });
}import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:thepos/core/navigator/app_navigator_factory.dart';

import 'helpers.dart';

/// ideally we should decouple our tests from Get implementation,
///  maybe the better approach is to use navigatorObservers
///  instead of Get.previousRoute && Get.currentRoute
///  those tests are a fragile tests any change of Getx snackBar code may break tests
void main() {
  testWidgets(
    'offAndToNamed should pop the current widget and pushed the new one',
    (WidgetTester tester) async {
      await tester.pumpWidget(anyMaterialApp);

      expect(Get.currentRoute, AnyRoutes.ANY_ROUTE, reason: 'precondition');

      final AppNavigatorFactory sut = AppNavigatorFactory();
      sut.offAndToNamed(AnyRoutes.ANOTHER_ROUTE);

      expect(Get.previousRoute, '',
          reason: 'offAndToNamed should remove previousRoute from the stack');
      expect(Get.currentRoute, AnyRoutes.ANOTHER_ROUTE);
    },
  );

  testWidgets(
    'snackbar should show snackbar with specific message and title',
    (WidgetTester tester) async {
      await tester.pumpWidget(anyMaterialApp);

      expect(Get.currentRoute, AnyRoutes.ANY_ROUTE, reason: 'precondition');
      expect(Get.isSnackbarOpen, false, reason: 'precondition');

      final AppNavigatorFactory sut = AppNavigatorFactory();
      const String title = 'snackbar title';
      const String message = 'snackbar message';
      const Duration animationDuration = Duration(milliseconds: 50);
      sut.snackbar(
        title,
        message,
        animationDuration: animationDuration,
      );

      await tester.pump(animationDuration);

      expect(Get.isSnackbarOpen, true);
      expect(find.text(title), findsOneWidget);
      expect(find.text(message), findsOneWidget);

      Get.closeAllSnackbars(); // we need to call this to make test pass without throwing an error.
    },
  );
}
import 'package:flutter_test/flutter_test.dart';
import 'package:thepos/features/carts/data/models/cart.dart';
import 'package:thepos/features/carts/data/models/cart_item.dart';
import 'package:thepos/features/home/data/models/product.dart';
import 'package:thepos/features/invoice/data/models/invoice.dart';
import 'package:thepos/features/invoice/data/models/invoice_item.dart';

final Product anyProduct =
    Product(name: 'test name', sku: 'test sku', price: 4);

const int anyQuantity = 2;

const double sellingPrice = 2.0;

final Cart emptyCart = Cart(
  keyCart: '1',
  cartItems: <CartItem>[],
);

final Cart anyCart = Cart(
  keyCart: '1',
  cartItems: <CartItem>[CartItem(product: anyProduct, quantity: anyQuantity,
      sellingPrice: sellingPrice)],
);

final InvoiceItem anyInvoiceItem =
    InvoiceItem(product: anyProduct, quantity: anyQuantity);

final Invoice anyInvoice = Invoice(
  clientId: 0,
  items: <InvoiceItem>[anyInvoiceItem],
);

Invoice createIn


print("Hello, World!")
print("This is my first Python program.")


iples of Embedded Systems",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(283, "Digital System Design using HDL Verilog",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(284, "Basics of Power Electronics",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(285, "Industrial Robotics",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(286, "Material Handling",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(287, "Automotive Safety & Ergonomics",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(288, "Object Oriented Analysis and Design",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(289, "Multimedia",
        branchToSem: {
          "IT": ["6"]
        },
        subjectType: SubjectType.Elective),
    Subject(290, "Data Science Using R Programming",
        branchToSem: {
          "IT": ["6", '7', '8'],
          "CSE": ['7', '8'],
          'ECE': ['7'],
          'EEE': ['7'],
          'CIVIL': ['7'],
          'MECH': ['7'],
          'EIE': ['7'],
          'PE': ['7']
        },
        subjectType: SubjectType.Elective),

    //5TH SEM

    //COMMON SUBJECTS
    //* VERIFIED FOR ECE 5
    Subject(82, "GENDER SENSITIZATION", branchToSem: {
      "ECE": ["5"],
      "IT": ["5"],
      "CIVIL": ["8"]
    }),
    //* VERIFIED
    Subject(83, "OPERATING SYSTEMS", branchToSem: {
      "CSE": ["5"],
      "IT": ["5"]
    }),
    //!DELETE [EXTRA]
    // Subject(84, "MANUFACTURING PROCESSES",  ),
    // Subject(85, "DYNAMICS OF MACHINES",  ),
    //MECH
    //* VERIFIED
    Subject(378, "Automata Languages & Computation", branchToSem: {
      "MECH": ["5"],
      "AE": ["5"],
      "PE": ["5"],
      "CSE": ["5"]
    }),
    //* VERIFIED
    Subject(86, "MACHINE DESIGN", branchToSem: {
      "MECH": ["6"],
      "PE": ["6"]
    }),
    //* VERIFIED
    Subject(87, "HEAT TRANSFER", branchToSem: {
      "MECH": ["5"],
      "AE": ["5"],
    }),
    //*VERIFIED
    Subject(89, "CAD/CAM",
        branchToSem: {
          "MECH": ["6"]
        },
        subjectType: SubjectType.Elective),
    //CSE
    //!DELETE [EXTRA]
    // Subject(90, "DATABASE MANAGEMENT SYSTEMS",  ),
    // Subject(91, "DATA COMMUNICATIONS",  ),
    // Subject(88, "OPERATIONS RESEARCH",  ),
    //*VERIFIED
    // Subject(92, "AUTOMATA LANGUAGES AND COMPUTATION",branchToSem: {"CSE":["5"]}),
    //* VERIFIED
    Subject(93, "COMPUTER GRAPHICS",


s	r5, r4
	bf	3b
#endif

	mov.l	._gd_init, r13		/* global data */
	mov.l	._stack_init, r15	/* stack */
#if CONFIG_IS_ENABLED(SYS_MALLOC_F)
	mov.l	._gd_malloc_base, r14
	mov.l	r15, @r14
#endif
	mov.l	._sh_generic_init, r0
	jsr	@r0
	mov     #0, r4

loop:
	bra	loop

	.align	2

._lowlevel_init:	.long	(lowlevel_init - (100b + 4))
._reloc_dst:		.long	_start
._reloc_dst_end:	.long	reloc_dst_end
._reloc_size:		.long	(_end - _start)
._bss_start:		.long	bss_start
._bss_end:		.long	bss_end
._gd_init:		.long	(_start - GENERATED_GBL_DATA_SIZE)
#if CONFIG_IS_ENABLED(SYS_MALLOC_F)
._gd_malloc_base:	.long	(_start - GENERATED_GBL_DATA_SIZE + GD_MALLOC_BASE)
#endif
._stack_init:		.long	(_start - GENERATED_GBL_DATA_SIZE - CONFIG_SYS_MALLOC_LEN - 16)
._sh_generic_init:	.long	board_init_f


.meta name="Ultimate map fix"
.meta description="Adds missing maps\nto Ultimate for\ncertain quests"
# Patch by Matt Swift

.versions 2OEF 2OJ5 2OJF 2OPF

entry_ptr:
reloc0:
  .offsetof start
start:
  .include  WriteCodeBlocksDC

  # Modify location of Ultimate Cave 1 map pointer table to 8C008100 and make it have 6 entries
  .align    4
  .data     <VERS 0x8C32FED0 0x8C32FED0 0x8C32D638 0x8C3244A8>
  .data     6
  .binary   0081008C0600

  # Modify location of Ultimate Cave 3 map pointer table to 8C008130 and make it have 6 entries
  .align    4
  .data     <VERS 0x8C32FEE0 0x8C32FEE0 0x8C32D648 0x8C3244B8>
  .data     6
  .binary   3081008C0600

  # Modify location of Ultimate Mine 1 map pointer table to 8C008160 and make it have 6 entries
  .align    4
  .data     <VERS 0x8C32FEE8 0x8C32FEE8 0x8C32D650 0x8C3244C0>
  .data     6
  .binary   6081008C0600

  # Modify location of Ultimate Mine 2 map pointer table to 8C008190 and make it have 6 entries
  .align    4
  .data     <VERS 0x8C32FEF0 0x8C32FEF0 0x8C32D658 0x8C3244C8>
  .data     6
  .binary   9081008C0600

  # New map pointer table for Cave 1
  .align    4
  .data     0x8C008100
  .data     48
  .binary   <VERS 5704338C6304338C5704338C7204338C5704338C8104338C5704338C9004338C5704338C9F04338C5704338C0082008C 5704338C6304338C5704338C7204338C5704338C8104338C5704338C9004338C5704338C9F04338C5704338C0082008C BFDB328CCBDB328CBFDB328CDADB328CBFDB328CE9DB328CBFDB328CF8DB328CBFDB328C07DC328CBFDB328C0082008C 2F4A328C3B4A328C2F4A328C4A4A328C2F4A328C594A328C2F4A328C684A328C2F4A328C774A328C2F4A328C0082008C>

  # New map pointer table for Cave 3
  .align    4
  .data     0x8C008130
  .data     48
  .binary   <VERS 0505338C1105338C0505338C4


 index of the task, used by UIs to sort prompts and results. */
  val index: Int,
  val type: Type,
  val label: String,
  val isRequired: Boolean,
  val multipleChoice: MultipleChoice? = null,
  val isAddLoiTask: Boolean = false,
  val condition: Condition? = null,
) {

  // TODO: Define these in data layer!
  // Issue URL: https://github.com/google/ground-android/issues/2910
  // Task type names as they appear in the local db, but in uppercase. DO NOT RENAME!
  enum class Type {
    UNKNOWN,
    TEXT,
    MULTIPLE_CHOICE,
    PHOTO,
    NUMBER,
    DATE,
    TIME,
    DROP_PIN,
    DRAW_AREA,
    CAPTURE_LOCATION,
    INSTRUCTIONS,
  }
}
/*
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://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 org.groundplatform.android.usecases.datasharingterms

import javax.inject.Inject
import org.groundplatform.android.data.local.LocalValueStore
import org.groundplatform.android.proto.Survey.DataSharingTerms
import org.groundplatform.android.repository.SurveyRepository

class GetDataSharingTermsUseCase
@Inject
constructor(
  private val localValueStore: LocalValueStore,
  private val surveyRepository: SurveyRepository,
) {

  /** Returns the data sharing terms for the currently active survey, if not already accepted. */
  operator fun invoke(): Result<DataSharingTerms?> = runCatching {
    val survey = surveyRepository.activeSurvey ?: error("No active survey")
    val sharingTerms = survey.dataSharingTerms
    if (sharingTerms == null || localValueStore.getDataSharingConsent(survey.id)) {
      // User previously agreed to the terms or data sharing terms are missing.
      return Result.success(null)
    }
    if (sharingTerms.type == DataSharingTerms.Type.CUSTOM && sharingTerms.customText.isBlank()) {
      throw InvalidCustomSharingTermsException()
    }
    return Result.success(sharingTerms)
  }

  class InvalidCustomSharingTermsException : Exception()
}
package com.example.googlehomeapisampleapp

import android.content.Context
import com.example.googlehomeapisampleapp.HomeClientProvider
import com.google.home.DeviceType
import com.google.home.DeviceTypeFactory
import com.google.home.FactoryRegistry
import com.google.home.HomeClient
import com.google.home.HomeConfig
import com.google.home.Trait
import com.google.home.TraitFactory
import com.google.home.google.AreaAttendanceState
import com.google.home.google.AreaPresenceState
import com.google.home.google.Assistant
import com.google.home.google.AssistantBroadcast
import com.google.home.google.AssistantFulfillment
import com.google.home.google.GoogleDisplayDevice
import com.google.home.google.GoogleTVDevice
import com.google.home.google.Notification
import com.google.home.google.Time
import com.google.home.google.Volume
import com.google.home.matter.standard.BasicInformation
import com.google.home.matter.standard.BooleanState
import com.google.home.matter.standard.ColorTemperatureLightDevice
import com.google.home.matter.standard.ContactSensorDevice
import com.google.home.matter.standard.DimmableLightDevice
import com.google.home.matter.standard.ExtendedColorLightDevice
import com.goo


ainSpeed_thenCreatesCorrectIncomingAndOutgoing', () {
      _expectIncomingOutgoingSpeed(Speed.parse('80/[90]'), '80/[90]');
    });

    test('parse_whenThreeSpeedsWithSquare_thenCreatesThreeCorrectSpeeds', () {
      _expectIncomingOutgoingSpeed(Speed.parse('[90]/80-70'), '[90]/80-70');
    });

    test('parse_whenXX_thenCreatesSpeedWithXXValue', () {
      _expectIncomingOutgoingSpeed(Speed.parse('XX/70-60-50'), 'XX/70-60-50');
    });

    test('parse_whenXXWithWhitespaces_thenCreatesSpeedWithXXValue', () {
      _expectIncomingOutgoingSpeed(Speed.parse('XX / 70-60-50'), 'XX/70-60-50');
    });

    test('parse_whenInvalidFormat_thenThrowsFormatException', () {
      expect(() => Speed.parse('50-5gj'), throwsFormatException);
    });

    test('parse_whenLeadingSeparator_thenThrowsFormatException', () {
      expect(() => Speed.parse('/93-12'), throwsFormatException);
    });

    test('parse_whenOnlySeparator_thenThrowsFormatException', () {
      expect(() => Speed.parse('/'), throwsFormatException);
    });

    test('parse_whenInvalidCharacters_thenThrowsFormatException', () {
      expect(() => Speed.parse('87-23/ikj'), throwsFormatException);
    });

    test('toString_whenCalled_thenReturnsFormattedString', () {
      // ARRANGE
      final speed = Speed.parse('90/80');
      final expectedString =
          'IncomingOutgoingSpeed('
          'incoming: SingleSpeed(value: 90, isSquared: false, isCircled: false), '
          'outgoing: SingleSpeed(value: 80, isSquared: false, isCircled: false))';

      // ACT & EXPECT
      expect(speed.toString(), equals(expectedString));
    });

    test('equality_whenEqual_shouldReturnTrue', () {
      // ARRANGE
      final a = Speed.parse('120/60');
      final b = Speed.parse('120/60');

      // ACT & EXPECT
      expect(a, equals(b));
    });

    test('equality_whenNotEqual_shouldReturnFalse', () {
      // ARRANGE
      final a = Speed.parse('120/80');
      final b = Speed.parse('120/60');

      // ACT & EXPECT
      expect(a == b, isFalse);
    });
  });
}

void _expectIncomingOutgoingSpeed(Speed result, String expected) {
  expect(result, isA<IncomingOutgoingSpeed>());
  result as IncomingOutgoingSpeed;

  final inOutSpeeds = expected.split('/').map(Speed.parse).toList();

  expect(result.incoming, inOutSpeeds[0]);
  expect(result.outgoing, inOutSpeeds[1]);
}
import 'package:flutter_test/flutter_test.dart';
import 'package:sfera/src/model/journey/additional_speed_restriction.dart';
import 'package:sfera/src/model/journey/track_equipment_segment.dart';

void main() {
  test('test ASR is displayed outside of ETCS level 2 segments', () {
    // GIVEN
    final asr = AdditionalSpeedRestriction(kmFrom: 5.0, kmTo: 10.0, orderFrom: 500, orderTo: 1000, speed: 50);
    final etcsL1TrackEquipments = [
      _trackEquipment(TrackEquipmentType.etcsL1lsSingleTrackNoBlock, 0, 9999),
    ];

    // WHEN
    final isDisplayedOnETCSL1 = asr.isDisplayed(etcsL1TrackEquipments);
    final isDisplayedWithoutTrackEquipment = asr.isDisplayed([]);

    // THEN
    expect(isDisplayedOnETC


, $typaram)*> FromStream for $ty<T $(, $typaram)*>
        where
            T: FromStream $(+ $tbound1 $(+ $tbound2)*)*,
            $($typaram: $bound1 $(+ $bound2)*,)*
            T::Context: Copy
        {
            type Context = T::Context;

            async fn from_stream<D: Decoder>(context: Self::Context, decoder: &mut D) -> Result<Self, D::Error> {
                struct SeqVisitor<C, T $(, $typaram)*> {
                    context: C,
                    marker: PhantomData<$ty<T $(, $typaram)*>>,
                }

                #[async_trait]
                impl<T $(, $typaram)*> Visitor for SeqVisitor<T::Context, T $(, $typaram)*>
                where
                    T: FromStream $(+ $tbound1 $(+ $tbound2)*)*,
                    $($typaram: $bound1 $(+ $bound2)*,)*
                    T::Context: Copy
                {
                    type Value = $ty<T $(, $typaram)*>;

                    fn expecting() -> &'static str {
                        "a sequence"
                    }

                    async fn visit_seq<A: SeqAccess>(self, mut $access: A) -> Result<Self::Value, A::Error> {
                        let mut values = $with_capacity;

                        while let Some(value) = $access.next_element(self.context).await? {
                            $insert(&mut values, value);
                        }

                        Ok(values)
                    }
                }

                let visitor = SeqVisitor { context, marker: PhantomData };
                decoder.decode_seq(visitor).await
            }
        }
    }
}

decode_seq!(
    BinaryHeap<T: Ord>,
    seq,
    BinaryHeap::clear,
    BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())),
    BinaryHeap::reserve,
    BinaryHeap::push
);

decode_seq!(
    BTreeSet<T: Eq + Ord>,
    seq,
    BTreeSet::clear,
    BTreeSet::new(),
    nop_reserve,
    BTreeSet::insert
);

decode_seq!(
    LinkedList<T>,
    seq,
    LinkedList::clear,
    LinkedList::new(),
    nop_reserve,
    LinkedList::push_back
);

decode_seq!(
    HashSet<T: Eq + Hash, S: BuildHasher + Default + Send>,
    seq,
    HashSet::clear,
    HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()),
    HashSet::reserve,
    HashSet::insert
);

decode_seq!(
    VecDeque<T>,
    seq,
    VecDeque::clear,
    VecDeque::with_capacity(size_hint::cautious(seq.size_hint())),
    VecDeque::reserve,
    VecDeque::push_back
);

decode_seq!(
    Vec<T>,
    seq,
    Vec::clear,
    Vec::with_capacity(size_hint::cautious(seq.size_hint())),
    Vec::reserve,
    Vec::push
);

////////////////////////////////////////////////////////////////////////////////

struct ArrayVisitor<C, T> {
    context: C,
    marker: PhantomData<T>,
}

impl<C, T> ArrayVisitor<C, T> {
    fn new(context: C) -> Self {
        ArrayVisitor {
            context,
            marker: PhantomData,
        }
    }
}

#[async_trait]
impl<T: FromStream> Visitor for ArrayVisitor<T::Context, [T; 0]> {
    type Value = [T; 0];

    fn expecting() -> &'static str {
        "a zer


| 尺寸
(像素) | mAP姿态
50-95 | mAP姿态
50 | 速度
CPU ONNX
(毫秒) | 速度
A100 TensorRT
(毫秒) | 参数
(M) | 浮点数运算
(B) |
|----------------------------------------------------------------------------------------------------|-----------------|---------------------|------------------|-----------------------------|----------------------------------|----------------|-------------------|
| [YOLOv8n-姿态](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-pose.pt)       | 640             | 50.4                | 80.1             | 131.8                       | 1.18                             | 3.3            | 9.2               |
| [YOLOv8s-姿态](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-pose.pt)       | 640             | 60.0                | 86.2             | 233.2                       | 1.42                             | 11.6           | 30.2              |
| [YOLOv8m-姿态](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-pose.pt)       | 640             | 65.0                | 88.8             | 456.3                       | 2.00                             | 26.4           | 81.0              |
| [YOLOv8l-姿态](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-pose.pt)       | 640             | 67.6                | 90.0             | 784.5                       | 2.59                             | 44.4           | 168.6             |
| [YOLOv8x-姿态](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose.pt)       | 640             | 69.2                | 90.2             | 1607.1                      | 3.73                             | 69.4           | 263.2             |
| [YOLOv8x-姿态-p6](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose-p6.pt) | 1280            | 71.6                | 91.2             | 4088.7                      | 10.04                            | 99.1           | 1066.4            |

- **mAPval** 值适用于[COCO 关键点 val2017](http://cocodataset.org)数据集上的单模型单尺度。

通过执行 `yolo val pose data=coco-pose.yaml device=0` 来复现。
- **速度** 是在 [亚马逊EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/)实例上使用COCO val图像的平均值。

通过执行 `yolo val pose data=coco8-pose.yaml batch


fer for RawFramebufferObject {
    #[inline]
    fn handle(&self) -> Option<Handle> {
        Some(self.handle)
    }
}

pub struct RawFramebufferTargetRead {
    bound_fb: Cell<Option<Handle>>,
}

pub struct RawFramebufferTargetDraw {
    bound_fb: Cell<Option<Handle>>,
}

/// The primitive rendering mode for the `draw` call. See [here](https://www.khronos.org/opengl/wiki/Primitive)
/// for more information.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum DrawMode {
    Points = gl::POINTS,
    LineStrip = gl::LINE_STRIP,
    LineLoop = gl::LINE_LOOP,
    Lines = gl::LINES,
    LineStripAdjacency = gl::LINE_STRIP_ADJACENCY,
    LinesAdjacency = gl::LINES_ADJACENCY,
    TriangleStrip = gl::TRIANGLE_STRIP,
    TriangleFan = gl::TRIANGLE_FAN,
    Triangles = gl::TRIANGLES,
    TriangleStripAdjacency = gl::TRIANGLE_STRIP_ADJACENCY,
    TrianglesAdjacency = gl::TRIANGLES_ADJACENCY, // We don't support patches because that's an OpenGL 4 feature.
                                                  // Patches
}

pub struct RawBoundFramebufferRead<'a, F>
where
    F: 'a + RawFramebuffer,
{
    _fb: PhantomData<&'a F>,
    gl: &'a Gl,
}

pub struct RawBoundFramebufferDraw<'a, F>
where
    F: 'a + RawFramebuffer,
{
    _fb: PhantomData<&'a mut F>,
    gl: &'a Gl,
}

impl RawFramebufferObject {
    #[inline]
    pub fn new(gl: &Gl) -> RawFramebufferObject {
        unsafe {
            let mut handle = 0;
            gl.GenFramebuffers(1, &mut handle);
            let handle = Handle::new(handle).expect("Invalid handle returned from OpenGL");

            RawFramebufferObject {
                handle,
                _sendsync_optout: PhantomData,
            }
        }
    }

    pub unsafe fn delete(&mut self, state: &ContextState) {
        state.framebuffer_targets.unbind(self, &state.gl);
        state.gl.DeleteFramebuffers(1, &self.handle.get());
    }
}

impl RawFramebufferTargetRead {
    #[inline]
    pub fn new() -> RawFramebufferTargetRead {
        RawFramebufferTargetRead {
            bound_fb: Cell::new(None),
        }
    }

    #[inline]
    pub unsafe fn bind<'a, F>(
        &'a self,
        framebuffer: &'a F,
        gl: &'a Gl,
    ) -> RawBoundFramebufferRead<'a, F>
    where
        F: RawFramebuffer,
    {
        if self.bound_fb.get() != framebuffer.handle() {
            self.bound_fb.set(framebuffer.handle());
            gl.BindFramebuffer(
                gl::READ_FRAMEBUFFER,
                framebuffer.handle().map(|h| h.get()).unwrap_or(0),
            );
        }

        RawBoundFramebufferRead {
            _fb: PhantomData,
            gl,
        }
    }

    #[inline]
    pub unsafe fn reset_bind(&self, gl: &Gl) {
        self.bound_fb.set(None);
        gl.BindFramebuffer(gl::READ_FRAMEBUFFER, 0);
    }

    #[inline]
    pub fn bound_buffer(&self) -> &Cell<Option<Handle>> {
        &self.bound_fb
    }
}

impl RawFramebufferTargetDraw {
    #[inline]
    pub fn new() -> RawFramebufferTargetDraw {
        RawFramebufferTargetDraw {
            bound_fb: Cell::new(None),
        }
    }

    #[inline]
    pub unsafe fn bind<'a, F>(
        &'a self,
        framebuffer: &'a mut F,
        gl: &'a Gl,
    ) -> RawBoundFrame


: function(from, to){
			// summary:
			//		Reverts editor to "to" setting, from the undo stack.
			// tags:
			//		private
			this.setValue(to.text);
			var b = to.bookmark;
			if(!b){
				return;
			}
			this._moveToBookmark(b);
		},
		undo: function(){
			// summary:
			//		Handler for editor undo (ex: ctrl-z) operation
			// tags:
			//		private
			var ret = false;
			if(!this._undoRedoActive){
				this._undoRedoActive = true;
				this.endEditing(true);
				var s = this._steps.pop();
				if(s && this._steps.length > 0){
					this.focus();
					this._changeToStep(s, this._steps[this._steps.length - 1]);
					this._undoedSteps.push(s);
					this.onDisplayChanged();
					delete this._undoRedoActive;
					ret = true;
				}
				delete this._undoRedoActive;
			}
			return ret;
		},
		redo: function(){
			// summary:
			//		Handler for editor redo (ex: ctrl-y) operation
			// tags:
			//		private
			var ret = false;
			if(!this._undoRedoActive){
				this._undoRedoActive = true;
				this.endEditing(true);
				var s = this._undoedSteps.pop();
				if(s && this._steps.length > 0){
					this.focus();
					this._changeToStep(this._steps[this._steps.length - 1], s);
					this._steps.push(s);
					this.onDisplayChanged();
					ret = true;
				}
				delete this._undoRedoActive;
			}
			return ret;
		},
		endEditing: function(ignore_caret){
			// summary:
			//		Called to note that the user has stopped typing alphanumeric characters, if it's not already noted.
			//		Deals with saving undo; see editActionInterval parameter.
			// tags:
			//		private
			if(this._editTimer){
				this._editTimer = this._editTimer.remove();
			}
			if(this._inEditing){
				this._endEditing(ignore_caret);
				this._inEditing = false;
			}
		},

		_getBookmark: function(){
			// summary:
			//		Get the currently selected text
			// tags:
			//		protected
			var b = this.selection.getBookmark();
			var tmp = [];
			if(b && b.mark){
				var mark = b.mark;
				if(has("ie") < 9 || (has("ie") === 9 && has("quirks"))){
					// Try to use the pseudo range API on IE for better accuracy.
					var sel = rangeapi.getSelection(this.window);
					if(!lang.isArray(mark)){
						if(sel){
							var range;
							if(sel.rangeCount){
								range = sel.getRangeAt(0);
							}
							if(range){
								b.mark = range.cloneRange();
							}else{
								b.mark = this.selection.getBookmark();
							}
						}
					}else{
						// Control ranges (img, table, etc), handle differently.
						array.forEach(b.mark, function(n){
							tmp.push(rangeapi.getIndex(n, this.editNode).o);
						}, this);
						b.mark = tmp;
					}
				}
				try{
					if(b.mark && b.mark.startContainer){
						tmp = rangeapi.getIndex(b.mark.startContainer, this.editNode).o;
						b.mark = {startContainer: tmp,
							startOffset: b.mark.startOffset,
							endContainer: b.mark.endContainer === b.mark.startContainer ? tmp : rangeapi.getIndex(b.mark.endContainer, this.editNode).o,
							endOffset: b.mark.endOffset};


;
  Set<String> summons;
  Set<int> myRoomMusic;

  FreeLPParams freeLPParams;
  Map<String, Map<int, int>> luckyBagSvtScores;

  SaintQuartzPlan saintQuartzPlan;

  BattleSimUserData battleSim;

  String? lastImportId;

  User({
    String? id,
    this.name = 'Gudako',
    this.isGirl = true,
    this.region = Region.jp,
    Map<int, SvtStatus>? servants,
    Map<int, int>? dupServantMapping,
    List<UserPlan>? plans,
    this.sameEventPlan = true,
    int curSvtPlanNo = 0,
    Map<int, int>? items,
    Map<int, CraftStatus>? craftEssences,
    Map<int, CmdCodeStatus>? cmdCodes,
    Map<int, int>? mysticCodes,
    Set<String>? summons,
    Set<int>? myRoomMusic,
    Map<int, ClassBoardPlan>? classBoards,
    FreeLPParams? freeLPParams,
    Map<String, Map<int, int>>? luckyBagSvtScores,
    SaintQuartzPlan? saintQuartzPlan,
    BattleSimUserData? battleSim,
    this.lastImportId,
  }) : id = id ?? const Uuid().v4(),
       servants = servants ?? {},
       dupServantMapping = dupServantMapping ?? {},
       plans = List.generate(kSvtPlanMaxNum, (index) => plans?.getOrNull(index) ?? UserPlan()),
       _curSvtPlanNo = curSvtPlanNo.clamp(0, kSvtPlanMaxNum - 1),
       items = items ?? {},
       craftEssences = craftEssences ?? {},
       cmdCodes = cmdCodes ?? {},
       mysticCodes = mysticCodes ?? {},
       summons = summons ?? {},
       myRoomMusic = myRoomMusic ?? {},
       classBoards = classBoards ?? {},
       freeLPParams = freeLPParams ?? FreeLPParams(),
       luckyBagSvtScores = luckyBagSvtScores ?? {},
       saintQuartzPlan = saintQuartzPlan ?? SaintQuartzPlan(),
       battleSim = battleSim ?? BattleSimUserData();

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);

  UserPlan get curPlan_ => plans[curSvtPlanNo];
  Map<int, SvtPlan> get curSvtPlan => curPlan_.servants;
  UserPlan get _curEventPlan => plans[sameEventPlan ? 0 : curSvtPlanNo];

  void ensurePlanLarger() {
    curSvtPlan.forEach((key, plan) {
      plan.validate(servants[key]?.cur, db.gameData.servantsWithDup[key]);
    });
  }

  SvtPlan svtPlanOf(int no) => curSvtPlan.putIfAbsent(no, () => SvtPlan())..validate();

  SvtStatus svtStatusOf(int no) {
    final status = servants.putIfAbsent(no, () => SvtStatus())..cur.validate();
    return status;
  }

  CraftStatus ceStatusOf(int no) => craftEssences.putIfAbsent(no, () => CraftStatus());
  CmdCodeStatus ccStatusOf(int no) => cmdCodes.putIfAbsent(no, () => CmdCodeStatus());

  LimitEventPlan limitEventPlanOf(int eventId) =>
      _curEventPlan.limitEvents.putIfAbsent(eventId, () => LimitEventPlan());

  MainStoryPlan mainStoryOf(int warId) => _curEventPlan.mainStories.putIfAbsent(warId, () => MainStoryPlan());

  ExchangeTicketPlan ticketOf(int key) => _curEventPlan.tickets.putIfAbsent(key, () => ExchangeTicketPlan());

  ClassBoardPlan classBoardStatusOf(int boardId) => classBoards.putIfAbsent(b


   return -EINVAL;

                default:
                        assert_not_reached();
                }
        }

        return 1;
}

static int run(int argc, char *argv[]) {
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
        int r;

        static const Verb verbs[] = {
                { "list",     VERB_ANY, 2,        VERB_DEFAULT|VERB_ONLINE_ONLY, verb_list     },
                { "check",    VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY,              verb_check    },
                { "update",   VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY,              verb_update   },
                { "vacuum",   VERB_ANY, VERB_ANY, VERB_ONLINE_ONLY,              verb_vacuum   },
                { "features", VERB_ANY, 2,        VERB_ONLINE_ONLY,              verb_features },
                { "enable",   2,        VERB_ANY, VERB_ONLINE_ONLY,              verb_enable   },
                { "disable",  2,        VERB_ANY, VERB_ONLINE_ONLY,              verb_enable   },
                {}
        };

        setlocale(LC_ALL, "");
        log_setup();

        (void) signal(SIGWINCH, columns_lines_cache_reset);

        r = parse_argv(argc, argv);
        if (r <= 0)
                return r;

        r = bus_connect_transport(arg_transport, arg_host, RUNTIME_SCOPE_SYSTEM, &bus);
        if (r < 0)
                return bus_log_connect_error(r, arg_transport, RUNTIME_SCOPE_SYSTEM);

        if (arg_transport == BUS_TRANSPORT_LOCAL)
                polkit_agent_open();

        (void) sd_bus_set_allow_interactive_authorization(bus, true);

        return dispatch_verb(argc, argv, verbs, bus);
}

DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);


e as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.vanita5.twittnuker.util.database

import android.content.ContentResolver
import de.vanita5.twittnuker.annotation.FilterScope
import de.vanita5.twittnuker.extension.rawQueryReference
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.provider.TwidereDataStore.Filters.*

object ContentFiltersUtils {

    fun isFiltered(cr: ContentResolver, status: ParcelableStatus, filterRts: Boolean,
                   @FilterScope scope: Int, allowedKeywords: Array<String>? = null): Boolean {
        val query = isFilteredQuery(status.filter_users, status.filter_texts,
                status.filter_sources, status.filter_links, status.filter_names,
                status.filter_descriptions, filterRts, scope, allowedKeywords)
        return cr.rawQueryReference(query.first, query.second)?.use { (cur) ->
            cur.moveToFirst() && cur.getInt(0) != 0
        } ?: false
    }

    private fun isFilteredQuery(users: Array<UserKey>?, texts: String?, sources: Array<String>?,
            links: Array<String>?, names: Array<String>?, descriptions: String?,
            filterRts: Boolean, @FilterScope scope: Int, allowedKeywords: Array<String>? = null): Pair<String, Array<String>> {
        var numExpressions = 0;
        val selectionArgs = mutableListOf<String>()
        val queryBuilder = StringBuilder("SELECT ")

        fun addExpression(ruleTable: String, ruleField: String, scopeField: String,
                          @FilterScope expressionScope: Int, noScopeAsTrue: Boolean, matchType: Int,
                          value: String, extraWhereAppend: ((StringBuilder, MutableList<String>, String) -> Unit)? = null) {
            if (numExpressions > 0) {
                queryBuilder.append(" OR ")
            }
            selectionArgs.add(value)
            queryBuilder.append("1 IN (SELECT ? LIKE ")
            when (matchType) {
                LINE_MATCH -> {
                    queryBuilder.append("'%\\'||")
                    queryBuilder.append(ruleField)
                    queryBuilder.append("||'\\%'")
                }
                LINE_CONTAINS -> {
                    queryBuilder.append("'\\%'||")
                    queryBuilder.append(ruleField)
                    queryBuilder.append("||'%\\'")
                }
                CONTAINS -> {
                    queryBuilder.append("'%'||")
                    queryBuilder.append(ruleField)
                    queryBuilder.append("||'%'")
                }
            }
            queryBuilder.append(" FROM ")
            queryBuilder.append(ruleTable)
            queryBuilder.append(" WHERE ")
            if (noScopeAsTrue) {
                queryBuilder.append("(")
                queryBuilder.append(scopeField)
                queryBuilder.append(" = 0 OR ")
            }
            queryBuilder.append(scopeField)
            queryBuilder.append(" & ")
            queryBuilder.append(expressionScope)
            queryBuilder.append(" != 0")
            if (noScopeAsTrue) {
                queryBuilder.append(")")
            }
            extra